text stringlengths 0 2k | heading1 stringlengths 3 79 | source_page_url stringclasses 188
values | source_page_title stringclasses 188
values |
|---|---|---|---|
Alternatively, one can add one or more callbacks to perform actions after the job has completed running, like this:
```python
from gradio_client import Client
def print_result(x):
print("The translated result is: {x}")
client = Client(space="abidlabs/en2fr")
job = client.submit("Hello", api_name="/predict", res... | Adding callbacks | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The `Job` object also allows you to get the status of the running job by calling the `.status()` method. This returns a `StatusUpdate` object with the following attributes: `code` (the status code, one of a set of defined strings representing the status. See the `utils.Status` class), `rank` (the current position of th... | Status | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
The `Job` class also has a `.cancel()` instance method that cancels jobs that have been queued but not started. For example, if you run:
```py
client = Client("abidlabs/whisper")
job1 = client.submit(handle_file("audio_sample1.wav"))
job2 = client.submit(handle_file("audio_sample2.wav"))
job1.cancel() will return Fal... | Cancelling Jobs | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Some Gradio API endpoints do not return a single value, rather they return a series of values. You can get the series of values that have been returned at any time from such a generator endpoint by running `job.outputs()`:
```py
from gradio_client import Client
client = Client(src="gradio/count_generator")
job = clie... | Generator Endpoints | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
Gradio demos can include [session state](https://www.gradio.app/guides/state-in-blocks), which provides a way for demos to persist information from user interactions within a page session.
For example, consider the following demo, which maintains a list of words that a user has submitted in a `gr.State` component. Whe... | Demos with Session State | https://gradio.app/guides/getting-started-with-the-python-client | Gradio Clients And Lite - Getting Started With The Python Client Guide |
You generally don't need to install cURL, as it comes pre-installed on many operating systems. Run:
```bash
curl --version
```
to confirm that `curl` is installed. If it is not already installed, you can install it by visiting https://curl.se/download.html.
| Installation | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
To query a Gradio app, you'll need its full URL. This is usually just the URL that the Gradio app is hosted on, for example: https://bec81a83-5b5c-471e.gradio.live
**Hugging Face Spaces**
However, if you are querying a Gradio on Hugging Face Spaces, you will need to use the URL of the embedded Gradio app, not the UR... | Step 0: Get the URL for your Gradio App | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
The first of the two `curl` requests is `POST` request that submits the input payload to the Gradio app.
The syntax of the `POST` request is as follows:
```bash
$ curl -X POST $URL/call/$API_NAME -H "Content-Type: application/json" -d '{
"data": $PAYLOAD
}'
```
Here:
* `$URL` is the URL of the Gradio app as obta... | Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
king a request to a private Space, you will need to pass in a [Hugging Face token](https://huggingface.co/settings/tokens) that has read access to the Space. The request will look like this:
```bash
$ curl -X POST https://private-space.hf.space/call/predict -H "Content-Type: application/json" -H "Authorization: Bearer... | Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
ient?"],
"session_hash": "newsequence5678"
}'
```
| Step 1: Make a Prediction (POST) | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
Once you have received the `EVENT_ID` corresponding to your prediction, you can stream the results. Gradio stores these results in a least-recently-used cache in the Gradio app. By default, the cache can store 2,000 results (across all users and endpoints of the app).
To stream the results for your prediction, make ... | Step 2: GET the result | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
```bash
event: generating
data: ["Hello, w!"]
event: generating
data: ["Hello, wo!"]
event: generating
data: ["Hello, wor!"]
event: generating
data: ["Hello, worl!"]
event: generating
data: ["Hello, world!"]
event: complete
data: ["Hello, world!"]
```
**File Example**
If your Gradio app returns a file, the file will ... | Step 2: GET the result | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
What if your Gradio application has [authentication enabled](/guides/sharing-your-appauthentication)? In that case, you'll need to make an additional `POST` request with cURL to authenticate yourself before you make any queries. Here are the complete steps:
First, login with a `POST` request supplying a valid username... | Authentication | https://gradio.app/guides/querying-gradio-apps-with-curl | Gradio Clients And Lite - Querying Gradio Apps With Curl Guide |
If the state is something that should be accessible to all function calls and all users, you can create a variable outside the function call and access it inside the function. For example, you may load a large model outside the function and use it inside the function so that every function call does not need to reload ... | Global State | https://gradio.app/guides/interface-state | Building Interfaces - Interface State Guide |
Another type of data persistence Gradio supports is session state, where data persists across multiple submits within a page session. However, data is _not_ shared between different users of your model. To store data in a session state, you need to do three things:
1. Pass in an extra parameter into your function, whi... | Session State | https://gradio.app/guides/interface-state | Building Interfaces - Interface State Guide |
Gradio includes more than 30 pre-built components (as well as many [community-built _custom components_](https://www.gradio.app/custom-components/gallery)) that can be used as inputs or outputs in your demo. These components correspond to common data types in machine learning and data science, e.g. the `gr.Image` compo... | Gradio Components | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
We used the default versions of the `gr.Textbox` and `gr.Slider`, but what if you want to change how the UI components look or behave?
Let's say you want to customize the slider to have values from 1 to 10, with a default of 2. And you wanted to customize the output text field — you want it to be larger and have a lab... | Components Attributes | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
Suppose you had a more complex function, with multiple outputs as well. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number.
$code_hello_world_3
$demo_hello_world_3
Just as each component in the `inputs` list corresponds to one of the parameters of the... | Multiple Input and Output Components | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
Gradio supports many types of components, such as `Image`, `DataFrame`, `Video`, or `Label`. Let's try an image-to-image function to get a feel for these!
$code_sepia_filter
$demo_sepia_filter
When using the `Image` component as input, your function will receive a NumPy array with the shape `(height, width, 3)`, wher... | An Image Example | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
You can provide example data that a user can easily load into `Interface`. This can be helpful to demonstrate the types of inputs the model expects, as well as to provide a way to explore your dataset in conjunction with your model. To load example data, you can provide a **nested list** to the `examples=` keyword argu... | Example Inputs | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
In the previous example, you may have noticed the `title=` and `description=` keyword arguments in the `Interface` constructor that helps users understand your app.
There are three arguments in the `Interface` constructor to specify where this content should go:
- `title`: which accepts text and can display it at the... | Descriptive Content | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
If your prediction function takes many inputs, you may want to hide some of them within a collapsed accordion to avoid cluttering the UI. The `Interface` class takes an `additional_inputs` argument which is similar to `inputs` but any input components included here are not visible by default. The user must click on the... | Additional Inputs within an Accordion | https://gradio.app/guides/the-interface-class | Building Interfaces - The Interface Class Guide |
Adding examples to an Interface is as easy as providing a list of lists to the `examples`
keyword argument.
Each sublist is a data sample, where each element corresponds to an input of the prediction function.
The inputs must be ordered in the same order as the prediction function expects them.
If your interface only ... | Providing Examples | https://gradio.app/guides/more-on-examples | Building Interfaces - More On Examples Guide |
You may wish to provide some cached examples of your model for users to quickly try out, in case your model takes a while to run normally.
If `cache_examples=True`, your Gradio app will run all of the examples and save the outputs when you call the `launch()` method. This data will be saved in a directory called `gradi... | Caching examples | https://gradio.app/guides/more-on-examples | Building Interfaces - More On Examples Guide |
To create a demo that has both the input and the output components, you simply need to set the values of the `inputs` and `outputs` parameter in `Interface()`. Here's an example demo of a simple image filter:
$code_sepia_filter
$demo_sepia_filter
| Standard demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
What about demos that only contain outputs? In order to build such a demo, you simply set the value of the `inputs` parameter in `Interface()` to `None`. Here's an example demo of a mock image generation model:
$code_fake_gan_no_input
$demo_fake_gan_no_input
| Output-only demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
Similarly, to create a demo that only contains inputs, set the value of `outputs` parameter in `Interface()` to be `None`. Here's an example demo that saves any uploaded image to disk:
$code_save_file_no_output
$demo_save_file_no_output
| Input-only demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
A demo that has a single component as both the input and the output. It can simply be created by setting the values of the `inputs` and `outputs` parameter as the same component. Here's an example demo of a text generation model:
$code_unified_demo_text_generation
$demo_unified_demo_text_generation
It may be the case... | Unified demos | https://gradio.app/guides/four-kinds-of-interfaces | Building Interfaces - Four Kinds Of Interfaces Guide |
You can make interfaces automatically refresh by setting `live=True` in the interface. Now the interface will recalculate as soon as the user input changes.
$code_calculator_live
$demo_calculator_live
Note there is no submit button, because the interface resubmits automatically on change.
| Live Interfaces | https://gradio.app/guides/reactive-interfaces | Building Interfaces - Reactive Interfaces Guide |
Some components have a "streaming" mode, such as `Audio` component in microphone mode, or the `Image` component in webcam mode. Streaming means data is sent continuously to the backend and the `Interface` function is continuously being rerun.
The difference between `gr.Audio(source='microphone')` and `gr.Audio(source=... | Streaming Components | https://gradio.app/guides/reactive-interfaces | Building Interfaces - Reactive Interfaces Guide |
The Model Context Protocol (MCP) standardizes how applications provide context to LLMs. It allows Claude to interact with external tools, like image generators, file systems, or APIs, etc.
| What is MCP? | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
- Python 3.10+
- An Anthropic API key
- Basic understanding of Python programming
| Prerequisites | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
First, install the required packages:
```bash
pip install gradio anthropic mcp
```
Create a `.env` file in your project directory and add your Anthropic API key:
```
ANTHROPIC_API_KEY=your_api_key_here
```
| Setup | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
The server provides tools that Claude can use. In this example, we'll create a server that generates images through [a HuggingFace space](https://huggingface.co/spaces/ysharma/SanaSprint).
Create a file named `gradio_mcp_server.py`:
```python
from mcp.server.fastmcp import FastMCP
import json
import sys
import io
imp... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
"message": f"Error generating image: {str(e)}"
})
if __name__ == "__main__":
mcp.run(transport='stdio')
```
What this server does:
1. It creates an MCP server that exposes a `generate_image` tool
2. The tool connects to the SanaSprint model hosted on HuggingFace Spaces
3. It handles the asynchronous na... | Part 1: Building the MCP Server | https://gradio.app/guides/building-an-mcp-client-with-gradio | Mcp - Building An Mcp Client With Gradio Guide |
Now let's create a Gradio chat interface as MCP Client that connects Claude to our MCP server.
Create a file named `app.py`:
```python
import asyncio
import os
import json
from typing import List, Dict, Any, Union
from contextlib import AsyncExitStack
import gradio as gr
from gradio.components.chatbot import ChatMes... | 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 |
iption,
"input_schema": tool.inputSchema
} for tool in response.tools]
tool_names = [tool["name"] for tool in self.tools]
return f"Connected to MCP server. Available tools: {', '.join(tool_names)}"
def process_message(self, message: str, history: List[Union[Dict[str... | 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 |
ntent": content.text
})
elif content.type == 'tool_use':
tool_name = content.name
tool_args = content.input
result_messages.append({
"role": "assistant",
"content": f"I'l... | 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 |
})
result_content = result.content
if isinstance(result_content, list):
result_content = "\n".join(str(item) for item in result_content)
try:
result_json = json.loads(result_content)
... | 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 |
"parent_id": f"result_{tool_name}",
"id": f"raw_result_{tool_name}",
"title": "Raw Output"
}
})
claude_messages.append({"role": "user", "content": f"Tool result for {tool_name}: {result_... | 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 |
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 |
If you're using LLMs in your workflow, adding this server will augment them with just the right context on gradio - which makes your experience a lot faster and smoother.
<video src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/mcp-docs.mp4" style="width:100%" controls p... | Why an MCP Server? | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
For clients that support streamable HTTP (e.g. Cursor, Windsurf, Cline), simply add the following configuration to your MCP config:
```json
{
"mcpServers": {
"gradio": {
"url": "https://gradio-docs-mcp.hf.space/gradio_api/mcp/"
}
}
}
```
We've included step-by-step instructions for Cursor below, but... | Installing in the Clients | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs Mcp Guide |
There are currently only two tools in the server: `gradio_docs_mcp_load_gradio_docs` and `gradio_docs_mcp_search_gradio_docs`.
1. `gradio_docs_mcp_load_gradio_docs`: This tool takes no arguments and will load an /llms.txt style summary of Gradio's latest, full documentation. Very useful context the LLM can parse befo... | Tools | https://gradio.app/guides/using-docs-mcp | Mcp - Using Docs 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 |
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 |
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 |
To add custom buttons to a component, pass a list of `gr.Button()` instances to the `buttons` parameter:
```python
import gradio as gr
refresh_btn = gr.Button("Refresh", variant="secondary", size="sm")
clear_btn = gr.Button("Clear", variant="secondary", size="sm")
textbox = gr.Textbox(
value="Sample text",
l... | Basic Usage | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Custom buttons work just like regular `gr.Button` components. You can connect them to Python functions or JavaScript functions using the `.click()` method:
Python Functions
```python
def refresh_data():
import random
return f"Refreshed: {random.randint(1000, 9999)}"
refresh_btn.click(refresh_data, outputs=te... | Connecting Button Events | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
Here's a complete example showing custom buttons with both Python and JavaScript functions:
$code_textbox_custom_buttons
| Complete Example | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
- Custom buttons appear in the component's toolbar, typically in the top-right corner
- Only the `value` of the Button is used, other attributes like `icon` are not used.
- Buttons are rendered in the order they appear in the `buttons` list
- Built-in buttons (like "copy", "download") can be hidden by omitting them fro... | Notes | https://gradio.app/guides/custom-buttons | Additional Features - Custom Buttons Guide |
**API endpoint names**
When you create a Gradio application, the API endpoint names are automatically generated based on the function names. You can change this by using the `api_name` parameter in `gr.Interface` or `gr.ChatInterface`. If you are using Gradio `Blocks`, you can name each event listener, like this:
```... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
**Adding API endpoints**
You can also add new API routes to your Gradio application that do not correspond to events in your UI.
For example, in this Gradio application, we add a new route that adds numbers and slices a list:
```py
import gradio as gr
with gr.Blocks() as demo:
with gr.Row():
input = gr... | Configuring the API Page | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
This API page not only lists all of the endpoints that can be used to query the Gradio app, but also shows the usage of both [the Gradio Python client](https://gradio.app/guides/getting-started-with-the-python-client/), and [the Gradio JavaScript client](https://gradio.app/guides/getting-started-with-the-js-client/).
... | The Clients | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Instead of reading through the view API page, you can also use Gradio's built-in API recorder to generate the relevant code snippet. Simply click on the "API Recorder" button, use your Gradio app via the UI as you would normally, and then the API Recorder will generate the code using the Clients to recreate your all of... | The API Recorder 🪄 | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
The API page also includes instructions on how to use the Gradio app as an Model Context Protocol (MCP) server, which is a standardized way to expose functions as tools so that they can be used by LLMs.

... | MCP Server | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
You can access the complete OpenAPI (formerly Swagger) specification of your Gradio app's API at the endpoint `<your-gradio-app-url>/gradio_api/openapi.json`. The OpenAPI specification is a standardized, language-agnostic interface description for REST APIs that enables both humans and computers to discover and underst... | OpenAPI Specification | https://gradio.app/guides/view-api-page | Additional Features - View Api Page Guide |
Let's create a demo where a user can choose a filter to apply to their webcam stream. Users can choose from an edge-detection filter, a cartoon filter, or simply flipping the stream vertically.
$code_streaming_filter
$demo_streaming_filter
You will notice that if you change the filter value it will immediately take e... | A Realistic Image Demo | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For some image streaming demos, like the one above, we don't need to display separate input and output components. Our app would look cleaner if we could just display the modified output stream.
We can do so by just specifying the input image component as the output of the stream event.
$code_streaming_filter_unified... | Unified Image Demos | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
Your streaming function should be stateless. It should take the current input and return its corresponding output. However, there are cases where you may want to keep track of past inputs or outputs. For example, you may want to keep a buffer of the previous `k` inputs to improve the accuracy of your transcription demo... | Keeping track of past inputs or outputs | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
For an end-to-end example of streaming from the webcam, see the object detection from webcam [guide](/main/guides/object-detection-from-webcam-with-webrtc). | End-to-End Examples | https://gradio.app/guides/streaming-inputs | Additional Features - Streaming Inputs Guide |
You can initialize the `I18n` class with multiple language dictionaries to add custom translations:
```python
import gradio as gr
Create an I18n instance with translations for multiple languages
i18n = gr.I18n(
en={"greeting": "Hello, welcome to my app!", "submit": "Submit"},
es={"greeting": "¡Hola, bienvenid... | Setting Up Translations | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
When you use the `i18n` instance with a translation key, Gradio will show the corresponding translation to users based on their browser's language settings or the language they've selected in your app.
If a translation isn't available for the user's locale, the system will fall back to English (if available) or displa... | How It Works | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
Locale codes should follow the BCP 47 format (e.g., 'en', 'en-US', 'zh-CN'). The `I18n` class will warn you if you use an invalid locale code.
| Valid Locale Codes | https://gradio.app/guides/internationalization | Additional Features - Internationalization Guide |
The following component properties typically support internationalization:
- `description`
- `info`
- `title`
- `placeholder`
- `value`
- `label`
Note that support may vary depending on the component, and some properties might have exceptions where internationalization is not applicable. You can check this by referri... | Supported Component Properties | https://gradio.app/guides/internationalization | Additional Features - Internationalization 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.