text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 189
values | source_page_title stringclasses 189
values |
|---|---|---|---|
w(equal_height=True):
msg = gr.Textbox(
label="Your Question",
placeholder="Ask about weather or alerts (e.g., What's the weather in New York?)",
scale=4
)
clear_btn = gr.Button("Clear Chat", scale=1)
connect_btn.click(... | Part 2: Building the MCP Client with Gradio | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
To run your MCP application:
- Start a terminal window and run the MCP Client:
```bash
python app.py
```
- Open the Gradio interface at the URL shown (typically http://127.0.0.1:7860)
- In the Gradio interface, you'll see a field for the MCP Server path. It should default to `gradio_mcp_server.py`.
- Click "C... | Running the Application | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now you can chat with Claude and it will be able to generate images based on your descriptions.
Try prompts like:
- "Can you generate an image of a mountain landscape at sunset?"
- "Create an image of a cool tabby cat"
- "Generate a picture of a panda wearing sunglasses"
Claude will recognize these as image generatio... | Example Usage | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Here's the high-level flow of what happens during a chat session:
1. Your prompt enters the Gradio interface
2. The client forwards your prompt to Claude
3. Claude analyzes the prompt and decides to use the `generate_image` tool
4. The client sends the tool call to the MCP server
5. The server calls the external image... | How it Works | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now that you have a working MCP system, here are some ideas to extend it:
- Add more tools to your server
- Improve error handling
- Add private Huggingface Spaces with authentication for secure tool access
- Create custom tools that connect to your own APIs or services
- Implement streaming responses for better user... | Next Steps | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Congratulations! You've successfully built an MCP Client and Server that allows Claude to generate images based on text prompts. This is just the beginning of what you can do with Gradio and MCP. This guide enables you to build complex AI applications that can use Claude or any other powerful LLM to interact with virtu... | Conclusion | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
As of version 5.36.0, Gradio now comes with a built-in MCP server that can upload files to a running Gradio application. In the `View API` page of the server, you should see the following code snippet if any of the tools require file inputs:
<img src="https://huggingface.co/datasets/freddyaboulton/bucket/resolve/main/... | Using the File Upload MCP Server | https://gradio.app/guides/file-upload-mcp | Mcp - File Upload Mcp Guide |
In this guide, we've covered how you can connect to the Upload File MCP Server so that your agent can upload files before using Gradio MCP servers. Remember to set the `<UPLOAD_DIRECTORY>` as small as possible to prevent unintended file uploads!
| Conclusion | https://gradio.app/guides/file-upload-mcp | Mcp - File Upload Mcp Guide |
An MCP (Model Control Protocol) server is a standardized way to expose tools so that they can be used by LLMs. A tool can provide an LLM functionality that it does not have natively, such as the ability to generate images or calculate the prime factors of a number.
| What is an MCP Server? | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
LLMs are famously not great at counting the number of letters in a word (e.g. the number of "r"-s in "strawberry"). But what if we equip them with a tool to help? Let's start by writing a simple Gradio app that counts the number of letters in a word or phrase:
$code_letter_counter
Notice that we have: (1) included a ... | Example: Counting Letters in a Word | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
1. **Tool Conversion**: Each API endpoint in your Gradio app is automatically converted into an MCP tool with a corresponding name, description, and input schema. To view the tools and schemas, visit http://your-server:port/gradio_api/mcp/schema or go to the "View API" link in the footer of your Gradio app, and then cl... | Key features of the Gradio <> MCP Integration | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
p: To minimize latency and increase throughput by as much as 10 times, set queue=False in the event handlers of your Gradio app. However, this disables progress notifications so its recommended that long running events set queue=True
| Key features of the Gradio <> MCP Integration | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
If there's an existing Space that you'd like to use an MCP server, you'll need to do three things:
1. First, [duplicate the Space](https://huggingface.co/docs/hub/en/spaces-more-ways-to-createduplicating-a-space) if it is not your own Space. This will allow you to make changes to the app. If the Space requires a GPU, ... | Converting an Existing Space | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
You can use either a public Space or a private Space as an MCP server. If you'd like to use a private Space as an MCP server (or a ZeroGPU Space with your own quota), then you will need to provide your [Hugging Face token](https://huggingface.co/settings/token) when you make your request. To do this, simply add it as a... | Private Spaces | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
You may wish to authenticate users more precisely or let them provide other kinds of credentials or tokens in order to provide a custom experience for different users.
Gradio allows you to access the underlying `starlette.Request` that has made the tool call, which means that you can access headers, originating IP ad... | Authentication and Credentials | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
the headers you need to supply when connecting to the server! See the image below:
```python
import gradio as gr
def make_api_request_on_behalf_of_user(prompt: str, x_api_token: gr.Header):
"""Make a request to everyone's favorite API.
Args:
prompt: The prompt to send to the API.
Returns:
... | Authentication and Credentials | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
Gradio automatically sets the tool name based on the name of your function, and the description from the docstring of your function. But you may want to change how the description appears to your LLM. You can do this by using the `api_description` parameter in `Interface`, `ChatInterface`, or any event listener. This p... | Modifying Tool Descriptions | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
In addition to tools (which execute functions generally and are the default for any function exposed through the Gradio MCP integration), MCP supports two other important primitives: **resources** (for exposing data) and **prompts** (for defining reusable templates). Gradio provides decorators to easily create MCP serv... | MCP Resources and Prompts | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
So far, all of our MCP tools, resources, or prompts have corresponded to event listeners in the UI. This works well for functions that directly update the UI, but may not work if you wish to expose a "pure logic" function that should return raw data (e.g. a JSON object) without directly causing a UI update.
In order t... | Adding MCP-Only Functions | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
In some cases, you may decide not to use Gradio's built-in integration and instead manually create an FastMCP Server that calls a Gradio app. This approach is useful when you want to:
- Store state / identify users between calls instead of treating every tool call completely independently
- Start the Gradio app MCP se... | Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
return result
@mcp.tool()
async def run_dia_tts(prompt: str, space_id: str = "ysharma/Dia-1.6B") -> str:
"""Text-to-Speech Synthesis.
Args:
prompt: Text prompt describing the conversation between speakers S1, S2
space_id: HuggingFace Space ID to use
"""
client = get_client(space_... | Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
use your Gradio-powered tools to accomplish these tasks.
| Gradio with FastMCP | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
The MCP protocol is still in its infancy and you might see issues connecting to an MCP Server that you've built. We generally recommend using the [MCP Inspector Tool](https://github.com/modelcontextprotocol/inspector) to try connecting and debugging your MCP Server.
Here are some things that may help:
**1. Ensure tha... | Troubleshooting your MCP Servers | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio Guide |
= 3
while divisor * divisor <= n_int:
while n_int % divisor == 0:
factors.append(divisor)
n_int //= divisor
divisor += 2
if n_int > 1:
factors.append(n_int)
return factors
```
**3. Ensure that your MCP Client Supports Streamable HTTP**
Some MCP Clients do ... | Troubleshooting your MCP Servers | https://gradio.app/guides/building-mcp-server-with-gradio | Mcp - Building Mcp Server With Gradio 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 |
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 |
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 |
**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 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 |
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 |
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 |
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 |
What are agents?
A [LangChain agent](https://docs.langchain.com/docs/components/agents/agent) is a Large Language Model (LLM) that takes user input and reports an output based on using one of many tools at its disposal.
What is Gradio?
[Gradio](https://github.com/gradio-app/gradio) is the defacto standard framework ... | Some background | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
To get started with `gradio_tools`, all you need to do is import and initialize your tools and pass them to the langchain agent!
In the following example, we import the `StableDiffusionPromptGeneratorTool` to create a good prompt for stable diffusion, the
`StableDiffusionTool` to create an image with our improved prom... | gradio_tools - An end-to-end example | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
that come with `gradio_tools`. Please see this [doc](https://github.com/freddyaboulton/gradio-toolsgradio-tools-gradio--llm-agents) for a complete list of the tools that come with `gradio_tools`.
If you would like to use a tool that's not currently in `gradio_tools`, it is very easy to add your own. That's what the nex... | gradio_tools - An end-to-end example | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
The core abstraction is the `GradioTool`, which lets you define a new tool for your LLM as long as you implement a standard interface:
```python
class GradioTool(BaseTool):
def __init__(self, name: str, description: str, src: str) -> None:
@abstractmethod
def create_job(self, query: str) -> Job:
... | gradio_tools - creating your own tool | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
lf, gr)` and `_block_output(self, gr)` methods of the tool. The `gr` variable is the gradio module (the result of `import gradio as gr`). It will be
automatically imported by the `GradiTool` parent class and passed to the `_block_input` and `_block_output` methods.
And that's it!
Once you have created your tool, o... | gradio_tools - creating your own tool | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
Here is the code for the StableDiffusion tool as an example:
```python
from gradio_tool import GradioTool
import os
class StableDiffusionTool(GradioTool):
"""Tool for calling stable diffusion from llm"""
def __init__(
self,
name="StableDiffusion",
description=(
"An image g... | Example tool - Stable Diffusion | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
You now know how to extend the abilities of your LLM with the 1000s of gradio spaces running in the wild!
Again, we welcome any contributions to the [gradio_tools](https://github.com/freddyaboulton/gradio-tools) library.
We're excited to see the tools you all build!
| Conclusion | https://gradio.app/guides/gradio-and-llm-agents | Gradio Clients And Lite - Gradio And Llm Agents Guide |
Install the @gradio/client package to interact with Gradio APIs using Node.js version >=18.0.0 or in browser-based projects. Use npm or any compatible package manager:
```bash
npm i @gradio/client
```
This command adds @gradio/client to your project dependencies, allowing you to import it in your JavaScript or TypeSc... | Installation via npm | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
For quick addition to your web project, you can use the jsDelivr CDN to load the latest version of @gradio/client directly into your HTML:
```html
<script type="module">
import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js";
...
</script>
```
Be sure to add this to the `<head>` of y... | Installation via CDN | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.