Sub topic 1
What Gradio Is and How to Launch an App
Prerequisites
You should know basic Python functions, generators, and how to run a script from a terminal. You should also understand that a chat API sends messages and receives replies.
What Gradio Is and How to Launch an App
Gradio is a Python library for building web interfaces around Python functions. It creates the browser interface and starts a local web server. You do not need to write HTML, CSS, or JavaScript.
Install it with:
pip install gradioA Gradio app launches with the launch() method:
import gradio as gr
def greet(name):
return f"Hello, {name}!"
demo = gr.Interface(fn=greet, inputs="text", outputs="text")
if __name__ == "__main__":
demo.launch()Run the script, then open the local URL shown in the terminal.
The Chat Function: Message and History In, Reply Out
A chat function receives the newest user message and the earlier conversation. Its basic contract is:
messageis the current user message as a string.historyis the previous conversation as a list.- The return value is the assistant's reply as a string.
def respond(message, history):
return f"You said: {message}"The function can ignore history for a simple demonstration. A real assistant usually sends both values to a model or uses them to implement conversation logic.
Your First Chat UI with `gr.ChatInterface`
gr.ChatInterface turns a function with this contract into a chat page:
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()When the user submits a message, Gradio calls respond. It displays the returned string as the assistant message and updates the conversation.
Understanding the History Format
With type="messages", each history item is a dictionary containing a role and content. Roles commonly include user, assistant, and system.
[
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]This format matches the message structure expected by many chat APIs. The current message is passed separately, so add it after history when constructing a request for a model.
Exercise
What two arguments must a basic gr.ChatInterface function accept?
Show answer
It accepts the current message and the previous conversation history, then returns the assistant reply.