Sub topic 6
Connecting a real LLM backend
This chapter replaces the echo function with calls to a real model. It assumes you can write Python generators, have installed gradio and openai with pip, and know what a chat completions API does. It also assumes you have read the earlier chapters on the (message, history) contract, the messages-style history, and streaming.
The working model
Gradio does not talk to any model. It calls your function, and your function talks to the model. Your job is to translate between two formats:
- Gradio gives you
message(a string) andhistory(a list of dictionaries withroleandcontent). - The chat API expects a list of messages that starts with an optional system message and ends with the newest user message.
Because type="messages" history already uses role and content, the translation is small. Then you stream the model output and yield the growing reply.
A streaming OpenAI example
Set your key first, for example export OPENAI_API_KEY="..." in your terminal. The client reads it from the environment, so the key never appears in your code.
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def respond(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
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
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()The function does four things:
- Starts the list with a system message that sets the assistant's behavior.
- Copies each history entry, keeping only
roleandcontent. - Appends the new user message last.
- Accumulates each
deltaand yields the whole reply so far.
Common errors
- Yielding only the delta. Gradio replaces the displayed reply with each yielded value. If you yield just the new fragment, the chat shows one word at a time. Yield the accumulated
reply. - Forgetting
or "". Some chunks, such as the first and last, havecontentset toNone. AddingNoneto a string raises aTypeError. - Passing extra keys. Gradio history entries can carry additional fields, such as metadata. Some APIs reject unknown keys. Copying only
roleandcontentavoids that. - Using the old tuple format. With
type="tuples",historyis a list of[user, assistant]pairs, andh["role"]fails. Matchtype="messages"on bothChatInterfaceand your code. - Missing key. Without
OPENAI_API_KEY,OpenAI()raises an error when you create the client, so the app fails at startup instead of on the first message.
Using another provider
Any OpenAI-compatible server works with the same function. Pass base_url and a key when you create the client. The rest of respond stays the same.
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="not-needed")This example points at a local server that exposes an OpenAI-style endpoint. Change model in the create call to a model name that server provides.
Exercise
Your streaming chat shows only the last word of each reply, and the earlier words disappear. What is the likely cause, and how do you fix it?
Show answer
The function yields only the latest delta instead of the accumulated text. Gradio replaces the displayed reply with each yielded value. Keep a reply string, add each delta to it with reply += delta, and yield reply.
Exercise
Why does the code use chunk.choices[0].delta.content or "" instead of chunk.choices[0].delta.content?
Show answer
Some streamed chunks have content set to None. Adding None to a string raises a TypeError. The or "" fallback turns None into an empty string.