text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 188
values | source_page_title stringclasses 188
values |
|---|---|---|---|
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 |
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 |
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 |
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 |
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 |
**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 |
Time plots need a datetime column on the x-axis. Here's a simple example with some flight data:
$code_plot_guide_temporal
$demo_plot_guide_temporal
| Creating a Plot with a pd.Dataframe | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
You may wish to bin data by time buckets. Use `x_bin` to do so, using a string suffix with "s", "m", "h" or "d", such as "15m" or "1d".
$code_plot_guide_aggregate_temporal
$demo_plot_guide_aggregate_temporal
| Aggregating by Time | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
You can use `gr.DateTime` to accept input datetime data. This works well with plots for defining the x-axis range for the data.
$code_plot_guide_datetime
$demo_plot_guide_datetime
Note how `gr.DateTime` can accept a full datetime string, or a shorthand using `now - [0-9]+[smhd]` format to refer to a past time.
You w... | DateTime Components | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
In many cases, you're working with live, realtime date, not a static dataframe. In this case, you'd update the plot regularly with a `gr.Timer()`. Assuming there's a `get_data` method that gets the latest dataframe:
```python
with gr.Blocks() as demo:
timer = gr.Timer(5)
plot1 = gr.BarPlot(x="time", y="price")... | RealTime Data | https://gradio.app/guides/time-plots | Data Science And Plots - Time Plots Guide |
Use any of the standard Gradio form components to filter your data. You can do this via event listeners or function-as-value syntax. Let's look at the event listener approach first:
$code_plot_guide_filters_events
$demo_plot_guide_filters_events
And this would be the function-as-value approach for the same demo.
$co... | Filters | https://gradio.app/guides/filters-tables-and-stats | Data Science And Plots - Filters Tables And Stats Guide |
Add `gr.DataFrame` and `gr.Label` to your dashboard for some hard numbers.
$code_plot_guide_tables_stats
$demo_plot_guide_tables_stats
| Tables and Stats | https://gradio.app/guides/filters-tables-and-stats | Data Science And Plots - Filters Tables And Stats Guide |
```python
from sqlalchemy import create_engine
import pandas as pd
engine = create_engine('sqlite:///your_database.db')
with gr.Blocks() as demo:
gr.LinePlot(pd.read_sql_query("SELECT time, price from flight_info;", engine), x="time", y="price")
```
Let's see a a more interactive plot involving filters that modi... | SQLite | https://gradio.app/guides/connecting-to-a-database | Data Science And Plots - Connecting To A Database Guide |
If you're using a different database format, all you have to do is swap out the engine, e.g.
```python
engine = create_engine('postgresql://username:password@host:port/database_name')
```
```python
engine = create_engine('mysql://username:password@host:port/database_name')
```
```python
engine = create_engine('oracl... | Postgres, mySQL, and other databases | https://gradio.app/guides/connecting-to-a-database | Data Science And Plots - Connecting To A Database Guide |
Plots accept a pandas Dataframe as their value. The plot also takes `x` and `y` which represent the names of the columns that represent the x and y axes respectively. Here's a simple example:
$code_plot_guide_line
$demo_plot_guide_line
All plots have the same API, so you could swap this out with a `gr.ScatterPlot`:
... | Creating a Plot with a pd.Dataframe | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can break out your plot into series using the `color` argument.
$code_plot_guide_series_nominal
$demo_plot_guide_series_nominal
If you wish to assign series specific colors, use the `color_map` arg, e.g. `gr.ScatterPlot(..., color_map={'white': 'FF9988', 'asian': '88EEAA', 'black': '333388'})`
The color column c... | Breaking out Series by Color | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can aggregate values into groups using the `x_bin` and `y_aggregate` arguments. If your x-axis is numeric, providing an `x_bin` will create a histogram-style binning:
$code_plot_guide_aggregate_quantitative
$demo_plot_guide_aggregate_quantitative
If your x-axis is a string type instead, they will act as the categ... | Aggregating Values | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
You can use the `.select` listener to select regions of a plot. Click and drag on the plot below to select part of the plot.
$code_plot_guide_selection
$demo_plot_guide_selection
You can combine this and the `.double_click` listener to create some zoom in/out effects by changing `x_lim` which sets the bounds of the x... | Selecting Regions | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
Take a look how you can have an interactive dashboard where the plots are functions of other Components.
$code_plot_guide_interactive
$demo_plot_guide_interactive
It's that simple to filter and control the data presented in your visualization! | Making an Interactive Dashboard | https://gradio.app/guides/creating-plots | Data Science And Plots - Creating Plots Guide |
Use `gradio.Server` instead of `gr.Blocks` when any of the following apply:
- You want a **completely custom (potentially vibe-coded) UI** (your own HTML, React, Svelte, etc.) powered by Gradio's backend
- You want **full FastAPI control** (custom GET/POST routes, middleware, dependency injection) alongside Gradio API... | When to use `gradio.Server` | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
`gradio.Server` is included in the main Gradio package. If you want MCP support, install the extra:
```bash
pip install "gradio[mcp]"
```
| Installation | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
Here's the simplest possible Server mode app — a single API endpoint with no UI:
```python
from gradio import Server
app = Server()
@app.api(name="hello")
def hello(name: str) -> str:
return f"Hello, {name}!"
app.launch()
```
That's it. When you run this script, you get:
- A Gradio API endpoint at `/gradio_ap... | A Minimal Example | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
Since `gradio.Server` inherits from FastAPI, you can add any route directly:
```python
from gradio import Server
from fastapi.responses import HTMLResponse
app = Server()
@app.api(name="hello")
def hello(name: str) -> str:
return f"Hello, {name}!"
@app.get("/", response_class=HTMLResponse)
async def homepage():... | Custom Routes | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
To expose your API endpoints as MCP tools, add the `@app.mcp.tool()` decorator and pass `mcp_server=True` to `launch()`:
```python
from gradio import Server
app = Server()
@app.mcp.tool(name="hello")
@app.api(name="hello")
def hello(name: str) -> str:
"""Greet someone by name."""
return f"Hello, {name}!"
ap... | MCP Tools | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
This example combines everything: custom HTML served at `/`, Gradio API endpoints with concurrency limits, MCP tools, and a custom REST endpoint, and two connected via [the Gradio JavaScript client](/guides/getting-started-with-the-js-client).
$code_server_app
Run it with:
```bash
python run.py
```
Then open `http:... | A Complete Example with the JavaScript Client | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
`app.api()` supports all of the same concurrency and streaming options as `gr.api()`:
```python
@app.api(name="generate", concurrency_limit=2, stream_every=0.5)
async def generate(prompt: str):
for token in model.generate(prompt):
yield token
```
Generator functions automatically stream results via SSE, j... | Concurrency and Streaming | https://gradio.app/guides/server-mode | Gradio Clients And Lite - Server Mode Guide |
Let's start with what seems like the most complex bit -- using machine learning to remove the music from a video.
Luckily for us, there's an existing Space we can use to make this process easier: [https://huggingface.co/spaces/abidlabs/music-separation](https://huggingface.co/spaces/abidlabs/music-separation). This Sp... | Step 1: Write the Video Processing Function | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
f heavy lifting when it comes to working with audio and video files. The most common way to use `ffmpeg` is through the command line, which we'll call via Python's `subprocess` module:
Our video processing workflow will consist of three steps:
1. First, we start by taking in a video filepath and extracting the audio ... | Step 1: Write the Video Processing Function | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Next up, we'll create a simple FastAPI app. If you haven't used FastAPI before, check out [the great FastAPI docs](https://fastapi.tiangolo.com/). Otherwise, this basic template, which we add to `main.py`, will look pretty familiar:
```python
import os
from fastapi import FastAPI, File, UploadFile, Request
from fastap... | Step 2: Create a FastAPI app (Backend Routes) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Finally, we create the frontend of our web application. First, we create a folder called `templates` in the same directory as `main.py`. We then create a template, `home.html` inside the `templates` folder. Here is the resulting file structure:
```csv
├── main.py
├── templates
│ └── home.html
```
Write the followin... | Step 3: Create a FastAPI app (Frontend Template) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
class="upload-btn">Choose video file</label> <input type="file"
name="video" id="video-upload"> <span class="file-name"></span> <button
type="submit" class="upload-btn">Upload</button> </form> <script> //
Display selected file name in the form const fileUpload =
document.getElementById("video-up... | Step 3: Create a FastAPI app (Frontend Template) | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client Guide |
Finally, we are ready to run our FastAPI app, powered by the Gradio Python Client!
Open up a terminal and navigate to the directory containing `main.py`. Then run the following command in the terminal:
```bash
$ uvicorn main:app
```
You should see an output that looks like this:
```csv
Loaded as API: https://abidla... | Step 4: Run your FastAPI app | https://gradio.app/guides/fastapi-app-with-the-gradio-client | Gradio Clients And Lite - Fastapi App With The Gradio Client 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 |
Start by connecting instantiating a `client` instance and connecting it to a Gradio app that is running on Hugging Face Spaces or generally anywhere on the web.
| Connecting to a running Gradio App | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr"); // a Space that translates from English to French
```
You can also connect to private Spaces by passing in your HF token with the `token` property of the options parameter. You can get your HF token here: https://huggin... | Connecting to a Hugging Face Space | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space, and then use it to make as many requests as you'd like! You'll need to pass in your [Hugging Face token](https://hug... | Duplicating a Space for private use | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
```js
import { Client } from "@gradio/client";
const app = Client.connect("https://bec81a83-5b5c-471e.gradio.live");
... | Connecting a general Gradio app | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:
```js
import { Client } from "@gradio/client";
Client.connect(
space_name,
{ auth: [username, password] }
)
```
| Connecting to a Gradio app with auth | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client`'s `view_api` method.
For the Whisper Space, we can do this:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/whisper");
const app_info = await app.view_api();
co... | Inspecting the API endpoints | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage.

The View API pag... | The "View API" Page | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The simplest way to make a prediction is simply to call the `.predict()` method with the appropriate arguments:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr");
const result = await app.predict("/predict", ["Hello"]);
```
If there are multiple parameters, then you sh... | Making a prediction | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
If the API you are working with can return results over time, or you wish to access information about the status of a job, you can use the iterable interface for more flexibility. This is especially useful for iterative endpoints or generator endpoints that will produce a series of values over time as discrete response... | Using events | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The event interface also allows you to get the status of the running job by instantiating the client with the `events` options passing `status` and `data` as an array:
```ts
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr", {
events: ["status", "data"]
});
```
This ensures... | Status | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
The job instance also has a `.cancel()` method that cancels jobs that have been queued but not started. For example, if you run:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("abidlabs/en2fr");
const job_one = app.submit("/predict", ["Hello"]);
const job_two = app.submit("/predict", ... | Cancelling Jobs | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client Guide |
Some Gradio API endpoints do not return a single value, rather they return a series of values. You can listen for these values in real time using the iterable interface:
```js
import { Client } from "@gradio/client";
const app = await Client.connect("gradio/count_generator");
const job = app.submit(0, [9]);
for awai... | Generator Endpoints | https://gradio.app/guides/getting-started-with-the-js-client | Gradio Clients And Lite - Getting Started With The Js Client 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 |
If you already have a recent version of `gradio`, then the `gradio_client` is included as a dependency. But note that this documentation reflects the latest version of the `gradio_client`, so upgrade if you're not sure!
The lightweight `gradio_client` package can be installed from pip (or pip3) and is tested to work w... | Installation | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Start by connecting instantiating a `Client` object and connecting it to a Gradio app that is running on Hugging Face Spaces.
```python
from gradio_client import Client
client = Client("abidlabs/en2fr") a Space that translates from English to French
```
You can also connect to private Spaces by passing in your HF t... | Connecting to a Gradio App on Hugging Face Spaces | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
While you can use any public Space as an API, you may get rate limited by Hugging Face if you make too many requests. For unlimited usage of a Space, simply duplicate the Space to create a private Space,
and then use it to make as many requests as you'd like!
The `gradio_client` includes a class method: `Client.duplic... | Duplicating a Space for private use | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If your app is running somewhere else, just provide the full URL instead, including the "http://" or "https://". Here's an example of making predictions to a Gradio app that is running on a share URL:
```python
from gradio_client import Client
client = Client("https://bec81a83-5b5c-471e.gradio.live")
```
| Connecting a general Gradio app | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
If the Gradio application you are connecting to [requires a username and password](/guides/sharing-your-appauthentication), then provide them as a tuple to the `auth` argument of the `Client` class:
```python
from gradio_client import Client
Client(
space_name,
auth=[username, password]
)
```
| Connecting to a Gradio app with auth | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Once you have connected to a Gradio app, you can view the APIs that are available to you by calling the `Client.view_api()` method. For the Whisper Space, we see the following:
```bash
Client.predict() Usage Info
---------------------------
Named API endpoints: 1
- predict(audio, api_name="/predict") -> output
P... | Inspecting the API endpoints | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
As an alternative to running the `.view_api()` method, you can click on the "Use via API" link in the footer of the Gradio app, which shows us the same information, along with example usage.

The View API pag... | The "View API" Page | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The simplest way to make a prediction is simply to call the `.predict()` function with the appropriate arguments:
```python
from gradio_client import Client
client = Client("abidlabs/en2fr")
client.predict("Hello", api_name='/predict')
>> Bonjour
```
If there are multiple parameters, then you should pass them as se... | Making a prediction | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
```python
from gradio_client import Client, handle_file
client = Client("abidlabs/whisper")
client.predict(
audio=handle_file("https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3")
)
>> "My thought I have nobody by a beauty and will as you poured. Mr. Rochester is serve in that so don'... | Making a prediction | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
One should note that `.predict()` is a _blocking_ operation as it waits for the operation to complete before returning the prediction.
In many cases, you may be better off letting the job run in the background until you need the results of the prediction. You can do this by creating a `Job` instance using the `.submit... | Running jobs asynchronously | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.