Sub topic 12
Accepting Files and Images in Chat
This chapter assumes you have a working gr.ChatInterface with a (message, history) function, you know the messages-style history format, and you can stream replies by yielding. Here you let users attach files and images. You then read them in your function, pass images to a vision-capable model, and restrict or reject uploads.
How multimodal mode changes the contract
By default, message is a plain string. Passing multimodal=True to gr.ChatInterface replaces the text box with a gr.MultimodalTextbox. This box accepts typed text and uploaded files, and optionally microphone recordings. Your function now receives a dictionary instead of a string.
| Row | Default | `multimodal=True` |
|---|---|---|
| `message` type | `str` | `dict` with keys `text` and `files` |
| `message["files"]` | not present | list of file paths on the server |
| History | text entries only | text entries plus file entries |
Gradio saves each upload into a temporary directory on the server. You receive paths to those saved copies, not the file bytes. You open the paths yourself.
A minimal multimodal app
This function reports what it received. Run it first to see the shape of the data.
import os
import gradio as gr
def respond(message, history):
text = message["text"]
files = message["files"]
if not files:
return f"You said: {text!r} (no files attached)"
names = [os.path.basename(path) for path in files]
sizes = [os.path.getsize(path) for path in files]
lines = [f"- {n}: {s} bytes" for n, s in zip(names, sizes)]
return f"You said: {text!r}\nFiles received:\n" + "\n".join(lines)
demo = gr.ChatInterface(
fn=respond,
type="messages",
multimodal=True,
)
if __name__ == "__main__":
demo.launch()Both keys are always present. text may be an empty string, and files may be an empty list. A user can send a file with no text, so code that assumes text is non-empty will break.
What the history looks like
In messages format, a turn with an upload becomes more than one history entry. Each file is stored as its own user entry, followed by the text entry. The content of a file entry is not a string. Depending on your Gradio version, it is a tuple holding the path, or a dictionary with a "path" key.
The history of one earlier turn might look like this:
[
{"role": "user", "content": {"path": "/tmp/gradio/abc/cat.png"}},
{"role": "user", "content": "What animal is this?"},
{"role": "assistant", "content": "It looks like a cat."},
]The exact file representation has changed between Gradio releases. Don't rely on one shape. Write one small helper that accepts all of them, and print history once in your own version to check.
def content_path(content):
"""Return a file path if this history content is a file, else None."""
if isinstance(content, (tuple, list)) and content:
return content[0]
if isinstance(content, dict) and "path" in content:
return content["path"]
return NoneText entries have a str as content, so content_path returns None for them.
Sending images to a vision model
Vision-capable chat APIs accept a message whose content is a list of parts, not a string. Each part is either text or an image. The OpenAI-style format accepts an image as a base64 data URL.
The function below does three things:
- It encodes image files as data URLs.
- It rebuilds earlier turns from history, merging file entries into the user text that follows them.
- It streams the reply.
import base64
import mimetypes
import gradio as gr
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def content_path(content):
if isinstance(content, (tuple, list)) and content:
return content[0]
if isinstance(content, dict) and "path" in content:
return content["path"]
return None
def image_part(path):
"""Return an image content part, or None if the file is not an image."""
mime, _ = mimetypes.guess_type(path)
if not mime or not mime.startswith("image/"):
return None
with open(path, "rb") as f:
encoded = base64.b64encode(f.read()).decode("ascii")
return {
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{encoded}"},
}
def build_messages(message, history):
messages = [{"role": "system", "content": "You are a helpful assistant."}]
pending = [] # image parts waiting for the user text that follows them
for entry in history:
path = content_path(entry["content"])
if path:
part = image_part(path)
if part:
pending.append(part)
continue
if entry["role"] == "user":
parts = pending + [{"type": "text", "text": entry["content"]}]
pending = []
messages.append({"role": "user", "content": parts})
else:
messages.append({"role": "assistant", "content": entry["content"]})
current = [image_part(p) for p in message["files"]]
current = [p for p in current if p]
current.append({"type": "text", "text": message["text"] or "Describe the image."})
messages.append({"role": "user", "content": current})
return messages
def respond(message, history):
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=build_messages(message, history),
stream=True,
)
reply = ""
for chunk in stream:
reply += chunk.choices[0].delta.content or ""
yield reply
demo = gr.ChatInterface(fn=respond, type="messages", multimodal=True)
if __name__ == "__main__":
demo.launch()Two details deserve attention:
- The
pendinglist handles the multi-entry history shape. A turn that contained only files, with no text, leaves its images pending. They then attach to the next user text, which is acceptable for a simple app. - The fallback
"Describe the image."covers a file-only send. Without it, the model receives an empty text part and some APIs reject that.
Restricting what users can upload
ChatInterface takes a textbox argument. Pass your own gr.MultimodalTextbox to control which files the user can attach.
import gradio as gr
def respond(message, history):
n = len(message["files"])
return f"Got {n} image(s) and the text {message['text']!r}."
box = gr.MultimodalTextbox(
file_types=["image"],
file_count="multiple",
placeholder="Type a message or attach images",
sources=["upload"],
)
demo = gr.ChatInterface(
fn=respond,
type="messages",
multimodal=True,
textbox=box,
)
if __name__ == "__main__":
demo.launch()The useful options are:
file_typestakes categories such as"image","audio","video", or extensions such as".pdf".file_countis"single","multiple", or"directory".sourcesselects the input sources, such as"upload"or"microphone".
The file_types filter is a convenience in the browser, not a security check. Always validate the files in your function too.
Validating uploads and reporting errors
Check files before you spend model tokens on them. Raise gr.Error to show a message to the user instead of a stack trace in your terminal.
import os
import gradio as gr
MAX_BYTES = 5 * 1024 * 1024
ALLOWED = {".png", ".jpg", ".jpeg", ".txt", ".md"}
def validate(files):
for path in files:
ext = os.path.splitext(path)[1].lower()
if ext not in ALLOWED:
raise gr.Error(f"{os.path.basename(path)}: type {ext or 'unknown'} is not allowed.")
if os.path.getsize(path) > MAX_BYTES:
raise gr.Error(f"{os.path.basename(path)} is larger than 5 MB.")
def respond(message, history):
validate(message["files"])
chunks = []
for path in message["files"]:
if path.lower().endswith((".txt", ".md")):
with open(path, "r", encoding="utf-8", errors="replace") as f:
chunks.append(f.read(2000))
summary = f"Read {len(chunks)} text file(s)."
return summary + ("\n\n" + "\n---\n".join(chunks) if chunks else "")
demo = gr.ChatInterface(fn=respond, type="messages", multimodal=True)
if __name__ == "__main__":
demo.launch()Reading only the first 2000 characters of a text file keeps the reply small. Passing errors="replace" stops a stray byte from crashing the read.
Multimodal input in gr.Blocks
In a custom layout you use gr.MultimodalTextbox and gr.Chatbot directly. The textbox's submit event passes the same {"text", "files"} dictionary. You are responsible for adding file entries to the chatbot history.
import gradio as gr
def add_user_turn(value, history):
for path in value["files"]:
history.append({"role": "user", "content": {"path": path}})
if value["text"]:
history.append({"role": "user", "content": value["text"]})
return history, gr.MultimodalTextbox(value=None, interactive=False)
def bot(history):
n_files = sum(1 for h in history if isinstance(h["content"], dict))
history.append({"role": "assistant", "content": f"I see {n_files} file(s) so far."})
return history
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
box = gr.MultimodalTextbox(file_count="multiple", placeholder="Say something or attach a file")
submitted = box.submit(add_user_turn, [box, chatbot], [chatbot, box])
done = submitted.then(bot, chatbot, chatbot)
done.then(lambda: gr.MultimodalTextbox(interactive=True), None, box)
if __name__ == "__main__":
demo.launch()The textbox is disabled while the bot works, then re-enabled in the final step. This prevents a second submission from interleaving with the first.
Common errors
TypeError: string indices must be integers. You enabledmultimodal=Truebut still treatmessageas a string. Usemessage["text"].KeyErroror a crash when history is replayed. Your code assumes every historycontentis a string. File entries are not. Use a helper likecontent_path.- The model never sees the image. Check that you sent a content list with an
image_urlpart. Also check that the model supports vision. A text-only model ignores or rejects image parts. - Files disappear after a restart. Uploads live in a temporary cache. Copy files you need to keep into your own storage.
- Large uploads time out. Limit sizes in your validation, and downscale images before encoding.
Security notes
Treat every upload as untrusted input. Check the extension and size, as shown above. Never execute uploaded files. Don't build shell commands from file names, since a user controls those too. If the app is public, add authentication, covered in a later chapter, so strangers can't fill your disk or run up your model bill.
Exercise
Your multimodal chat app crashes on the second message of a conversation, but the first message works. The first message included an uploaded image. Your function loops over history with entry["content"].strip(). What is the cause, and how do you fix it?
Show answer
In messages-style history, an uploaded file is stored as its own user entry whose content is a tuple or a dictionary holding the path, not a string. The first message worked because history was empty. On the second message the loop reaches the file entry and calls .strip() on a non-string. Fix it by testing the content first, for example with a helper such as content_path(entry["content"]). Handle file entries separately, either by encoding them as image parts or by skipping them, and call string methods only on entries whose content is a str.
Exercise
Write the gr.MultimodalTextbox that lets users attach up to several PDF files only, and say why you still need to validate files inside your chat function.
Show answer
Use gr.MultimodalTextbox(file_types=[".pdf"], file_count="multiple") and pass it to gr.ChatInterface(..., multimodal=True, textbox=box). The file_types setting only filters in the browser's file picker. A client can bypass it, for example by calling the API directly. So the function must still check extensions, sizes, and ideally the file contents before processing.