text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 190
values | source_page_title stringclasses 190
values |
|---|---|---|---|
Once your Gradio app is running, you can share the URL with others so they can try out the API through a friendly web interface—no code required. For even more power, you can launch the app as an MCP (Model Control Protocol) server using [Gradio's MCP integration](https://www.gradio.app/guides/building-mcp-server-with-... | Next steps | https://gradio.app/guides/from-openapi-spec | Other Tutorials - From Openapi Spec Guide |
A virtual environment in Python is a self-contained directory that holds a Python installation for a particular version of Python, along with a number of additional packages. This environment is isolated from the main Python installation and other virtual environments. Each environment can have its own independent set ... | Virtual Environments | https://gradio.app/guides/installing-gradio-in-a-virtual-environment | Other Tutorials - Installing Gradio In A Virtual Environment Guide |
To install Gradio on a Windows system in a virtual environment, follow these steps:
1. **Install Python**: Ensure you have Python 3.10 or higher installed. You can download it from [python.org](https://www.python.org/). You can verify the installation by running `python --version` or `python3 --version` in Command Pro... | Installing Gradio on Windows | https://gradio.app/guides/installing-gradio-in-a-virtual-environment | Other Tutorials - Installing Gradio In A Virtual Environment Guide |
The installation steps on MacOS and Linux are similar to Windows but with some differences in commands.
1. **Install Python**:
Python usually comes pre-installed on MacOS and most Linux distributions. You can verify the installation by running `python --version` in the terminal (note that depending on how Python is... | Installing Gradio on MacOS/Linux | https://gradio.app/guides/installing-gradio-in-a-virtual-environment | Other Tutorials - Installing Gradio In A Virtual Environment Guide |
Chatbots are a popular application of large language models (LLMs). Using Gradio, you can easily build a chat application and share that with your users, or try it yourself using an intuitive UI.
This tutorial uses `gr.ChatInterface()`, which is a high-level abstraction that allows you to create your chatbot UI fast, ... | Introduction | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
If you have a chat server serving an OpenAI-API compatible endpoint (such as Ollama), you can spin up a ChatInterface in a single line of Python. First, also run `pip install openai`. Then, with your own URL, model, and optional token:
```python
import gradio as gr
gr.load_chat("http://localhost:11434/v1/", model="ll... | Note for OpenAI-API compatible endpoints | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
To create a chat application with `gr.ChatInterface()`, the first thing you should do is define your **chat function**. In the simplest case, your chat function should accept two arguments: `message` and `history` (the arguments can be named anything, but must be in this order).
- `message`: a `str` representing the u... | Defining a chat function | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
t take user input or the previous history into account! Here's another simple example showing how to incorporate a user's input as well as the history.
```python
import gradio as gr
def alternatingly_agree(message, history):
if len([h for h in history if h['role'] == "assistant"]) % 2 == 0:
return f"Yes, ... | Defining a chat function | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
In your chat function, you can use `yield` to generate a sequence of partial responses, each replacing the previous ones. This way, you'll end up with a streaming chatbot. It's that simple!
```python
import time
import gradio as gr
def slow_echo(message, history):
for i in range(len(message)):
time.sleep(... | Streaming chatbots | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
If you're familiar with Gradio's `gr.Interface` class, the `gr.ChatInterface` includes many of the same arguments that you can use to customize the look and feel of your Chatbot. For example, you can:
- add a title and description above your chatbot using `title` and `description` arguments.
- add a theme or custom cs... | Customizing the Chat UI | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
le of how we to apply the parameters we've discussed in this section:
```python
import gradio as gr
def yes_man(message, history):
if message.endswith("?"):
return "Yes"
else:
return "Ask me anything!"
gr.ChatInterface(
yes_man,
chatbot=gr.Chatbot(height=300),
textbox=gr.Textbox(p... | Customizing the Chat UI | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may want to add multimodal capabilities to your chat interface. For example, you may want users to be able to upload images or files to your chatbot and ask questions about them. You can make your chatbot "multimodal" by passing in a single parameter (`multimodal=True`) to the `gr.ChatInterface` class.
When `multi... | Multimodal Chat Interface | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
ox` to the `textbox` parameter. You can customize the `MultimodalTextbox` further by passing in the `sources` parameter, which is a list of sources to enable. Here's an example that illustrates how to set up and customize and multimodal chat interface:
```python
import gradio as gr
def count_images(message, history... | Multimodal Chat Interface | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may want to add additional inputs to your chat function and expose them to your users through the chat UI. For example, you could add a textbox for a system prompt, or a slider that sets the number of tokens in the chatbot's response. The `gr.ChatInterface` class supports an `additional_inputs` parameter which can ... | Additional Inputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
s to the `examples` parameter, where each inner list represents one sample, and each inner list should be `1 + len(additional_inputs)` long. The first element in the inner list should be the example value for the chat message, and each subsequent element should be an example value for one of the additional inputs, in o... | Additional Inputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
In the same way that you can accept additional inputs into your chat function, you can also return additional outputs. Simply pass in a list of components to the `additional_outputs` parameter in `gr.ChatInterface` and return additional values for each component from your chat function. Here's an example that extracts ... | Additional Outputs | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
We mentioned earlier that in the simplest case, your chat function should return a `str` response, which will be rendered as Markdown in the chatbot. However, you can also return more complex responses as we discuss below:
**Returning files or Gradio components**
Currently, the following Gradio components can be dis... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
ma of the `gr.ChatMessage` data class as well as two internal typed dictionaries:
```py
MessageContent = Union[str, FileDataDict, FileData, Component]
@dataclass
class ChatMessage:
content: MessageContent | list[MessageContent]
metadata: MetadataDict = None
options: list[OptionDict] = None
class Metada... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
corresponding to the `options` key should be a list of dictionaries, each with a `value` (a string that is the value that should be sent to the chat function when this response is clicked) and an optional `label` (if provided, is the text displayed as the preset response instead of the `value`).
This example illustr... | Returning Complex Responses | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You may wish to modify the value of the chatbot with your own events, other than those prebuilt in the `gr.ChatInterface`. For example, you could create a dropdown that prefills the chat history with certain conversations or add a separate button to clear the conversation history. The `gr.ChatInterface` supports these ... | Modifying the Chatbot Value Directly | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
Once you've built your Gradio chat interface and are hosting it on [Hugging Face Spaces](https://hf.space) or somewhere else, then you can query it with a simple API. The API route will be the name of the function you pass to the ChatInterface. So if `gr.ChatInterface(respond)`, then the API route is `/respond`. The en... | Using Your Chatbot via API | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
You can enable persistent chat history for your ChatInterface, allowing users to maintain multiple conversations and easily switch between them. When enabled, conversations are stored locally and privately in the user's browser using local storage. So if you deploy a ChatInterface e.g. on [Hugging Face Spaces](https://... | Chat History | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
To gather feedback on your chat model, set `gr.ChatInterface(flagging_mode="manual")` and users will be able to thumbs-up or thumbs-down assistant responses. Each flagged response, along with the entire chat history, will get saved in a CSV file in the app working directory (this can be configured via the `flagging_dir... | Collecting User Feedback | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
Now that you've learned about the `gr.ChatInterface` class and how it can be used to create chatbot UIs quickly, we recommend reading one of the following:
* [Our next Guide](../guides/chatinterface-examples) shows examples of how to use `gr.ChatInterface` with popular LLM libraries.
* If you'd like to build very cust... | What's Next? | https://gradio.app/guides/creating-a-chatbot-fast | Chatbots - Creating A Chatbot Fast Guide |
**Important Note**: if you are getting started, we recommend using the `gr.ChatInterface` to create chatbots -- its a high-level abstraction that makes it possible to create beautiful chatbot applications fast, often with a single line of code. [Read more about it here](/guides/creating-a-chatbot-fast).
This tutorial ... | Introduction | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
Let's start with recreating the simple demo above. As you may have noticed, our bot simply randomly responds "How are you?", "Today is a great day", or "I'm very hungry" to any input. Here's the code to create this with Gradio:
$code_chatbot_simple
There are three Gradio components here:
- A `Chatbot`, whose value s... | A Simple Chatbot Demo | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
There are several ways we can improve the user experience of the chatbot above. First, we can stream responses so the user doesn't have to wait as long for a message to be generated. Second, we can have the user message appear immediately in the chat history, while the chatbot's response is being generated. Here's the ... | Add Streaming to your Chatbot | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
The `gr.Chatbot` component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold **That's cool!**, like this:
```py
def bot(history):
response = {"role": "assistant", "content": "**That's cool!**"}
history.append(r... | Adding Markdown, Images, Audio, or Videos | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
ggingface.co/spaces/gradio/chatbot_streaming): A streaming chatbot demo built with `gr.Chatbot` and Blocks.
- [gradio/chatbot_examples](https://huggingface.co/spaces/gradio/chatbot_examples): A chatbot that presents new visitors with a list of multimodal examples they can use to start the conversation.
| Adding Markdown, Images, Audio, or Videos | https://gradio.app/guides/creating-a-custom-chatbot-with-blocks | Chatbots - Creating A Custom Chatbot With Blocks Guide |
The Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API.
Because Gradio's API is very flexible, you can create D... | How does it work? | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
* Install the latest version of `gradio` and the `discord.py` libraries:
```
pip install --upgrade gradio discord.py~=2.0
```
* Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/g... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
CORD BOT TOKEN HERE
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
```
Now, run this file: `python bot.py`, which should run and print a message like:
```text
We have logged in as GradioPlaygroundBot1451
```
If that is working,... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']):
image_path = download_image(attachment)
files.append(handle_file(image_path))
break
Stream the responses to the channel
for response in gradio_client.su... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
c example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps.

If you build a Discord bot from a Gra... | Prerequisites | https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app | Chatbots - Creating A Discord Bot From A Gradio App Guide |
Let's start by using `llama-index` on top of `openai` to build a RAG chatbot on any text or PDF files that you can demo and share in less than 30 lines of code. You'll need to have an OpenAI key for this example (keep reading for the free, open-source equivalent!)
$code_llm_llamaindex
| Llama Index | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Here's an example using `langchain` on top of `openai` to build a general-purpose chatbot. As before, you'll need to have an OpenAI key for this example.
$code_llm_langchain
Tip: For quick prototyping, the community-maintained <a href='https://github.com/AK391/langchain-gradio'>langchain-gradio repo</a> makes it eve... | LangChain | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, we could also use the `openai` library directy. Here a similar example to the LangChain , but this time with streaming as well:
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/openai-gradio'>openai-gradio library</a> makes it even easier to build chatbots on top of OpenAI models.
| OpenAI | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Of course, in many cases you want to run a chatbot locally. Here's the equivalent example using the SmolLM2-135M-Instruct model using the Hugging Face `transformers` library.
$code_llm_hf_transformers
| Hugging Face `transformers` | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The SambaNova Cloud API provides access to full-precision open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the SambaNova API
$code_llm_sambanova
Tip: For quick prototyping, the <a href='https://github.com/gradio-app/sambanova-gradio'>sambanova-gradio library</a> mak... | SambaNova | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The Hyperbolic AI API provides access to many open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the Hyperbolic
$code_llm_hyperbolic
Tip: For quick prototyping, the <a href='https://github.com/HyperbolicLabs/hyperbolic-gradio'>hyperbolic-gradio library</a> makes it ev... | Hyperbolic | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
Anthropic's Claude model can also be used via API. Here's a simple 20 questions-style game built on top of the Anthropic API:
$code_llm_claude
| Anthropic's Claude | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The MiniMax API exposes the M-series models through an OpenAI-compatible endpoint, so the standard `openai` client works out of the box. Here's an example of how to build a Gradio app around MiniMax:
$code_llm_minimax
| MiniMax | https://gradio.app/guides/chatinterface-examples | Chatbots - Chatinterface Examples Guide |
The Slack bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API.
Because Gradio's API is very flexible, you can create Sla... | How does it work? | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
* Install the latest version of `gradio` and the `slack-bolt` library:
```bash
pip install --upgrade gradio slack-bolt~=1.0
```
* Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs... | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
eHandler
SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE
SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE
app = App(token=SLACK_BOT_TOKEN)
@app.event("app_mention")
def handle_app_mention_events(body, say):
user_id = body["event"]["user"]
say(f"Hi <@{user_id}>! You mentioned me and said: {body['event']['t... | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
= body["authorizations"][0]["user_id"]
clean_message = text.replace(f"<@{bot_user_id}>", "").strip()
Handle images if present
files = []
if "files" in body["event"]:
for file in body["event"]["files"]:
if file["filetype"] in ["png", "jpg", "jpeg", "gif", "webp"]:
... | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)
If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify! | Prerequisites | https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app | Chatbots - Creating A Slack Bot From A Gradio App Guide |
First, we'll build the UI without handling these events and build from there.
We'll use the Hugging Face InferenceClient in order to get started without setting up
any API keys.
This is what the first draft of our application looks like:
```python
from huggingface_hub import InferenceClient
import gradio as gr
clie... | The UI | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
Our undo event will populate the textbox with the previous user message and also remove all subsequent assistant responses.
In order to know the index of the last user message, we can pass `gr.UndoData` to our event handler function like so:
```python
def handle_undo(history, undo_data: gr.UndoData):
return histo... | The Undo Event | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
The retry event will work similarly. We'll use `gr.RetryData` to get the index of the previous user message and remove all the subsequent messages from the history. Then we'll use the `respond` function to generate a new response. We could also get the previous prompt via the `value` property of `gr.RetryData`.
```pyt... | The Retry Event | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
By now you should hopefully be seeing the pattern!
To let users like a message, we'll add a `.like` event to our chatbot.
We'll pass it a function that accepts a `gr.LikeData` object.
In this case, we'll just print the message that was either liked or disliked.
```python
def handle_like(data: gr.LikeData):
if data... | The Like Event | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
Same idea with the edit listener! with `gr.Chatbot(editable=True)`, you can capture user edits. The `gr.EditData` object tells us the index of the message edited and the new text of the mssage. Below, we use this object to edit the history, and delete any subsequent messages.
```python
def handle_edit(history, edit_d... | The Edit Event | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
As a bonus, we'll also cover the `.clear()` event, which is triggered when the user clicks the clear icon to clear all messages. As a developer, you can attach additional events that should happen when this icon is clicked, e.g. to handle clearing of additional chatbot state:
```python
from uuid import uuid4
import gr... | The Clear Event | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
That's it! You now know how you can implement the retry, undo, like, and clear events for the Chatbot.
| Conclusion | https://gradio.app/guides/chatbot-specific-events | Chatbots - Chatbot Specific Events Guide |
The chat widget appears as a small button in the corner of your website. When clicked, it opens a chat interface that communicates with your Gradio app via the JavaScript Client API. Users can ask questions and receive responses directly within the widget.
| How does it work? | https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot | Chatbots - Creating A Website Widget From A Gradio Chatbot Guide |
* A running Gradio app (local or on Hugging Face Spaces). In this example, we'll use the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which helps generate code for Gradio apps based on natural language descriptions.
1. Create and Style the Chat Widget
First, add this HTML a... | Prerequisites | https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot | Chatbots - Creating A Website Widget From A Gradio Chatbot Guide |
solid eee;
display: flex;
}
chat-input {
flex-grow: 1;
padding: 8px;
border: 1px solid ddd;
border-radius: 4px;
margin-right: 8px;
}
.message {
margin: 8px 0;
padding: 8px;
border-radius: 4px;
}
.user-message {
background: e9ecef;
margin-left: 20px;
}
.bot-message {
... | Prerequisites | https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot | Chatbots - Creating A Website Widget From A Gradio Chatbot Guide |
client.predict("/chat", {
message: {"text": userMessage, "files": []}
});
const message = result.data[0];
console.log(result.data[0]);
const botMessage = result.data[0].join('\n');
appendMessage(botMessage, 'bot');
... | Prerequisites | https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot | Chatbots - Creating A Website Widget From A Gradio Chatbot Guide |
%20Recording%202024-12-19%20at%203.32.46%E2%80%AFPM.gif)
If you build a website widget from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify! | Prerequisites | https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot | Chatbots - Creating A Website Widget From A Gradio Chatbot Guide |
Every element of the chatbot value is a dictionary of `role` and `content` keys. You can always use plain python dictionaries to add new values to the chatbot but Gradio also provides the `ChatMessage` dataclass to help you with IDE autocompletion. The schema of `ChatMessage` is as follows:
```py
MessageContent = Uni... | The `ChatMessage` dataclass | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
tion`: an optional numeric value representing the duration of the thought/tool usage, in seconds. Displayed in a subdued font next inside parentheses next to the thought title.
* `status`: if set to `"pending"`, a spinner appears next to the thought title and the accordion is initialized open. If `status` is `"done"`,... | The `ChatMessage` dataclass | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
A real example using transformers.agents
We'll create a Gradio application simple agent that has access to a text-to-image tool.
Tip: Make sure you read the [smolagents documentation](https://huggingface.co/docs/smolagents/index) first
We'll start by importing the necessary classes from transformers and gradio.
``... | Building with Agents | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
om/freddyaboulton/freddyboulton/assets/41651716/c8d21336-e0e6-4878-88ea-e6fcfef3552d)
A real example using langchain agents
We'll create a UI for langchain agent that has access to a search engine.
We'll begin with imports and setting up the langchain agent. Note that you'll need an .env file with the following env... | Building with Agents | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
🦜⛓️ and see its thoughts 💭")
chatbot = gr.Chatbot(
label="Agent",
avatar_images=(
None,
"https://em-content.zobj.net/source/twitter/141/parrot_1f99c.png",
),
)
input = gr.Textbox(lines=1, label="Chat Message")
input.submit(interact_with_langchain_agent, ... | Building with Agents | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
The Gradio Chatbot can natively display intermediate thoughts of a _thinking_ LLM. This makes it perfect for creating UIs that show how an AI model "thinks" while generating responses. Below guide will show you how to build a chatbot that displays Gemini AI's thought process in real-time.
A real example using Gemini ... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
if len(parts) == 2 and not thinking_complete:
Complete thought and start response
thought_buffer += current_chunk
messages[-1] = ChatMessage(
role="assistant",
content=thought_buffer,
metadata={"title": "⏳Thinking: *The thoughts produc... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
message
input_box.submit(
lambda msg: (msg, msg, ""), Store message and clear input
inputs=[input_box],
outputs=[msg_store, input_box, input_box],
queue=False
).then(
user_message, Add user message to chat
inputs=[msg_store, chatbot],
outputs=[inpu... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
document preparation:
```python
def encode_pdf_to_base64(file_obj) -> str:
"""Convert uploaded PDF file to base64 string."""
if file_obj is None:
return None
with open(file_obj.name, 'rb') as f:
return base64.b64encode(f.read()).decode('utf-8')
def format_message_history(
history: list... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
latest_message["content"].append({"type": "text", "text": history[-1]["content"]})
formatted_messages.append(latest_message)
return formatted_messages
```
Then, let's create our bot response handler that processes citations:
```python
def bot_response(
history: list,
enable_citations: bool,
d... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
your request."
})
return history
```
Finally, let's create the Gradio interface:
```python
with gr.Blocks() as demo:
gr.Markdown("Chat with Citations")
with gr.Row(scale=1):
with gr.Column(scale=4):
chatbot = gr.Chatbot(bubble_full_width=False, show_label=False, scale... | Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
tbot that not only responds to users but also shows its sources, creating a more transparent and trustworthy interaction. See our finished Citations demo [here](https://huggingface.co/spaces/ysharma/anthropic-citations-with-gradio-metadata-key).
| Building with Visibly Thinking LLMs | https://gradio.app/guides/agents-and-tool-usage | Chatbots - Agents And Tool Usage Guide |
By default, Gradio automatically generates a navigation bar for multipage apps that displays all your pages with "Home" as the title for the main page. You can customize the navbar behavior using the `gr.Navbar` component.
Per-Page Navbar Configuration
You can have different navbar configurations for each page of you... | Customizing the Navbar | https://gradio.app/guides/multipage-apps | Additional Features - Multipage Apps Guide |
Add `@gr.cache` to any function to automatically cache its results. The decorator hashes inputs by their content — two different numpy arrays with the same pixel values will produce a cache hit. Cache hits bypass the Gradio queue entirely.
```python
import gradio as gr
@gr.cache
def classify(image):
return model.... | Automatic caching with `@gr.cache` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
.
- **`per_session`** — when `True`, each user session gets an isolated cache namespace. Prevents one user's cached results from being served to another, clears that session's entries when the client disconnects, and still applies `max_size` and `max_memory` to the shared cache store across all sessions.
Access the c... | Automatic caching with `@gr.cache` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
For full control over what gets cached and when, use `gr.Cache()` as an injectable parameter (like `gr.Progress`). Gradio injects the same instance on every call, giving you a thread-safe `get`/`set` interface:
```python
def my_function(prompt, c=gr.Cache()):
hit = c.get(prompt)
if hit is not None:
ret... | Manual cache control with `gr.Cache()` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
best_len = len(cached_key)
if best_key:
past_kv = c.get(best_key)["kv"]
output = model.generate(prompt, past_key_values=past_kv)
else:
output = model.generate(prompt)
c.set(prompt, kv=model.past_key_values)
return output.text
```
For a full runnable version, see the [`g... | Manual cache control with `gr.Cache()` | https://gradio.app/guides/caching | Additional Features - Caching Guide |
`@gr.cache` is most useful for **deterministic** functions where the same input always produces the same output: image classification, audio transcription, embedding computation, structured data extraction.
It is less useful for **non-deterministic** functions like text generation or image generation, where users migh... | When to use caching | https://gradio.app/guides/caching | Additional Features - Caching Guide |
Take a look at these complete examples and then build your own Gradio app with caching!
- [`@gr.cache()` function types demo](https://github.com/gradio-app/gradio/blob/main/demo/cache_demo/run.py) - sync, async, generator, and async generator caching
- [`gr.Cache()` manual cache demo](https://github.com/gradio-app/gra... | Next steps | https://gradio.app/guides/caching | Additional Features - Caching Guide |
Client side functions are ideal for updating component properties (like visibility, placeholders, interactive state, or styling).
Here's a basic example:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row() as row:
btn = gr.Button("Hide this row")
This function runs in the browser ... | When to Use Client Side Functions | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Client side functions have some important restrictions:
* They can only update component properties (not values)
* They cannot take any inputs
Here are some functions that will work with `js=True`:
```py
Simple property updates
lambda: gr.Textbox(lines=4)
Multiple component updates
lambda: [gr.Textbox(lines=4), gr.B... | Limitations | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Here's a more complete example showing how client side functions can improve the user experience:
$code_todo_list_js
| Complete Example | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
When you set `js=True`, Gradio:
1. Transpiles your Python function to JavaScript
2. Runs the function directly in the browser
3. Still sends the request to the server (for consistency and to handle any side effects)
This provides immediate visual feedback while ensuring your application state remains consistent.
| Behind the Scenes | https://gradio.app/guides/client-side-functions | Additional Features - Client Side Functions Guide |
Gradio demos can be easily shared publicly by setting `share=True` in the `launch()` method. Like this:
```python
import gradio as gr
def greet(name):
return "Hello " + name + "!"
demo = gr.Interface(fn=greet, inputs="textbox", outputs="textbox")
demo.launch(share=True) Share your demo with just 1 extra parame... | Sharing Demos | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
If you'd like to have a permanent link to your Gradio demo on the internet, use Hugging Face Spaces. [Hugging Face Spaces](http://huggingface.co/spaces/) provides the infrastructure to permanently host your machine learning model for free!
After you have [created a free Hugging Face account](https://huggingface.co/joi... | Hosting on HF Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can add a button to your Gradio app that creates a unique URL you can use to share your app and all components **as they currently are** with others. This is useful for sharing unique and interesting generations from your application , or for saving a snapshot of your app at a particular point in time.
To add a de... | Sharing Deep Links | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Once you have hosted your app on Hugging Face Spaces (or on your own server), you may want to embed the demo on a different website, such as your blog or your portfolio. Embedding an interactive demo allows people to try out the machine learning model that you have built, without needing to download or install anything... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
=> {
let v = obj.info.version;
content = document.querySelector('.prose');
content.innerHTML = content.innerHTML.replaceAll("{GRADIO_VERSION}", v);
});
</script>
You can see examples of how web components look <a href="https://www.gradio.app">on the Gradio landing page</a>.
You can also customize the appe... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
ple of how to use these attributes to create a Gradio app that does not lazy load and has an initial height of 0px.
```html
<gradio-app
space="gradio/Echocardiogram-Segmentation"
eager="true"
initial_height="0px"
></gradio-app>
```
Here's another example of how to use the `render` event. An event listener is used ... | Embedding Hosted Spaces | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
You can use almost any Gradio app as an API! In the footer of a Gradio app [like this one](https://huggingface.co/spaces/gradio/hello_world), you'll see a "Use via API" link.

This is a page that lists the endpoints t... | API Page | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When a user makes a prediction to your app, you may need the underlying network request, in order to get the request headers (e.g. for advanced authentication), log the client's IP address, getting the query parameters, or for other reasons. Gradio supports this in a similar manner to FastAPI: simply add a function par... | Accessing the Network Request Directly | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
In some cases, you might have an existing FastAPI app, and you'd like to add a path for a Gradio demo.
You can easily do this with `gradio.mount_gradio_app()`.
Here's a complete example:
$code_custom_path
Note that this approach also allows you run your Gradio apps on custom paths (`http://localhost:8000/gradio` in ... | Mounting Within Another FastAPI App | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Password-protected app
You may wish to put an authentication page in front of your app to limit who can open your app. With the `auth=` keyword argument in the `launch()` method, you can provide a tuple with a username and password, or a list of acceptable username/password tuples; Here's an example that provides pass... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Let's update the previous example to include a log out button:
```python
import gradio as gr
def update_message(request: gr.Request):
return f"Welcome, {request.username}"
with gr.Blocks() as demo:
m = gr.Markdown()
logout_button = gr.Button("Logout", link="/logout")
demo.load(update_message, None, ... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
e. If you want
to perform actions on behalf of the user (e.g. list user's private repos, create repo, etc.), you can retrieve the user
token by adding a parameter of type `gr.OAuthToken`. You must define which scopes you will use in your Space metadata
(see [documentation](https://huggingface.co/docs/hub/spaces-oauthsc... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
erence is that the `gr.OAuthProfile` or `gr.OAuthToken` will be `None` in the corresponding functions.
OAuth (with external providers)
It is also possible to authenticate with external OAuth providers (e.g. Google OAuth) in your Gradio apps. To do this, first mount your Gradio app within a FastAPI app ([as discussed... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
entials on the [Google Developer Console](https://console.cloud.google.com/project)):
```python
import os
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import FastAPI, Depends, Request
from starlette.config import Config
from starlette.responses import RedirectResponse
from starlette... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
direct_uri = urlunparse(urlparse(str(redirect_uri))._replace(scheme='https'))
return await oauth.google.authorize_redirect(request, redirect_uri)
@app.route('/auth')
async def auth(request: Request):
try:
access_token = await oauth.google.authorize_access_token(request)
except OAuthError:
r... | Authentication | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Gradio apps can function as MCP (Model Context Protocol) servers, allowing LLMs to use your app's functions as tools. By simply setting `mcp_server=True` in the `.launch()` method, Gradio automatically converts your app's functions into MCP tools that can be called by MCP clients like Claude Desktop, Cursor, or Cline. ... | MCP Servers | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
When publishing your app publicly, and making it available via API or via MCP server, you might want to set rate limits to prevent users from abusing your app. You can identify users using their IP address (using the `gr.Request` object [as discussed above](accessing-the-network-request-directly)) or, if they are logge... | Rate Limits | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
By default, Gradio collects certain analytics to help us better understand the usage of the `gradio` library. This includes the following information:
* What environment the Gradio app is running on (e.g. Colab Notebook, Hugging Face Spaces)
* What input/output components are being used in the Gradio app
* Whether the... | Analytics | https://gradio.app/guides/sharing-your-app | Additional Features - Sharing Your App Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.