Sub topic 6
Connecting a real LLM backend
This chapter replaces the echo function with a call to a real language model. It assumes you can write Python generators, have gradio and openai installed (pip install gradio openai), and have an OPENAI_API_KEY environment variable set. You should also know the (message, history) contract and the messages-style history from earlier chapters. Any OpenAI-compatible client works the same way, so the pattern carries over to other providers.
The job of the chat function
Gradio knows nothing about language models. It calls your function with the newest user message and the prior turns, then displays whatever string your function returns or yields. Your function does three things:
- Build the list of messages the model expects.
- Call the model with streaming turned on.
- Yield the growing reply so the UI updates as text arrives.
Building the message list
Chat APIs expect a list of dictionaries, each with a role and a content. The roles are system, user, and assistant. With type="messages", Gradio's history already has this shape, so conversion is mostly copying.
def build_messages(system_prompt, history, message):
messages = [{"role": "system", "content": system_prompt}]
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
return messagesThree details matter here:
- The system message goes first and is never stored in
history. You add it on every call. - The new
messageis not inhistoryyet. You append it yourself. - Each history entry may carry extra keys, such as
metadata. Copying onlyroleandcontentkeeps the request valid, because the API rejects unknown fields on some providers.
A complete streaming chat app
This is the full app. The system prompt and temperature arrive as extra arguments from additional_inputs, which a later chapter covers in detail. Here they only show that the function signature grows with the inputs.
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history, system_prompt, temperature):
messages = [{"role": "system", "content": system_prompt}]
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,
temperature=temperature,
stream=True,
)
reply = ""
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
reply += delta
yield reply
demo = gr.ChatInterface(
fn=respond,
type="messages",
additional_inputs=[
gr.Textbox("You are a helpful assistant.", label="System prompt"),
gr.Slider(0, 1, value=0.7, label="Temperature"),
],
)
if __name__ == "__main__":
demo.launch()Run it with python app.py and open the printed local URL.
Why yield the whole reply, not the delta
Each yield replaces the displayed reply. It does not append to it. So you must yield the accumulated text (reply), not the latest delta. If you yield only the delta, the message shows one fragment at a time and ends as a few characters.
Why `or ""`
Streaming chunks do not always carry text. The first chunk often contains only the role, and the last contains a finish reason. In both cases delta.content is None. Without or "", the line reply += delta raises a TypeError.
Guarding against empty `choices`
Some OpenAI-compatible servers and Azure deployments send chunks with an empty choices list, for example a usage summary or a content-filter result. Indexing chunk.choices[0] then raises IndexError. A defensive version skips those chunks:
reply = ""
for chunk in stream:
if not chunk.choices:
continue
delta = chunk.choices[0].delta.content or ""
reply += delta
yield replyWhere the API key lives
OpenAI() reads OPENAI_API_KEY from the environment. Keep the key out of source files, notebooks, and version control. On Linux or macOS you can set it for one shell session:
export OPENAI_API_KEY="your-key-here"
python app.pyThe key stays on the server. Browser users never see it, because the model call happens inside your Python process.
Using a different provider
The OpenAI client accepts a base_url, so you can point it at any server that implements the same chat completions API. Examples include a local Ollama or vLLM server, or a hosted provider.
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:11434/v1", # a local Ollama server
api_key="ollama", # required by the client, ignored by Ollama
)Then change the model argument to a model name that server has loaded. The rest of respond stays the same. Providers differ in details, such as which parameters they accept, so check the provider's documentation if a request fails with a validation error.
Shared client and concurrency
Create the client once at module level, as the example does. Gradio runs your function for many users, and a shared client reuses its HTTP connection pool. The client object is safe to share across threads.
By default, Gradio runs a synchronous function in a worker thread pool, so one slow model call does not block other users from sending messages. The concurrency_limit parameter of queue() or of the event controls how many calls of the same function run at once. The default is 1 per event, which means two users chatting at the same moment are processed one after the other. You can raise the limit:
demo.queue(default_concurrency_limit=8)
demo.launch()Pick the limit based on your provider's rate limits and your server's capacity, not on how many users you hope to have.
History grows, and so does the cost
You send the full history on every turn. Token usage and latency grow with the conversation, and a long enough chat exceeds the model's context window, which produces an API error. A simple guard keeps only the most recent turns:
MAX_TURNS = 10 # user and assistant messages together: 2 * 5 exchanges
def trim(history):
return history[-MAX_TURNS:]Use it as trim(history) when building the list. Slicing by message count is crude. It can cut a conversation off mid-topic, and it ignores message length. Counting tokens, or summarizing old turns, is more accurate but needs more code. Always keep the system message outside the trimmed slice so it is never dropped.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AuthenticationError` on the first message | `OPENAI_API_KEY` is missing in the process that runs the app | Export the variable in the same shell, then restart |
| Reply shows only the last few characters | Yielding `delta` instead of the accumulated `reply` | Yield `reply` |
| `TypeError: can only concatenate str` | `delta.content` is `None` on some chunks | Use `or ""` |
| `IndexError: list index out of range` in the loop | A chunk had an empty `choices` list | Skip chunks where `not chunk.choices` |
| Error about unknown message fields | History entries carry extra keys | Copy only `role` and `content` |
| History looks like lists of pairs | `type="messages"` is missing in an older Gradio 5.x setup | Set `type="messages"` on `ChatInterface` |
| Context length exceeded after a long chat | Full history sent every turn | Trim or summarize history |
| The UI freezes between chunks | Blocking work inside the loop | Keep the loop to cheap operations |
Testing without spending tokens
Before wiring in a paid API, test the history handling with a stand-in that mimics streaming. This lets you confirm that the history reaches your function in the shape you expect.
import time
import gradio as gr
def fake_llm(message, history):
summary = f"Turn {len(history) // 2 + 1}. You said: {message}"
reply = ""
for word in summary.split():
reply += word + " "
time.sleep(0.05)
yield reply
gr.ChatInterface(fn=fake_llm, type="messages").launch()Send two or three messages and watch the turn number rise. If it stays at 1, your history is not being passed or kept as you expect. Once this behaves correctly, swap the loop for the real streaming call.
Exercise
Your streaming chat shows each new word replacing the previous one, so the finished message is a single word. The loop contains reply += delta and then yield delta. What is wrong, and what is the fix?
Show answer
Each yield replaces the whole displayed reply. Yielding delta shows only the latest fragment. Change it to yield reply, which holds the accumulated text.
Exercise
Your app crashes with TypeError partway through the first streamed reply, on the line reply += delta. Name the cause and write the corrected line that reads the delta.
Show answer
Some chunks, such as the first one carrying only the role and the final one carrying the finish reason, have delta.content set to None. Use delta = chunk.choices[0].delta.content or "".
Exercise
You want to run the same app against a local Ollama server instead of OpenAI. Which two parts of the code change, and which part stays the same?
Show answer
Create the client with base_url pointing to the local server (such as http://localhost:11434/v1) and a placeholder api_key, and change model to a model loaded on that server. The respond function's message building, streaming loop, and yield reply logic stay the same.