import gradio as gr
with gr.Blocks() as demo:
gr.Chatbot(value=[
{"role": "user", "content": "Hello World"},
{"role": "assistant", "content": "Hey Gradio!"},
{"role": "user", "content": "❤️"},
{"role": "assistant", "content": "😍"}
],
type="messages")
demo.launch()
Description
Creates a chatbot that displays user-submitted messages and responses. Supports a subset of Markdown including bold, italics, code, tables. Also supports audio/video/image files, which are displayed in the Chatbot, and other kinds of files which are displayed as links. This component is usually used as an output component.
Behavior
The data format accepted by the Chatbot is dictated by the type parameter.
This parameter can take two values, 'tuples' and 'messages'.
The 'tuples' type is deprecated and will be removed in a future version of Gradio.
Message format
If the type is 'messages', then the data sent to/from the chatbot will be a list of dictionaries
with role and content keys. This format is compliant with the format expected by most LLM APIs (HuggingChat, OpenAI, Claude).
The role key is either 'user' or 'assistant' and the content key can be one of the following:
A string (markdown/html is also supported).
A dictionary with path and alt_text keys. In this case, the file at path will be displayed in the chat history. Image, audio, and video files are fully embedded and visualized in the chat bubble.
The path key can point to a valid publicly available URL. The alt_text key is optional but it’s good practice to provide alt text.
An instance of another Gradio component.
We will show examples for all three cases below -
defgenerate_response(history):# A plain text response
history.append({"role":"assistant", content="I am happy to provide you that report and plot."})# Embed the quaterly sales report in the chat
history.append({"role":"assistant", content={"path":"quaterly_sales.txt","alt_text":"Sales Report for Q2 2024"}})# Make a plot of sales data
history.append({"role":"assistant", content=gr.Plot(value=make_plot_from_file('quaterly_sales.txt'))})return history
For convenience, you can use the ChatMessage dataclass so that your text editor can give you autocomplete hints and typechecks.
from gradio import ChatMessage
defgenerate_response(history):
history.append(
ChatMessage(role="assistant",
content="How can I help you?"))return history
Tuples format
If type is 'tuples', then the data sent to/from the chatbot will be a list of tuples.
The first element of each tuple is the user message and the second element is the bot’s response.
Each element can be a string (markdown/html is supported),
a tuple (in which case the first element is a filepath that will be displayed in the chatbot),
or a gradio component (see the Examples section for more details).
Initialization
Parameters
Shortcuts
Class
Interface String Shortcut
Initialization
gradio.Chatbot
"chatbot"
Uses default values
Examples
Displaying Thoughts/Tool Usage
When type is messages, you can provide additional metadata regarding any tools used to generate the response.
This is useful for displaying the thought process of LLM agents. For example,
defgenerate_response(history):
history.append(
ChatMessage(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title":"🛠️ Used tool Weather API"}))return history
Would be displayed as following:
You can also specify metadata with a plain python dictionary,
defgenerate_response(history):
history.append(dict(role="assistant",
content="The weather API says it is 20 degrees Celcius in New York.",
metadata={"title":"🛠️ Used tool Weather API"}))return history
Using Gradio Components Inside gr.Chatbot
The Chatbot component supports using many of the core Gradio components (such as gr.Image, gr.Plot, gr.Audio, and gr.HTML) inside of the chatbot. Simply include one of these components in your list of tuples. Here’s an example:
import gradio as gr
defload():return[("Here's an audio", gr.Audio("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav")),("Here's an video", gr.Video("https://github.com/gradio-app/gradio/raw/main/demo/video_component/files/world.mp4"))]with gr.Blocks()as demo:
chatbot = gr.Chatbot()
button = gr.Button("Load audio and video")
button.click(load,None, chatbot)
demo.launch()
Demos
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.ClearButton([msg, chatbot])
def respond(message, chat_history):
bot_message = random.choice(["How are you?", "Today is a great day", "I'm very hungry"])
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
time.sleep(2)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
if __name__ == "__main__":
demo.launch()
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.ClearButton([msg, chatbot])
def respond(message, chat_history):
bot_message = random.choice(["How are you?", "Today is a great day", "I'm very hungry"])
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": bot_message})
time.sleep(2)
return "", chat_history
msg.submit(respond, [msg, chatbot], [msg, chatbot])
if __name__ == "__main__":
demo.launch()
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.Button("Clear")
def user(user_message, history: list):
return "", history + [{"role": "user", "content": user_message}]
def bot(history: list):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
history.append({"role": "assistant", "content": ""})
for character in bot_message:
history[-1]['content'] += character
time.sleep(0.05)
yield history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch()
import gradio as gr
import random
import time
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox()
clear = gr.Button("Clear")
def user(user_message, history: list):
return "", history + [{"role": "user", "content": user_message}]
def bot(history: list):
bot_message = random.choice(["How are you?", "I love you", "I'm very hungry"])
history.append({"role": "assistant", "content": ""})
for character in bot_message:
history[-1]['content'] += character
time.sleep(0.05)
yield history
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
bot, chatbot, chatbot
)
clear.click(lambda: None, None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch()
import gradio as gr
from gradio import ChatMessage
import time
def generate_response(history):
history.append(
ChatMessage(
role="user", content="What is the weather in San Francisco right now?"
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="In order to find the current weather in San Francisco, I will need to use my weather tool.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="API Error when connecting to weather service.",
metadata={"title": "💥 Error using tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="I will try again",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Weather 72 degrees Fahrenheit with 20% chance of rain.",
metadata={"title": "🛠️ Used tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Now that the API succeeded I can complete my task.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="It's a sunny day in San Francisco with a current temperature of 72 degrees Fahrenheit and a 20% chance of rain. Enjoy the weather!",
)
)
yield history
def like(evt: gr.LikeData):
print("User liked the response")
print(evt.index, evt.liked, evt.value)
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages", height=500, show_copy_button=True)
button = gr.Button("Get San Francisco Weather")
button.click(generate_response, chatbot, chatbot)
chatbot.like(like)
if __name__ == "__main__":
demo.launch()
import gradio as gr
from gradio import ChatMessage
import time
def generate_response(history):
history.append(
ChatMessage(
role="user", content="What is the weather in San Francisco right now?"
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="In order to find the current weather in San Francisco, I will need to use my weather tool.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="API Error when connecting to weather service.",
metadata={"title": "💥 Error using tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="I will try again",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Weather 72 degrees Fahrenheit with 20% chance of rain.",
metadata={"title": "🛠️ Used tool 'Weather'"},
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="Now that the API succeeded I can complete my task.",
)
)
yield history
time.sleep(0.25)
history.append(
ChatMessage(
role="assistant",
content="It's a sunny day in San Francisco with a current temperature of 72 degrees Fahrenheit and a 20% chance of rain. Enjoy the weather!",
)
)
yield history
def like(evt: gr.LikeData):
print("User liked the response")
print(evt.index, evt.liked, evt.value)
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages", height=500, show_copy_button=True)
button = gr.Button("Get San Francisco Weather")
button.click(generate_response, chatbot, chatbot)
chatbot.like(like)
if __name__ == "__main__":
demo.launch()
import gradio as gr
import os
import plotly.express as px
import random
# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
txt = """
Absolutely! The mycorrhizal network, often referred to as the "Wood Wide Web," is a symbiotic association between fungi and the roots of most plant species. Here’s a deeper dive into how it works and its implications:
### How It Works
1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.
2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.
3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.
### Benefits and Functions
1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.
2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.
3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.
### Ecological Impact
1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.
2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.
3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.
### Research and Discoveries
1. **Suzanne Simard's Work**: Ecologist Suzanne Simard’s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that "mother trees" (large, older trees) play a crucial role in nurturing younger plants.
2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.
### Practical Applications
1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.
2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.
The "Wood Wide Web" exemplifies the intricate and often hidden connections that sustain life on Earth. It’s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.
"""
def random_plot():
df = px.data.iris()
fig = px.scatter(
df,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
hover_data=["petal_width"],
)
return fig
color_map = {
"harmful": "crimson",
"neutral": "gray",
"beneficial": "green",
}
def html_src(harm_level):
return f"""
<div style="display: flex; gap: 5px;">
<div style="background-color: {color_map[harm_level]}; padding: 2px; border-radius: 5px;">
{harm_level}
</div>
</div>
"""
def print_like_dislike(x: gr.LikeData):
print(x.index, x.value, x.liked)
def random_bokeh_plot():
from bokeh.models import ColumnDataSource, Whisker
from bokeh.plotting import figure
from bokeh.sampledata.autompg2 import autompg2 as df
from bokeh.transform import factor_cmap, jitter
classes = sorted(df["class"].unique())
p = figure(
height=400,
x_range=classes,
background_fill_color="#efefef",
title="Car class vs HWY mpg with quintile ranges",
)
p.xgrid.grid_line_color = None
g = df.groupby("class")
upper = g.hwy.quantile(0.80)
lower = g.hwy.quantile(0.20)
source = ColumnDataSource(data=dict(base=classes, upper=upper, lower=lower))
error = Whisker(
base="base",
upper="upper",
lower="lower",
source=source,
level="annotation",
line_width=2,
)
error.upper_head.size = 20
error.lower_head.size = 20
p.add_layout(error)
p.circle(
jitter("class", 0.3, range=p.x_range),
"hwy",
source=df,
alpha=0.5,
size=13,
line_color="white",
color=factor_cmap("class", "Light6", classes),
)
return p
def random_matplotlib_plot():
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
countries = ["USA", "Canada", "Mexico", "UK"]
months = ["January", "February", "March", "April", "May"]
m = months.index("January")
r = 3.2
start_day = 30 * m
final_day = 30 * (m + 1)
x = np.arange(start_day, final_day + 1)
pop_count = {"USA": 350, "Canada": 40, "Mexico": 300, "UK": 120}
df = pd.DataFrame({"day": x})
for country in countries:
df[country] = x ** (r) * (pop_count[country] + 1)
fig = plt.figure()
plt.plot(df["day"], df[countries].to_numpy())
plt.title("Outbreak in " + "January")
plt.ylabel("Cases")
plt.xlabel("Days since Day 0")
plt.legend(countries)
return fig
def add_message(history, message):
for x in message["files"]:
history.append({"role": "user", "content": {"path": x}})
if message["text"] is not None:
history.append({"role": "user", "content": message["text"]})
return history, gr.MultimodalTextbox(value=None, interactive=False)
def bot(history, response_type):
msg = {"role": "assistant", "content": ""}
if response_type == "plot":
content = gr.Plot(random_plot())
elif response_type == "bokeh_plot":
content = gr.Plot(random_bokeh_plot())
elif response_type == "matplotlib_plot":
content = gr.Plot(random_matplotlib_plot())
elif response_type == "gallery":
content = gr.Gallery(
[os.path.join("files", "avatar.png"), os.path.join("files", "avatar.png")]
)
elif response_type == "image":
content = gr.Image(os.path.join("files", "avatar.png"))
elif response_type == "video":
content = gr.Video(os.path.join("files", "world.mp4"))
elif response_type == "audio":
content = gr.Audio(os.path.join("files", "audio.wav"))
elif response_type == "audio_file":
content = {"path": os.path.join("files", "audio.wav"), "alt_text": "description"}
elif response_type == "image_file":
content = {"path": os.path.join("files", "avatar.png"), "alt_text": "description"}
elif response_type == "video_file":
content = {"path": os.path.join("files", "world.mp4"), "alt_text": "description"}
elif response_type == "txt_file":
content = {"path": os.path.join("files", "sample.txt"), "alt_text": "description"}
elif response_type == "html":
content = gr.HTML(
html_src(random.choice(["harmful", "neutral", "beneficial"]))
)
else:
content = txt
msg["content"] = content
history.append(msg)
return history
fig = random_plot()
with gr.Blocks(fill_height=True) as demo:
chatbot = gr.Chatbot(
elem_id="chatbot",
type="messages",
bubble_full_width=False,
scale=1,
show_copy_button=True,
avatar_images=(
None, # os.path.join("files", "avatar.png"),
os.path.join("files", "avatar.png"),
),
)
response_type = gr.Radio(
[
"audio_file",
"image_file",
"video_file",
"txt_file",
"plot",
"matplotlib_plot",
"bokeh_plot",
"image",
"text",
"gallery",
"video",
"audio",
"html",
],
value="text",
label="Response Type",
)
chat_input = gr.MultimodalTextbox(
interactive=True,
placeholder="Enter message or upload file...",
show_label=False,
)
chat_msg = chat_input.submit(
add_message, [chatbot, chat_input], [chatbot, chat_input]
)
bot_msg = chat_msg.then(
bot, [chatbot, response_type], chatbot, api_name="bot_response"
)
bot_msg.then(lambda: gr.MultimodalTextbox(interactive=True), None, [chat_input])
chatbot.like(print_like_dislike, None, None)
if __name__ == "__main__":
demo.launch()
import gradio as gr
import os
import plotly.express as px
import random
# Chatbot demo with multimodal input (text, markdown, LaTeX, code blocks, image, audio, & video). Plus shows support for streaming text.
txt = """
Absolutely! The mycorrhizal network, often referred to as the "Wood Wide Web," is a symbiotic association between fungi and the roots of most plant species. Here’s a deeper dive into how it works and its implications:
### How It Works
1. **Symbiosis**: Mycorrhizal fungi attach to plant roots, extending far into the soil. The plant provides the fungi with carbohydrates produced via photosynthesis. In return, the fungi help the plant absorb water and essential nutrients like phosphorus and nitrogen from the soil.
2. **Network Formation**: The fungal hyphae (thread-like structures) connect individual plants, creating an extensive underground network. This network can link many plants together, sometimes spanning entire forests.
3. **Communication**: Trees and plants use this network to communicate and share resources. For example, a tree under attack by pests can send chemical signals through the mycorrhizal network to warn neighboring trees. These trees can then produce defensive chemicals to prepare for the impending threat.
### Benefits and Functions
1. **Resource Sharing**: The network allows for the redistribution of resources among plants. For instance, a large, established tree might share excess nutrients and water with smaller, younger trees, promoting overall forest health.
2. **Defense Mechanism**: The ability to share information about pests and diseases enhances the resilience of plant communities. This early warning system helps plants activate their defenses before they are directly affected.
3. **Support for Seedlings**: Young seedlings, which have limited root systems, benefit immensely from the mycorrhizal network. They receive nutrients and water from larger plants, increasing their chances of survival and growth.
### Ecological Impact
1. **Biodiversity**: The mycorrhizal network supports biodiversity by fostering a cooperative environment. Plants of different species can coexist and thrive because of the shared resources and information.
2. **Forest Health**: The network enhances the overall health of forests. By enabling efficient nutrient cycling and supporting plant defenses, it contributes to the stability and longevity of forest ecosystems.
3. **Climate Change Mitigation**: Healthy forests act as significant carbon sinks, absorbing carbon dioxide from the atmosphere. The mycorrhizal network plays a critical role in maintaining forest health and, consequently, in mitigating climate change.
### Research and Discoveries
1. **Suzanne Simard's Work**: Ecologist Suzanne Simard’s research has been pivotal in uncovering the complexities of the mycorrhizal network. She demonstrated that trees of different species can share resources and that "mother trees" (large, older trees) play a crucial role in nurturing younger plants.
2. **Implications for Conservation**: Understanding the mycorrhizal network has significant implications for conservation efforts. It highlights the importance of preserving not just individual trees but entire ecosystems, including the fungal networks that sustain them.
### Practical Applications
1. **Agriculture**: Farmers and horticulturists are exploring the use of mycorrhizal fungi to improve crop yields and soil health. By incorporating these fungi into agricultural practices, they can reduce the need for chemical fertilizers and enhance plant resilience.
2. **Reforestation**: In reforestation projects, introducing mycorrhizal fungi can accelerate the recovery of degraded lands. The fungi help establish healthy plant communities, ensuring the success of newly planted trees.
The "Wood Wide Web" exemplifies the intricate and often hidden connections that sustain life on Earth. It’s a reminder of the profound interdependence within natural systems and the importance of preserving these delicate relationships.
"""
def random_plot():
df = px.data.iris()
fig = px.scatter(
df,
x="sepal_width",
y="sepal_length",
color="species",
size="petal_length",
hover_data=["petal_width"],
)
return fig
color_map = {
"harmful": "crimson",
"neutral": "gray",
"beneficial": "green",
}
def html_src(harm_level):
return f"""
Event listeners allow you to respond to user interactions with the UI
components you've defined in a Gradio Blocks app. When a user interacts with
an element, such as changing a slider value or uploading an image, a
function is called.
Supported Event Listeners
The Chatbot
component supports the following event listeners. Each event listener takes the
same parameters, which are listed in the
Event Parameters table below.
Listener
Description
Chatbot.change(fn, ···)
Triggered when the value of the Chatbot changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See .input() for a listener that is only triggered by user input.
Chatbot.select(fn, ···)
Event listener for when the user selects or deselects the Chatbot. Uses event data gradio.SelectData to carry value referring to the label of the Chatbot, and selected to refer to state of the Chatbot. See EventData documentation on how to use this event data
Chatbot.like(fn, ···)
This listener is triggered when the user likes/dislikes from within the Chatbot. This event has EventData of type gradio.LikeData that carries information, accessible through LikeData.index and LikeData.value. See EventData documentation on how to use this event data.