Sub topic 3
Handling, Extending, and Sharing a Gradio Chat App
Assume basic Python, functions, generators, pip, and familiarity with chat APIs. This chapter focuses on errors, custom layouts, sessions, files, programmatic access, and deployment.
Showing errors with `gr.Error`
Raise gr.Error when the user can fix the problem, such as missing input or an unavailable file. Gradio displays the message in the interface.
import gradio as gr
def respond(message, history):
if not message.strip():
raise gr.Error("Enter a message first.")
return f"You said: {message}"
gr.ChatInterface(respond, type="messages").launch()Catch backend errors rather than exposing stack traces or secrets:
try:
answer = call_model(message)
except Exception as exc:
raise gr.Error("The model is temporarily unavailable.") from excCustom layouts with `gr.Blocks`
Use gr.Blocks when you need controls beside the chat, custom event wiring, or multiple outputs. gr.Chatbot(type="messages") stores dictionaries with role and content.
import gradio as gr
def add_user(message, history, turns):
data = message or {}
text = data.get("text", "").strip()
files = data.get("files", [])
if not text and not files:
raise gr.Error("Add text or a file.")
shown = text or f"[{len(files)} file(s)]"
return {"text": "", "files": []}, history + [
{"role": "user", "content": shown}
], turns + 1
def reply(history, turns):
history.append({"role": "assistant", "content": f"Turn {turns} received."})
return history
with gr.Blocks() as demo:
chat = gr.Chatbot(type="messages")
message = gr.MultimodalTextbox(
file_types=["image", "text"], placeholder="Message or attach a file"
)
turns = gr.State(0)
message.submit(add_user, [message, chat, turns], [message, chat, turns]).then(
reply, [chat, turns], chat
)
demo.launch()gr.State keeps turns separate for each browser session. Do not use a module-level list for private conversation data.
The multimodal textbox provides text and uploaded files. Validate file type, size, and content before sending files to a model.
Calling and deploying the app
A gr.ChatInterface exposes a callable endpoint:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
print(client.predict("Hello", api_name="/chat"))Use share=True for a temporary public tunnel. For a server or container, bind explicitly and protect access:
import os
demo.launch(
server_name="0.0.0.0",
server_port=7860,
auth=(os.environ["CHAT_USER"], os.environ["CHAT_PASSWORD"]),
)Use HTTPS through a trusted reverse proxy, keep API keys in environment variables, restrict uploads, and avoid logging private messages.
Exercise
Why is gr.State safer than a global list for conversation turns?
Show answer
Gradio gives each session its own state value, while a global list could mix data from different users.