Sub topic 5
Streaming replies by yielding partial text
This chapter assumes you can write Python functions and generators, you have run a gr.ChatInterface app locally, and you know the (message, history) contract and the messages-style history from earlier chapters. It covers how streaming works in Gradio, how to write a streaming chat function, and the errors that most often appear.
Why stream
A language model can take several seconds to produce a full answer. If your function returns only when the answer is complete, the user sees a spinner and nothing else. Streaming shows text as it is produced. The total time is the same, but the wait before the first words appear is much shorter, and users can start reading right away.
Gradio supports this with no extra configuration. If your chat function is a generator, Gradio treats each yielded value as an updated version of the reply.
The working model
A normal function uses return once. A generator function uses yield any number of times. Gradio detects that fn is a generator and then does the following:
- It calls your function and gets a generator object.
- It takes each yielded value and sends it to the browser.
- The browser replaces the current assistant message with that value.
- When the generator finishes, Gradio marks the response as complete.
The key point is that each yield replaces the displayed reply. It does not append to it. So you must yield the full text so far, not only the newest piece.
A minimal streaming example
This function splits the echo into words and yields a longer string each time.
import time
import gradio as gr
def respond(message, history):
reply = ""
for word in f"You said: {message}".split():
reply += word + " "
time.sleep(0.1)
yield reply
gr.ChatInterface(fn=respond, type="messages").launch()The time.sleep(0.1) call only simulates a slow model. Remove it in real code. The type="messages" argument applies to Gradio 5.x. Newer versions may use this format by default.
Run the script, open the local URL, and send a message. The words appear one after another.
Return versus yield
| Aspect | `return` | `yield` |
|---|---|---|
| Function type | Ordinary function | Generator function |
| Updates sent | One, at the end | One per yield |
| What you pass | The complete reply | The reply so far |
| User sees | Spinner, then full text | Text growing in place |
| Stop button | Little visible effect | Stops further yields |
Accumulate, then yield
The most common mistake is yielding only the new piece:
def respond(message, history):
for word in message.split():
yield word # wrong: each yield replaces the previous oneThe user would see a single word that keeps changing. The fix is to keep an accumulator string, as in the example above, and yield that.
You can build the accumulator in two ways. Both work.
def respond_concat(message, history):
reply = ""
for ch in message:
reply += ch
yield reply
def respond_slice(message, history):
for i in range(1, len(message) + 1):
yield message[:i]Use concatenation when the pieces come from a source you do not control, such as a model API. Use slicing when you already hold the full text.
Streaming from a model API
Model APIs return chunks called deltas. Each delta holds a small piece of the reply, often a token or a few characters. Your job is to add each delta to the accumulator and yield the result. The example below uses the OpenAI client, but any client that streams chunks follows the same pattern.
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history):
messages = [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
stream=True,
)
reply = ""
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
reply += delta
yield reply
if __name__ == "__main__":
gr.ChatInterface(fn=respond, type="messages").launch()Two details matter here.
stream=Truemakes the API return an iterator of chunks instead of one response object.delta.content or ""handles chunks wherecontentisNone. The first chunk often carries only the role, and the last chunk often carries only a finish reason. Without the fallback,reply += Noneraises aTypeError.
The next chapters cover the LLM connection in more depth. Here the point is only the shape of the loop.
Edge cases
Yielding nothing
If the generator ends without yielding, the user sees an empty reply. This can happen when a model returns no content or when a branch of your code skips the loop. Add a fallback when it matters:
def respond(message, history):
reply = ""
for piece in get_pieces(message):
reply += piece
yield reply
if not reply:
yield "No response was generated."Here get_pieces stands for any function that returns an iterable of strings.
Yielding a value of the wrong type
For a basic ChatInterface, each yield should be a string. Yielding None or a number may show an empty message or raise an error. Convert values with str() if there is any doubt.
Exceptions in the middle of a stream
If your code raises an error after some yields, the user has already seen part of the reply. Gradio then shows an error state. Partial text may remain on screen or be replaced, depending on the version. To control what the user sees, catch the exception and raise gr.Error with a clear message. A later chapter covers this in detail.
Stopping a stream
The chat UI shows a stop button while a generator runs. Pressing it cancels the event, and Gradio stops pulling values from your generator. If your function holds a connection open, such as a streaming HTTP response, close it in a finally block so it is released:
def respond(message, history):
stream = open_stream(message)
try:
reply = ""
for chunk in stream:
reply += chunk
yield reply
finally:
stream.close()Here open_stream is a placeholder for your own function that returns a closable iterator.
Many users at once
Each running generator occupies a worker while it streams. Long streams from many users can queue behind each other. Gradio's queue controls how many events run at the same time through default_concurrency_limit, which you can set when you call demo.queue(). Raise the limit only if your backend can handle that many parallel calls.
Blocking calls inside the generator
A call such as time.sleep or a slow synchronous request blocks the worker thread that runs your function. This is fine for a single user. For many users, prefer a client that streams natively, and avoid doing heavy work between yields, because each delay adds to the gap the user perceives between updates.
Update rate
Yielding after every single token is usually fine, but it sends many small updates. If you see lag in the browser or heavy network traffic, batch the updates. This example yields at most about once every 50 milliseconds.
import time
import gradio as gr
def respond(message, history):
reply = ""
last = time.monotonic()
for word in ("This is a longer streamed answer " * 20).split():
reply += word + " "
now = time.monotonic()
if now - last >= 0.05:
last = now
yield reply
yield reply # always send the final textThe final yield reply is essential. Without it, the last words might never be shown.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Only one changing word appears | Yielding the delta, not the accumulated text | Yield the accumulator |
| Whole reply appears at once | Function uses `return`, or the client buffers the response | Use `yield`, and check that `stream=True` is set |
| `TypeError` on `+=` with `None` | Chunk has no content | Use `delta or ""` |
| Last words missing | Throttled loop skipped the final update | Yield once more after the loop |
| Blank reply | Generator ended without yielding | Add a fallback message |
| Server stays busy after Stop | Upstream stream is still open | Close it in `finally` |
Summary of the pattern
- Write the chat function as a generator.
- Keep a local string that holds the reply so far.
- Add each new piece to it.
- Yield the whole string after each addition.
- Yield once more at the end if you throttle updates.
- Clean up upstream resources in
finally.
Exercise
A chat function contains for token in tokens: yield token. The user sees only the latest token flash by instead of a growing sentence. What is wrong, and how do you fix it?
Show answer
Each yield replaces the displayed reply, so yielding only the new token shows one token at a time. Keep a local string such as reply = "", do reply += token inside the loop, and yield reply so the full text so far is sent each time.
Exercise
You throttle updates so the loop yields only when 50 ms have passed since the last yield. Users report that the last few words of some replies never appear. What is the cause, and what is the fix?
Show answer
The final chunks arrived within the 50 ms window, so the condition skipped them and the loop ended without sending them. Add a yield reply after the loop so the complete text is always sent.
Exercise
In a streaming model call, chunk.choices[0].delta.content is sometimes None. Write the line that safely adds it to reply, and explain why it is needed.
Show answer
reply += chunk.choices[0].delta.content or "". Some chunks, such as the first one with only the role or the last one with a finish reason, carry no content. Adding None to a string raises a TypeError, so the or "" fallback turns it into an empty string.