Sub topic 2
Streaming Replies with Gradio
Assume you know basic Python functions, generators, pip, and the idea of sending messages to an LLM API. A generator is a function that returns values over time with yield. Gradio displays each yielded value as the current assistant reply.
Streaming replies by yielding partial text
A normal chat function returns one complete string. A streaming function yields increasingly longer strings:
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()Each yield replaces the displayed reply. The delay makes the behavior visible. A real LLM usually yields chunks as they arrive from the network.
Connecting a real LLM backend
Install the client and set OPENAI_API_KEY in your environment. The function converts Gradio's history into the message format expected by the API.
import gradio as gr
from openai import OpenAI
client = OpenAI()
def respond(message, history, system_prompt, temperature):
messages = [{"role": "system", "content": system_prompt}]
messages += [
{"role": item["role"], "content": item["content"]}
for item in history
]
messages.append({"role": "user", "content": message})
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
temperature=temperature,
stream=True,
)
reply = ""
for chunk in stream:
reply += chunk.choices[0].delta.content or ""
yield replyControls and presentation
additional_inputs supplies values after message and history. The system prompt guides the model. Temperature controls variation: lower values are more predictable.
demo = gr.ChatInterface(
fn=respond,
type="messages",
title="Helpful Chat",
description="Ask a question and watch the answer stream.",
examples=["Explain recursion", "Write a short poem"],
additional_inputs=[
gr.Textbox("You are a concise, helpful assistant.", label="System prompt"),
gr.Slider(0, 1, value=0.7, label="Temperature"),
],
theme=gr.themes.Soft(),
)
if __name__ == "__main__":
demo.launch()Exercise
Why must a streaming chat function use yield instead of one final return?
Show answer
yield gives Gradio partial results while the backend is still working, so the browser can update incrementally.