Sub topic 12
Accepting files and images in chat
This chapter assumes you have a working gr.ChatInterface with a (message, history) function and know the messages-style history format from earlier chapters. You should also be able to call a vision-capable model through an OpenAI-compatible client.
Turning on multimodal input
By default the chat box accepts text only. Pass multimodal=True and the textbox becomes a combined input with an upload button. The type of message changes with it. Your function no longer receives a string. It receives a dictionary with two keys:
text: the typed string, which may be empty.files: a list of local file paths where Gradio saved the uploads.
Here is a minimal app that reports what it received:
import gradio as gr
def respond(message, history):
text = message["text"]
files = message["files"]
if not files:
return f"You said: {text}"
names = ", ".join(files)
return f"You said: {text}\nYou attached {len(files)} file(s): {names}"
demo = gr.ChatInterface(
fn=respond,
type="messages",
multimodal=True,
)
if __name__ == "__main__":
demo.launch()Limiting what users can upload
Uploads are open-ended by default. You can restrict them with a gr.MultimodalTextbox passed as textbox:
import gradio as gr
box = gr.MultimodalTextbox(
file_types=["image", ".pdf"],
file_count="multiple",
placeholder="Ask a question or attach an image",
)
def respond(message, history):
return f"Received {len(message['files'])} file(s)."
gr.ChatInterface(
fn=respond, type="messages", multimodal=True, textbox=box
).launch()file_types accepts categories such as "image" and extensions such as ".pdf". Treat this as a convenience filter. It is not a security control, so validate files again on the server before you process them.
Sending an image to a vision model
Most vision APIs take images inline as base64 data URLs. This function reads the uploaded file and builds a content list with a text part and an image part:
import base64
import mimetypes
import gradio as gr
from openai import OpenAI
client = OpenAI()
def to_data_url(path):
mime = mimetypes.guess_type(path)[0] or "image/png"
with open(path, "rb") as f:
encoded = base64.b64encode(f.read()).decode()
return f"data:{mime};base64,{encoded}"
def respond(message, history):
content = [{"type": "text", "text": message["text"] or "Describe this image."}]
for path in message["files"]:
content.append(
{"type": "image_url", "image_url": {"url": to_data_url(path)}}
)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": content}],
stream=True,
)
reply = ""
for chunk in stream:
reply += chunk.choices[0].delta.content or ""
yield reply
gr.ChatInterface(fn=respond, type="messages", multimodal=True).launch()This sends only the current turn. Earlier turns are left out on purpose, because of the history gotcha below.
What history looks like with files
Past uploads appear in history as their own entries. Their content is not a string. It is a dictionary containing a path key (older versions used a tuple). Code that assumes every content is a string, like the loop in the LLM chapter, will fail or send garbage to the model. Filter defensively:
def text_only(history):
return [
{"role": h["role"], "content": h["content"]}
for h in history
if isinstance(h["content"], str)
]To keep images in context, convert each file entry into an image_url part. Keep in mind that images are re-sent on every turn, which raises cost and latency.
Common errors
TypeError: string indices must be integers: you enabledmultimodal=Truebut still treatmessageas a string.- The model rejects the request: the model you chose does not support images, or the file is not a supported format.
- Empty
textwith files attached: supply a default prompt, as the example does.
Exercise
With multimodal=True, what does the message argument contain, and why must you be careful when you build an LLM message list from history?
Show answer
message is a dictionary with text (a string) and files (a list of file paths). History entries for uploaded files have a non-string content (a dictionary with a path), so you must skip them or convert them to the model's image format before sending history to an API that expects strings.