Hi LiveKit team, I'm using openai.LLM(model="gpt-4...
# ask-ai
s
Hi LiveKit team, I'm using openai.LLM(model="gpt-4o").chat(chat_ctx=chat_ctx) in my agent and need to collect the complete response text from the streaming chunks to parse it for special markers. What's the correct attribute name to access the text content from each chunk? python Apply llm = openai.LLM(model="gpt-4o") llm_stream = llm.chat(_chat_ctx_=chat_ctx) full_response = "" async for chunk in llm_stream: full_response += chunk.??? # What attribute contains the text? I tried chunk.content but got AttributeError: 'ChatChunk' object has no attribute 'content'. Thanks!
t
Thanks for reaching out, Jason. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
When you want to grab the text content from each streaming chunk in your code, you’ll want to use
chunk.choices[0].delta.content
. But just a heads-up—there are a few important things to watch out for to make sure everything runs smoothly: • Make sure
chunk.choices
isn’t empty or
None
. • Double-check that
chunk.choices[0].delta
isn’t `None`—this can happen sometimes, like when content gets filtered. • Also, confirm that
chunk.choices[0].delta.content
isn’t
None
or empty before you add it to your response. Here’s a simple example to help you handle the stream safely:
Copy code
full_response = ""
async for chunk in llm_stream:
    if chunk.choices:
        content = getattr(chunk.choices[0].delta, 'content', None)
        if content:
            full_response += content
Using this way, your code will gracefully handle those tricky edge cases without a hitch. Sources: livekit-plugins/livekit-plugins-google/livekit/plugins/google/llm.py | pipeline-llm/replacing_llm_output.py