text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
183 values
source_page_title
stringclasses
183 values
- 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 import time from gradio_client import Client sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace') sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace') mcp = FastMCP("huggingface_spaces_image_display") @mcp.tool() async def generate_image(prompt: str, width: int = 512, height: int = 512) -> str: """Generate an image using SanaSprint model. Args: prompt: Text prompt describing the image to generate width: Image width (default: 512) height: Image height (default: 512) """ client = Client("https://ysharma-sanasprint.hf.space/") try: result = client.predict( prompt, "0.6B", 0, True, width, height, 4.0, 2, api_name="/infer" ) if isinstance(result, list) and len(result) >= 1: image_data = result[0] if isinstance(image_data, dict) and "url" in image_data: return json.dumps({ "type": "image", "url": image_data["url"], "message": f"Generated image for prompt: {prompt}" }) return json.dumps({ "type": "error", "message": "Failed to generate image" }) except Exception as e: return json.dumps({ "type": "error", "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 `gene
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 nature of image generation by polling for results 4. When an image is ready, it returns the URL in a structured JSON format
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 ChatMessage from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client from anthropic import Anthropic from dotenv import load_dotenv load_dotenv() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) class MCPClientWrapper: def __init__(self): self.session = None self.exit_stack = None self.anthropic = Anthropic() self.tools = [] def connect(self, server_path: str) -> str: return loop.run_until_complete(self._connect(server_path)) async def _connect(self, server_path: str) -> str: if self.exit_stack: await self.exit_stack.aclose() self.exit_stack = AsyncExitStack() is_python = server_path.endswith('.py') command = "python" if is_python else "node" server_params = StdioServerParameters( command=command, args=[server_path], env={"PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"} ) stdio_transport = await self.exit_stack.enter_async_context(stdio_client(server_params)) self.stdio, self.write = stdio_transport self.session = await self.exit_stack.enter_async_context(ClientSession(self.stdio, self.write)) await self.session.initialize() response = await self.session.list_tools() self.tools = [{ "name": tool.name, "description": tool.description, "input_schema": tool.inputSchema } for tool in response.tools] tool_names = [tool["name"] for tool in self.tools] return f"Connected to MCP server.
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, Any], ChatMessage]]) -> tuple: if not self.session: return history + [ {"role": "user", "content": message}, {"role": "assistant", "content": "Please connect to an MCP server first."} ], gr.Textbox(value="") new_messages = loop.run_until_complete(self._process_query(message, history)) return history + [{"role": "user", "content": message}] + new_messages, gr.Textbox(value="") async def _process_query(self, message: str, history: List[Union[Dict[str, Any], ChatMessage]]): claude_messages = [] for msg in history: if isinstance(msg, ChatMessage): role, content = msg.role, msg.content else: role, content = msg.get("role"), msg.get("content") if role in ["user", "assistant", "system"]: claude_messages.append({"role": role, "content": content}) claude_messages.append({"role": "user", "content": message}) response = self.anthropic.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1000, messages=claude_messages, tools=self.tools ) result_messages = [] for content in response.content: if content.type == 'text': result_messages.append({ "role": "assistant", "content": content.text }) elif content.type == 'tool_use': tool_name = content.name tool_args = content.input
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'll use the {tool_name} tool to help answer your question.", "metadata": { "title": f"Using tool: {tool_name}", "log": f"Parameters: {json.dumps(tool_args, ensure_ascii=True)}", "status": "pending", "id": f"tool_call_{tool_name}" } }) result_messages.append({ "role": "assistant", "content": "```json\n" + json.dumps(tool_args, indent=2, ensure_ascii=True) + "\n```", "metadata": { "parent_id": f"tool_call_{tool_name}", "id": f"params_{tool_name}", "title": "Tool Parameters" } }) result = await self.session.call_tool(tool_name, tool_args) if result_messages and "metadata" in result_messages[-2]: result_messages[-2]["metadata"]["status"] = "done" result_messages.append({ "role": "assistant", "content": "Here are the results from the tool:", "metadata": { "title": f"Tool Result for {tool_name}", "status": "done", "id": f"result_{tool_name}" } }) result_content = result.content if isinstance(result_content, list): result_content = "\n".join(str(item) for item in re
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) if isinstance(result_json, dict) and "type" in result_json: if result_json["type"] == "image" and "url" in result_json: result_messages.append({ "role": "assistant", "content": {"path": result_json["url"], "alt_text": result_json.get("message", "Generated image")}, "metadata": { "parent_id": f"result_{tool_name}", "id": f"image_{tool_name}", "title": "Generated Image" } }) else: result_messages.append({ "role": "assistant", "content": "```\n" + result_content + "\n```", "metadata": { "parent_id": f"result_{tool_name}", "id": f"raw_result_{tool_name}", "title": "Raw Output" } }) except: result_messages.append({ "role": "assistant", "content": "```\n" + result_content + "\n```", "metadata": { "parent_id": f"result_{tool_name}", "id": f"raw_result_{tool_name}", "title": "Raw Output" } })
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_content}"}) next_response = self.anthropic.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1000, messages=claude_messages, ) if next_response.content and next_response.content[0].type == 'text': result_messages.append({ "role": "assistant", "content": next_response.content[0].text }) return result_messages client = MCPClientWrapper() def gradio_interface(): with gr.Blocks(title="MCP Weather Client") as demo: gr.Markdown("MCP Weather Assistant") gr.Markdown("Connect to your MCP weather server and chat with the assistant") with gr.Row(equal_height=True): with gr.Column(scale=4): server_path = gr.Textbox( label="Server Script Path", placeholder="Enter path to server script (e.g., weather.py)", value="gradio_mcp_server.py" ) with gr.Column(scale=1): connect_btn = gr.Button("Connect") status = gr.Textbox(label="Connection Status", interactive=False) chatbot = gr.Chatbot( value=[], height=500, show_copy_button=True, avatar_images=("👤", "🤖") ) with gr.Row(equal_height=True): msg = gr.Textbox( label="Your Question", placeholder="Ask about weather or alerts (e.g., What's the weather in New York?)",
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(client.connect, inputs=server_path, outputs=status) msg.submit(client.process_message, [msg, chatbot], [chatbot, msg]) clear_btn.click(lambda: [], None, chatbot) return demo if __name__ == "__main__": if not os.getenv("ANTHROPIC_API_KEY"): print("Warning: ANTHROPIC_API_KEY not found in environment. Please set it in your .env file.") interface = gradio_interface() interface.launch(debug=True) ``` What this MCP Client does: - Creates a friendly Gradio chat interface for user interaction - Connects to the MCP server you specify - Handles conversation history and message formatting - Makes call to Claude API with tool definitions - Processes tool usage requests from Claude - Displays images and other tool outputs in the chat - Sends tool results back to Claude for interpretation
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 "Connect" to establish the connection to the MCP server. - You should see a message indicating the server connection was successful.
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 generation requests and automatically use the `generate_image` tool from your MCP server.
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 generation API 6. The image URL is returned to the client 7. The client sends the image URL back to Claude 8. Claude provides a response that references the generated image 9. The Gradio chat interface displays both Claude's response and the 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 experience
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 virtually any external tool or service. Read our other Guide on using [Gradio apps as MCP Servers](./building-mcp-server-with-gradio).
Conclusion
https://gradio.app/guides/building-an-mcp-client-with-gradio
Mcp - Building An Mcp Client With Gradio 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 TypeScript files.
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 your HTML. This will install the latest version but we advise hardcoding the version in production. You can find all available versions [here](https://www.jsdelivr.com/package/npm/@gradio/client). This approach is ideal for experimental or prototying purposes, though has some limitations. A complete example would look like this: ```html <!DOCTYPE html> <html lang="en"> <head> <script type="module"> import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"; const client = await Client.connect("abidlabs/en2fr"); const result = await client.predict("/predict", { text: "My name is Hannah" }); console.log(result); </script> </head> </html> ```
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://huggingface.co/settings/tokens ```js import { Client } from "@gradio/client"; const app = await Client.connect("abidlabs/my-private-space", { token: "hf_..." }) ```
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://huggingface.co/settings/tokens)). `Client.duplicate` is almost identical to `Client.connect`, the only difference is under the hood: ```js import { Client, handle_file } from "@gradio/client"; const response = await fetch( "https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3" ); const audio_file = await response.blob(); const app = await Client.duplicate("abidlabs/whisper", { token: "hf_..." }); const transcription = await app.predict("/predict", [handle_file(audio_file)]); ``` If you have previously duplicated a Space, re-running `Client.duplicate` will _not_ create a new Space. Instead, the client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate` method multiple times with the same space. **Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 5 minutes of inactivity. You can also set the hardware using the `hardware` and `timeout` properties of `duplicate`'s options object like this: ```js import { Client } from "@gradio/client"; const app = await Client.duplicate("abidlabs/whisper", { token: "hf_...", timeout: 60, hardware: "a10g-small" }); ```
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(); console.log(app_info); ``` And we will see the following: ```json { "named_endpoints": { "/predict": { "parameters": [ { "label": "text", "component": "Textbox", "type": "string" } ], "returns": [ { "label": "output", "component": "Textbox", "type": "string" } ] } }, "unnamed_endpoints": {} } ``` This shows us that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `string`, which is a url to a file. We should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available. If an app has unnamed API endpoints, these can also be displayed by running `.view_api(all_endpoints=True)`.
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. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png) The View API page also includes an "API Recorder" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the JS Client.
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 should pass them as an array to `.predict()`, like this: ```js import { Client } from "@gradio/client"; const app = await Client.connect("gradio/calculator"); const result = await app.predict("/predict", [4, "add", 5]); ``` For certain inputs, such as images, you should pass in a `Buffer`, `Blob` or `File` depending on what is most convenient. In node, this would be a `Buffer` or `Blob`; in a browser environment, this would be a `Blob` or `File`. ```js import { Client, handle_file } from "@gradio/client"; const response = await fetch( "https://audio-samples.github.io/samples/mp3/blizzard_unconditional/sample-0.mp3" ); const audio_file = await response.blob(); const app = await Client.connect("abidlabs/whisper"); const result = await app.predict("/predict", [handle_file(audio_file)]); ```
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 responses. ```js import { Client } from "@gradio/client"; function log_result(payload) { const { data: [translation] } = payload; console.log(`The translated result is: ${translation}`); } const app = await Client.connect("abidlabs/en2fr"); const job = app.submit("/predict", ["Hello"]); for await (const message of job) { log_result(message); } ```
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 that status messages are also reported to the client. `status`es are returned as an object with the following attributes: `status` (a human readbale status of the current job, `"pending" | "generating" | "complete" | "error"`), `code` (the detailed gradio code for the job), `position` (the current position of this job in the queue), `queue_size` (the total queue size), `eta` (estimated time this job will complete), `success` (a boolean representing whether the job completed successfully), and `time` ( as `Date` object detailing the time that the status was generated). ```js import { Client } from "@gradio/client"; function log_status(status) { console.log( `The current status for this job is: ${JSON.stringify(status, null, 2)}.` ); } const app = await Client.connect("abidlabs/en2fr", { events: ["status", "data"] }); const job = app.submit("/predict", ["Hello"]); for await (const message of job) { if (message.type === "status") { log_status(message); } } ```
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", ["Friends"]); job_one.cancel(); job_two.cancel(); ``` If the first job has started processing, then it will not be canceled but the client will no longer listen for updates (throwing away the job). If the second job has not yet started, it will be successfully canceled and removed from the queue.
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 await (const message of job) { console.log(message.data); } ``` This will log out the values as they are generated by the endpoint. You can also cancel jobs that that have iterative outputs, in which case the job will finish immediately. ```js import { Client } from "@gradio/client"; const app = await Client.connect("gradio/count_generator"); const job = app.submit(0, [9]); for await (const message of job) { console.log(message.data); } setTimeout(() => { job.cancel(); }, 3000); ```
Generator Endpoints
https://gradio.app/guides/getting-started-with-the-js-client
Gradio Clients And Lite - Getting Started With The Js Client 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 Space takes an audio file and produces two separate audio files: one with the instrumental music and one with all other sounds in the original clip. Perfect to use with our client! Open a new Python file, say `main.py`, and start by importing the `Client` class from `gradio_client` and connecting it to this Space: ```py from gradio_client import Client, handle_file client = Client("abidlabs/music-separation") def acapellify(audio_path): result = client.predict(handle_file(audio_path), api_name="/predict") return result[0] ``` That's all the code that's needed -- notice that the API endpoints returns two audio files (one without the music, and one with just the music) in a list, and so we just return the first element of the list. --- **Note**: since this is a public Space, there might be other users using this Space as well, which might result in a slow experience. You can duplicate this Space with your own [Hugging Face token](https://huggingface.co/settings/tokens) and create a private Space that only you have will have access to and bypass the queue. To do that, simply replace the first two lines above with: ```py from gradio_client import Client client = Client.duplicate("abidlabs/music-separation", token=YOUR_HF_TOKEN) ``` Everything else remains the same! --- Now, of course, we are working with video files, so we first need to extract the audio from the video files. For this, we will be using the `ffmpeg` library, which does a lot of 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 proc
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 using `ffmpeg`. 2. Then, we pass in the audio file through the `acapellify()` function above. 3. Finally, we combine the new audio with the original video to produce a final acapellified video. Here's the complete code in Python, which you can add to your `main.py` file: ```python import subprocess def process_video(video_path): old_audio = os.path.basename(video_path).split(".")[0] + ".m4a" subprocess.run(['ffmpeg', '-y', '-i', video_path, '-vn', '-acodec', 'copy', old_audio]) new_audio = acapellify(old_audio) new_video = f"acap_{video_path}" subprocess.call(['ffmpeg', '-y', '-i', video_path, '-i', new_audio, '-map', '0:v', '-map', '1:a', '-c:v', 'copy', '-c:a', 'aac', '-strict', 'experimental', f"static/{new_video}"]) return new_video ``` You can read up on [ffmpeg documentation](https://ffmpeg.org/ffmpeg.html) if you'd like to understand all of the command line parameters, as they are beyond the scope of this tutorial.
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 fastapi.responses import HTMLResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates app = FastAPI() os.makedirs("static", exist_ok=True) app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") videos = [] @app.get("/", response_class=HTMLResponse) async def home(request: Request): return templates.TemplateResponse( "home.html", {"request": request, "videos": videos}) @app.post("/uploadvideo/") async def upload_video(video: UploadFile = File(...)): video_path = video.filename with open(video_path, "wb+") as fp: fp.write(video.file.read()) new_video = process_video(video.filename) videos.append(new_video) return RedirectResponse(url='/', status_code=303) ``` In this example, the FastAPI app has two routes: `/` and `/uploadvideo/`. The `/` route returns an HTML template that displays a gallery of all uploaded videos. The `/uploadvideo/` route accepts a `POST` request with an `UploadFile` object, which represents the uploaded video file. The video file is "acapellified" via the `process_video()` method, and the output video is stored in a list which stores all of the uploaded videos in memory. Note that this is a very basic example and if this were a production app, you will need to add more logic to handle file storage, user authentication, and security considerations.
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 following as the contents of `home.html`: ```html &lt;!DOCTYPE html> &lt;html> &lt;head> &lt;title>Video Gallery&lt;/title> &lt;style> body { font-family: sans-serif; margin: 0; padding: 0; background-color: f5f5f5; } h1 { text-align: center; margin-top: 30px; margin-bottom: 20px; } .gallery { display: flex; flex-wrap: wrap; justify-content: center; gap: 20px; padding: 20px; } .video { border: 2px solid ccc; box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2); border-radius: 5px; overflow: hidden; width: 300px; margin-bottom: 20px; } .video video { width: 100%; height: 200px; } .video p { text-align: center; margin: 10px 0; } form { margin-top: 20px; text-align: center; } input[type="file"] { display: none; } .upload-btn { display: inline-block; background-color: 3498db; color: fff; padding: 10px 20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; } .upload-btn:hover { background-color: 2980b9; } .file-name { margin-left: 10px; } &lt;/style> &lt;/head> &lt;body> &lt;h1>Video Gallery&lt;/h1> {% if videos %} &lt;div class="gallery"> {% for video in videos %} &lt;div class="video"> &lt;video controls> &lt;source src="{{ url_for('static', path=video) }}" type="video/mp4"> Your browser does not support the video tag. &lt;/video> &lt;p>{{ video }}&lt;/p> &lt;/div> {% endfor %} &lt;/div> {% else %} &lt;p>No videos uploaded yet.&lt;/p> {% endif %} &lt;form action="/uploadvideo/" method="post" enctype="multipart/form-data"> &lt;label for="video-upload" class="upload-btn">Choose video file&lt;/label> &lt;input type="file" name="video" id="video-upload"> &lt;span class="file-name">&lt;/span> &lt;button type="submit" class="upload-btn">Upload&lt;/butto
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&lt;/label> &lt;input type="file" name="video" id="video-upload"> &lt;span class="file-name">&lt;/span> &lt;button type="submit" class="upload-btn">Upload&lt;/button> &lt;/form> &lt;script> // Display selected file name in the form const fileUpload = document.getElementById("video-upload"); const fileName = document.querySelector(".file-name"); fileUpload.addEventListener("change", (e) => { fileName.textContent = e.target.files[0].name; }); &lt;/script> &lt;/body> &lt;/html> ```
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://abidlabs-music-separation.hf.space ✔ INFO: Started server process [1360] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` And that's it! Start uploading videos and you'll get some "acapellified" videos in response (might take seconds to minutes to process depending on the length of your videos). Here's how the UI looks after uploading two videos: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/acapellify.png) If you'd like to learn more about how to use the Gradio Python Client in your projects, [read the dedicated Guide](/guides/getting-started-with-the-python-client/).
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
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 with **Python versions 3.10 or higher**: ```bash $ pip install --upgrade gradio_client ```
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 token with the `token` parameter. You can get your HF token here: https://huggingface.co/settings/tokens ```python from gradio_client import Client client = Client("abidlabs/my-private-space", token="...") ```
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.duplicate()` to make this process simple (you'll need to pass in your [Hugging Face token](https://huggingface.co/settings/tokens) or be logged in using the Hugging Face CLI): ```python import os from gradio_client import Client, handle_file HF_TOKEN = os.environ.get("HF_TOKEN") client = Client.duplicate("abidlabs/whisper", token=HF_TOKEN) client.predict(handle_file("audio_sample.wav")) >> "This is a test of the whisper speech recognition model." ``` If you have previously duplicated a Space, re-running `duplicate()` will _not_ create a new Space. Instead, the Client will attach to the previously-created Space. So it is safe to re-run the `Client.duplicate()` method multiple times. **Note:** if the original Space uses GPUs, your private Space will as well, and your Hugging Face account will get billed based on the price of the GPU. To minimize charges, your Space will automatically go to sleep after 1 hour of inactivity. You can also set the hardware using the `hardware` parameter of `duplicate()`.
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 Parameters: - [Audio] audio: filepath (required) Returns: - [Textbox] output: str ``` We see that we have 1 API endpoint in this space, and shows us how to use the API endpoint to make a prediction: we should call the `.predict()` method (which we will explore below), providing a parameter `input_audio` of type `str`, which is a `filepath or URL`. We should also provide the `api_name='/predict'` argument to the `predict()` method. Although this isn't necessary if a Gradio app has only 1 named endpoint, it does allow us to call different endpoints in a single app if they are available.
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. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/view-api.png) The View API page also includes an "API Recorder" that lets you interact with the Gradio UI normally and converts your interactions into the corresponding code to run with the Python Client.
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 separate arguments to `.predict()`, like this: ```python from gradio_client import Client client = Client("gradio/calculator") client.predict(4, "add", 5) >> 9.0 ``` It is recommended to provide key-word arguments instead of positional arguments: ```python from gradio_client import Client client = Client("gradio/calculator") client.predict(num1=4, operation="add", num2=5) >> 9.0 ``` This allows you to take advantage of default arguments. For example, this Space includes the default value for the Slider component so you do not need to provide it when accessing it with the client. ```python from gradio_client import Client client = Client("abidlabs/image_generator") client.predict(text="an astronaut riding a camel") ``` The default value is the initial value of the corresponding Gradio component. If the component does not have an initial value, but if the corresponding argument in the predict function has a default value of `None`, then that parameter is also optional in the client. Of course, if you'd like to override it, you can include it as well: ```python from gradio_client import Client client = Client("abidlabs/image_generator") client.predict(text="an astronaut riding a camel", steps=25) ``` For providing files or URLs as inputs, you should pass in the filepath or URL to the file enclosed within `gradio_client.handle_file()`. This takes care of uploading the file to the Gradio server and ensures that the file is preprocessed correctly: ```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/s
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't find simpus, and devoted abode, to at might in a r—" ```
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()` method, and then later calling `.result()` on the job to get the result. For example: ```python from gradio_client import Client client = Client(space="abidlabs/en2fr") job = client.submit("Hello", api_name="/predict") This is not blocking Do something else job.result() This is blocking >> Bonjour ```
Running jobs asynchronously
https://gradio.app/guides/getting-started-with-the-python-client
Gradio Clients And Lite - Getting Started With The Python Client Guide
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", result_callbacks=[print_result]) Do something else >> The translated result is: Bonjour ```
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 this job in the queue), `queue_size` (the total queue size), `eta` (estimated time this job will complete), `success` (a boolean representing whether the job completed successfully), and `time` (the time that the status was generated). ```py from gradio_client import Client client = Client(src="gradio/calculator") job = client.submit(5, "add", 4, api_name="/predict") job.status() >> <Status.STARTING: 'STARTING'> ``` _Note_: The `Job` class also has a `.done()` instance method which returns a boolean indicating whether the job has completed.
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 False, assuming the job has started job2.cancel() will return True, indicating that the job has been canceled ``` If the first job has started processing, then it will not be canceled. If the second job has not yet started, it will be successfully canceled and removed from the queue.
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 = client.submit(3, api_name="/count") while not job.done(): time.sleep(0.1) job.outputs() >> ['0', '1', '2'] ``` Note that running `job.result()` on a generator endpoint only gives you the _first_ value returned by the endpoint. The `Job` object is also iterable, which means you can use it to display the results of a generator function as they are returned from the endpoint. Here's the equivalent example using the `Job` as a generator: ```py from gradio_client import Client client = Client(src="gradio/count_generator") job = client.submit(3, api_name="/count") for o in job: print(o) >> 0 >> 1 >> 2 ``` You can also cancel jobs that that have iterative outputs, in which case the job will finish as soon as the current iteration finishes running. ```py from gradio_client import Client import time client = Client("abidlabs/test-yield") job = client.submit("abcdef") time.sleep(3) job.cancel() job cancels after 2 iterations ```
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. When a user submits a new word, it is added to the state, and the number of previous occurrences of that word is displayed: ```python import gradio as gr def count(word, list_of_words): return list_of_words.count(word), list_of_words + [word] with gr.Blocks() as demo: words = gr.State([]) textbox = gr.Textbox() number = gr.Number() textbox.submit(count, inputs=[textbox, words], outputs=[number, words]) demo.launch() ``` If you were to connect this this Gradio app using the Python Client, you would notice that the API information only shows a single input and output: ```csv Client.predict() Usage Info --------------------------- Named API endpoints: 1 - predict(word, api_name="/count") -> value_31 Parameters: - [Textbox] word: str (required) Returns: - [Number] value_31: float ``` That is because the Python client handles state automatically for you -- as you make a series of requests, the returned state from one request is stored internally and automatically supplied for the subsequent request. If you'd like to reset the state, you can do that by calling `Client.reset_session()`.
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
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 for building Machine Learning Web Applications and sharing them with the world - all with just python! 🐍
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 prompt, the `ImageCaptioningTool` to caption the generated image, and the `TextToVideoTool` to create a video from a prompt. We then tell our agent to create an image of a dog riding a skateboard, but to please improve our prompt ahead of time. We also ask it to caption the generated image and create a video for it. The agent can decide which tool to use without us explicitly telling it. ```python import os if not os.getenv("OPENAI_API_KEY"): raise ValueError("OPENAI_API_KEY must be set") from langchain.agents import initialize_agent from langchain.llms import OpenAI from gradio_tools import (StableDiffusionTool, ImageCaptioningTool, StableDiffusionPromptGeneratorTool, TextToVideoTool) from langchain.memory import ConversationBufferMemory llm = OpenAI(temperature=0) memory = ConversationBufferMemory(memory_key="chat_history") tools = [StableDiffusionTool().langchain, ImageCaptioningTool().langchain, StableDiffusionPromptGeneratorTool().langchain, TextToVideoTool().langchain] agent = initialize_agent(tools, llm, memory=memory, agent="conversational-react-description", verbose=True) output = agent.run(input=("Please create a photo of a dog riding a skateboard " "but improve my prompt prior to using an image generator." "Please caption the generated image and create a video for it using the improved prompt.")) ``` You'll note that we are using some pre-built tools 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
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 next section will cover.
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: pass @abstractmethod def postprocess(self, output: Tuple[Any] | Any) -> str: pass ``` The requirements are: 1. The name for your tool 2. The description for your tool. This is crucial! Agents decide which tool to use based on their description. Be precise and be sure to include example of what the input and the output of the tool should look like. 3. The url or space id, e.g. `freddyaboulton/calculator`, of the Gradio application. Based on this value, `gradio_tool` will create a [gradio client](https://github.com/gradio-app/gradio/blob/main/client/python/README.md) instance to query the upstream application via API. Be sure to click the link and learn more about the gradio client library if you are not familiar with it. 4. create_job - Given a string, this method should parse that string and return a job from the client. Most times, this is as simple as passing the string to the `submit` function of the client. More info on creating jobs [here](https://github.com/gradio-app/gradio/blob/main/client/python/README.mdmaking-a-prediction) 5. postprocess - Given the result of the job, convert it to a string the LLM can display to the user. 6. _Optional_ - Some libraries, e.g. [MiniChain](https://github.com/srush/MiniChain/tree/main), may need some info about the underlying gradio input and output types used by the tool. By default, this will return gr.Textbox() but if you'd like to provide more accurate info, implement the `_block_input(self, 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
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, open a pull request to the `gradio_tools` repo! We welcome all contributions.
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 generator. Use this to generate images based on " "text input. Input should be a description of what the image should " "look like. The output will be a path to an image file." ), src="gradio-client-demos/stable-diffusion", token=None, ) -> None: super().__init__(name, description, src, token) def create_job(self, query: str) -> Job: return self.client.submit(query, "", 9, fn_index=1) def postprocess(self, output: str) -> str: return [os.path.join(output, i) for i in os.listdir(output) if not i.endswith("json")][0] def _block_input(self, gr) -> "gr.components.Component": return gr.Textbox() def _block_output(self, gr) -> "gr.components.Component": return gr.Image() ``` Some notes on this implementation: 1. All instances of `GradioTool` have an attribute called `client` that is a pointed to the underlying [gradio client](https://github.com/gradio-app/gradio/tree/main/client/pythongradio_client-use-a-gradio-app-as-an-api----in-3-lines-of-python). That is what you should use in the `create_job` method. 2. `create_job` just passes the query string to the `submit` function of the client with some other parameters hardcoded, i.e. the negative prompt string and the guidance scale. We could modify our tool to also accept these values from the input string in a subsequent version. 3. The `postprocess` method simply returns the first image from the gallery of images created by the stable diffusion space. We use the `os` module to get the full path of the image.
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
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 URL of the Space webpage. For example: ```bash ❌ Space URL: https://huggingface.co/spaces/abidlabs/en2fr ✅ Gradio app URL: https://abidlabs-en2fr.hf.space/ ``` You can get the Gradio app URL by clicking the "view API" link at the bottom of the page. Or, you can right-click on the page and then click on "View Frame Source" or the equivalent in your browser to view the URL of the embedded Gradio app. 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! Note: to query private Spaces, you will need to pass in your Hugging Face (HF) token. You can get your HF token here: https://huggingface.co/settings/tokens. In this case, you will need to include an additional header in both of your `curl` calls that we'll discuss below: ```bash -H "Authorization: Bearer $HF_TOKEN" ``` Now, we are ready to make the two `curl` requests.
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 obtained in Step 0 * `$API_NAME` is the name of the API endpoint for the event that you are running. You can get the API endpoint names by clicking the "view API" link at the bottom of the page. * `$PAYLOAD` is a valid JSON data list containing the input payload, one element for each input component. When you make this `POST` request successfully, you will get an event id that is printed to the terminal in this format: ```bash >> {"event_id": $EVENT_ID} ``` This `EVENT_ID` will be needed in the subsequent `curl` request to fetch the results of the prediction. Here are some examples of how to make the `POST` request **Basic Example** Revisiting the example at the beginning of the page, here is how to make the `POST` request for a simple Gradio application that takes in a single input text component: ```bash $ curl -X POST https://abidlabs-en2fr.hf.space/call/predict -H "Content-Type: application/json" -d '{ "data": ["Hello, my friend."] }' ``` **Multiple Input Components** This [Gradio demo](https://huggingface.co/spaces/gradio/hello_world_3) accepts three inputs: a string corresponding to the `gr.Textbox`, a boolean value corresponding to the `gr.Checkbox`, and a numerical value corresponding to the `gr.Slider`. Here is the `POST` request: ```bash curl -X POST https://gradio-hello-world-3.hf.space/call/predict -H "Content-Type: application/json" -d '{ "data": ["Hello", true, 5] }' ``` **Private Spaces** As mentioned earlier, if you are making 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
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 $HF_TOKEN" -d '{ "data": ["Hello, my friend."] }' ``` **Files** If you are using `curl` to query a Gradio application that requires file inputs, the files *need* to be provided as URLs, and The URL needs to be enclosed in a dictionary in this format: ```bash {"path": $URL} ``` Here is an example `POST` request: ```bash $ curl -X POST https://gradio-image-mod.hf.space/call/predict -H "Content-Type: application/json" -d '{ "data": [{"path": "https://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.png"}] }' ``` **Stateful Demos** If your Gradio demo [persists user state](/guides/interface-state) across multiple interactions (e.g. is a chatbot), you can pass in a `session_hash` alongside the `data`. Requests with the same `session_hash` are assumed to be part of the same user session. Here's how that might look: ```bash These two requests will share a session curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{ "data": ["Are you sentient?"], "session_hash": "randomsequence1234" }' curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{ "data": ["Really?"], "session_hash": "randomsequence1234" }' This request will be treated as a new session curl -X POST https://gradio-chatinterface-random-response.hf.space/call/chat -H "Content-Type: application/json" -d '{ "data": ["Are you sentient?"], "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
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 a `GET` request with the following syntax: ```bash $ curl -N $URL/call/$API_NAME/$EVENT_ID ``` Tip: If you are fetching results from a private Space, include a header with your HF token like this: `-H "Authorization: Bearer $HF_TOKEN"` in the `GET` request. This should produce a stream of responses in this format: ```bash event: ... data: ... event: ... data: ... ... ``` Here: `event` can be one of the following: * `generating`: indicating an intermediate result * `complete`: indicating that the prediction is complete and the final result * `error`: indicating that the prediction was not completed successfully * `heartbeat`: sent every 15 seconds to keep the request alive The `data` is in the same format as the input payload: valid JSON data list containing the output result, one element for each output component. Here are some examples of what results you should expect if a request is completed successfully: **Basic Example** Revisiting the example at the beginning of the page, we would expect the result to look like this: ```bash event: complete data: ["Bonjour, mon ami."] ``` **Multiple Outputs** If your endpoint returns multiple values, they will appear as elements of the `data` list: ```bash event: complete data: ["Good morning Hello. It is 5 degrees today", -15.0] ``` **Streaming Example** If your Gradio app [streams a sequence of values](/guides/streaming-outputs), then they will be streamed directly to your terminal, like this: ```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, w
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 be represented as a dictionary in this format (including potentially some additional keys): ```python { "orig_name": "example.jpg", "path": "/path/in/server.jpg", "url": "https:/example.com/example.jpg", "meta": {"_type": "gradio.FileData"} } ``` In your terminal, it may appear like this: ```bash event: complete data: [{"path": "/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp", "url": "https://gradio-image-mod.hf.space/c/file=/tmp/gradio/359933dc8d6cfe1b022f35e2c639e6e42c97a003/image.webp", "size": null, "orig_name": "image.webp", "mime_type": null, "is_stream": false, "meta": {"_type": "gradio.FileData"}}] ```
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 and password: ```bash curl -X POST $URL/login \ -d "username=$USERNAME&password=$PASSWORD" \ -c cookies.txt ``` If the credentials are correct, you'll get `{"success":true}` in response and the cookies will be saved in `cookies.txt`. Next, you'll need to include these cookies when you make the original `POST` request, like this: ```bash $ curl -X POST $URL/call/$API_NAME -b cookies.txt -H "Content-Type: application/json" -d '{ "data": $PAYLOAD }' ``` Finally, you'll need to `GET` the results, again supplying the cookies from the file: ```bash curl -N $URL/call/$API_NAME/$EVENT_ID -b cookies.txt ```
Authentication
https://gradio.app/guides/querying-gradio-apps-with-curl
Gradio Clients And Lite - Querying Gradio Apps With Curl Guide
For this demo we will be tweaking the existing Gradio `Chatbot` component to display text and media files in the same message. Let's create a new custom component directory by templating off of the `Chatbot` component source code. ```bash gradio cc create MultimodalChatbot --template Chatbot ``` And we're ready to go! Tip: Make sure to modify the `Author` key in the `pyproject.toml` file.
Part 1 - Creating our project
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Open up the `multimodalchatbot.py` file in your favorite code editor and let's get started modifying the backend of our component. The first thing we will do is create the `data_model` of our component. The `data_model` is the data format that your python component will receive and send to the javascript client running the UI. You can read more about the `data_model` in the [backend guide](./backend). For our component, each chatbot message will consist of two keys: a `text` key that displays the text message and an optional list of media files that can be displayed underneath the text. Import the `FileData` and `GradioModel` classes from `gradio.data_classes` and modify the existing `ChatbotData` class to look like the following: ```python class FileMessage(GradioModel): file: FileData alt_text: Optional[str] = None class MultimodalMessage(GradioModel): text: Optional[str] = None files: Optional[List[FileMessage]] = None class ChatbotData(GradioRootModel): root: List[Tuple[Optional[MultimodalMessage], Optional[MultimodalMessage]]] class MultimodalChatbot(Component): ... data_model = ChatbotData ``` Tip: The `data_model`s are implemented using `Pydantic V2`. Read the documentation [here](https://docs.pydantic.dev/latest/). We've done the hardest part already!
Part 2a - The backend data_model
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
For the `preprocess` method, we will keep it simple and pass a list of `MultimodalMessage`s to the python functions that use this component as input. This will let users of our component access the chatbot data with `.text` and `.files` attributes. This is a design choice that you can modify in your implementation! We can return the list of messages with the `root` property of the `ChatbotData` like so: ```python def preprocess( self, payload: ChatbotData | None, ) -> List[MultimodalMessage] | None: if payload is None: return payload return payload.root ``` Tip: Learn about the reasoning behind the `preprocess` and `postprocess` methods in the [key concepts guide](./key-component-concepts) In the `postprocess` method we will coerce each message returned by the python function to be a `MultimodalMessage` class. We will also clean up any indentation in the `text` field so that it can be properly displayed as markdown in the frontend. We can leave the `postprocess` method as is and modify the `_postprocess_chat_messages` ```python def _postprocess_chat_messages( self, chat_message: MultimodalMessage | dict | None ) -> MultimodalMessage | None: if chat_message is None: return None if isinstance(chat_message, dict): chat_message = MultimodalMessage(**chat_message) chat_message.text = inspect.cleandoc(chat_message.text or "") for file_ in chat_message.files: file_.file.mime_type = client_utils.get_mimetype(file_.file.path) return chat_message ``` Before we wrap up with the backend code, let's modify the `example_value` and `example_payload` method to return a valid dictionary representation of the `ChatbotData`: ```python def example_value(self) -> Any: return [[{"text": "Hello!", "files": []}, None]] def example_payload(self) -> Any: return [[{"text": "Hello!", "files": []}, None]] ``` Congrats - the backend is complete!
Part 2b - The pre and postprocess methods
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
The frontend for the `Chatbot` component is divided into two parts - the `Index.svelte` file and the `shared/Chatbot.svelte` file. The `Index.svelte` file applies some processing to the data received from the server and then delegates the rendering of the conversation to the `shared/Chatbot.svelte` file. First we will modify the `Index.svelte` file to apply processing to the new data type the backend will return. Let's begin by porting our custom types from our python `data_model` to typescript. Open `frontend/shared/utils.ts` and add the following type definitions at the top of the file: ```ts export type FileMessage = { file: FileData; alt_text?: string; }; export type MultimodalMessage = { text: string; files?: FileMessage[]; } ``` Now let's import them in `Index.svelte` and modify the type annotations for `value` and `_value`. ```ts import type { FileMessage, MultimodalMessage } from "./shared/utils"; export let value: [ MultimodalMessage | null, MultimodalMessage | null ][] = []; let _value: [ MultimodalMessage | null, MultimodalMessage | null ][]; ``` We need to normalize each message to make sure each file has a proper URL to fetch its contents from. We also need to format any embedded file links in the `text` key. Let's add a `process_message` utility function and apply it whenever the `value` changes. ```ts function process_message(msg: MultimodalMessage | null): MultimodalMessage | null { if (msg === null) { return msg; } msg.text = redirect_src_url(msg.text); msg.files = msg.files.map(normalize_messages); return msg; } $: _value = value ? value.map(([user_msg, bot_msg]) => [ process_message(user_msg), process_message(bot_msg) ]) : []; ```
Part 3a - The Index.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Let's begin similarly to the `Index.svelte` file and let's first modify the type annotations. Import `Mulimodal` message at the top of the `<script>` section and use it to type the `value` and `old_value` variables. ```ts import type { MultimodalMessage } from "./utils"; export let value: | [ MultimodalMessage | null, MultimodalMessage | null ][] | null; let old_value: | [ MultimodalMessage | null, MultimodalMessage | null ][] | null = null; ``` We also need to modify the `handle_select` and `handle_like` functions: ```ts function handle_select( i: number, j: number, message: MultimodalMessage | null ): void { dispatch("select", { index: [i, j], value: message }); } function handle_like( i: number, j: number, message: MultimodalMessage | null, liked: boolean ): void { dispatch("like", { index: [i, j], value: message, liked: liked }); } ``` Now for the fun part, actually rendering the text and files in the same message! You should see some code like the following that determines whether a file or a markdown message should be displayed depending on the type of the message: ```svelte {if typeof message === "string"} <Markdown {message} {latex_delimiters} {sanitize_html} {render_markdown} {line_breaks} on:load={scroll} /> {:else if message !== null && message.file?.mime_type?.includes("audio")} <audio data-testid="chatbot-audio" controls preload="metadata" ... ``` We will modify this code to always display the text message and then loop through the files and display all of them that are present: ```svelte <Markdown message={message.text} {latex_delimiters} {sanitize_html} {render_markdown} {line_breaks} on:load={scroll} /> {each message.files as file, k} {if file !== null && fil
Part 3b - the Chatbot.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
own message={message.text} {latex_delimiters} {sanitize_html} {render_markdown} {line_breaks} on:load={scroll} /> {each message.files as file, k} {if file !== null && file.file.mime_type?.includes("audio")} <audio data-testid="chatbot-audio" controls preload="metadata" src={file.file?.url} title={file.alt_text} on:play on:pause on:ended /> {:else if message !== null && file.file?.mime_type?.includes("video")} <video data-testid="chatbot-video" controls src={file.file?.url} title={file.alt_text} preload="auto" on:play on:pause on:ended > <track kind="captions" /> </video> {:else if message !== null && file.file?.mime_type?.includes("image")} <img data-testid="chatbot-image" src={file.file?.url} alt={file.alt_text} /> {:else if message !== null && file.file?.url !== null} <a data-testid="chatbot-file" href={file.file?.url} target="_blank" download={window.__is_colab__ ? null : file.file?.orig_name || file.file?.path} > {file.file?.orig_name || file.file?.path} </a> {:else if pending_message && j === 1} <Pending {layout} /> {/if} {/each} ``` We did it! 🎉
Part 3b - the Chatbot.svelte file
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
For this tutorial, let's keep the demo simple and just display a static conversation between a hypothetical user and a bot. This demo will show how both the user and the bot can send files. In part 2 of this tutorial series we will build a fully functional chatbot demo! The demo code will look like the following: ```python import gradio as gr from gradio_multimodalchatbot import MultimodalChatbot from gradio.data_classes import FileData user_msg1 = {"text": "Hello, what is in this image?", "files": [{"file": FileData(path="https://gradio-builds.s3.amazonaws.com/diffusion_image/cute_dog.jpg")}] } bot_msg1 = {"text": "It is a very cute dog", "files": []} user_msg2 = {"text": "Describe this audio clip please.", "files": [{"file": FileData(path="cantina.wav")}]} bot_msg2 = {"text": "It is the cantina song from Star Wars", "files": []} user_msg3 = {"text": "Give me a video clip please.", "files": []} bot_msg3 = {"text": "Here is a video clip of the world", "files": [{"file": FileData(path="world.mp4")}, {"file": FileData(path="cantina.wav")}]} conversation = [[user_msg1, bot_msg1], [user_msg2, bot_msg2], [user_msg3, bot_msg3]] with gr.Blocks() as demo: MultimodalChatbot(value=conversation, height=800) demo.launch() ``` Tip: Change the filepaths so that they correspond to files on your machine. Also, if you are running in development mode, make sure the files are located in the top level of your custom component directory.
Part 4 - The demo
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Let's build and deploy our demo with `gradio cc build` and `gradio cc deploy`! You can check out our component deployed to [HuggingFace Spaces](https://huggingface.co/spaces/freddyaboulton/gradio_multimodalchatbot) and all of the source code is available [here](https://huggingface.co/spaces/freddyaboulton/gradio_multimodalchatbot/tree/main/src). See you in the next installment of this series!
Part 5 - Deploying and Conclusion
https://gradio.app/guides/multimodal-chatbot-part1
Custom Components - Multimodal Chatbot Part1 Guide
Before using Custom Components, make sure you have Python 3.10+, Node.js v18+, npm 9+, and Gradio 4.0+ (preferably Gradio 5.0+) installed.
What do I need to install before using Custom Components?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
Custom components built with Gradio 5.0 should be compatible with Gradio 4.0. If you built your custom component in Gradio 4.0 you will have to rebuild your component to be compatible with Gradio 5.0. Simply follow these steps: 1. Update the `@gradio/preview` package. `cd` into the `frontend` directory and run `npm update`. 2. Modify the `dependencies` key in `pyproject.toml` to pin the maximum allowed Gradio version at version 5, e.g. `dependencies = ["gradio>=4.0,<6.0"]`. 3. Run the build and publish commands
Are custom components compatible between Gradio 4.0 and 5.0?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
Run `gradio cc show` to see the list of built-in templates. You can also start off from other's custom components! Simply `git clone` their repository and make your modifications.
What templates can I use to create my custom component?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
When you run `gradio cc dev`, a development server will load and run a Gradio app of your choosing. This is like when you run `python <app-file>.py`, however the `gradio` command will hot reload so you can instantly see your changes.
What is the development server?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
**1. Check your terminal and browser console** Make sure there are no syntax errors or other obvious problems in your code. Exceptions triggered from python will be displayed in the terminal. Exceptions from javascript will be displayed in the browser console and/or the terminal. **2. Are you developing on Windows?** Chrome on Windows will block the local compiled svelte files for security reasons. We recommend developing your custom component in the windows subsystem for linux (WSL) while the team looks at this issue. **3. Inspect the window.__GRADIO_CC__ variable** In the browser console, print the `window.__GRADIO__CC` variable (just type it into the console). If it is an empty object, that means that the CLI could not find your custom component source code. Typically, this happens when the custom component is installed in a different virtual environment than the one used to run the dev command. Please use the `--python-path` and `gradio-path` CLI arguments to specify the path of the python and gradio executables for the environment your component is installed in. For example, if you are using a virtualenv located at `/Users/mary/venv`, pass in `/Users/mary/bin/python` and `/Users/mary/bin/gradio` respectively. If the `window.__GRADIO__CC` variable is not empty (see below for an example), then the dev server should be working correctly. ![](https://gradio-builds.s3.amazonaws.com/demo-files/gradio_CC_DEV.png) **4. Make sure you are using a virtual environment** It is highly recommended you use a virtual environment to prevent conflicts with other python dependencies installed in your system.
The development server didn't work for me
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
No! You can start off from an existing gradio component as a template, see the [five minute guide](./custom-components-in-five-minutes). You can also start from an existing custom component if you'd like to tweak it further. Once you find the source code of a custom component you like, clone the code to your computer and run `gradio cc install`. Then you can run the development server to make changes.If you run into any issues, contact the author of the component by opening an issue in their repository. The [gallery](https://www.gradio.app/custom-components/gallery) is a good place to look for published components. For example, to start from the [PDF component](https://www.gradio.app/custom-components/gallery?id=freddyaboulton%2Fgradio_pdf), clone the space with `git clone https://huggingface.co/spaces/freddyaboulton/gradio_pdf`, `cd` into the `src` directory, and run `gradio cc install`.
Do I always need to start my component from scratch?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
You can develop and build your custom component without hosting or connecting to HuggingFace. If you would like to share your component with the gradio community, it is recommended to publish your package to PyPi and host a demo on HuggingFace so that anyone can install it or try it out.
Do I need to host my custom component on HuggingFace Spaces?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
You must implement the `preprocess`, `postprocess`, `example_payload`, and `example_value` methods. If your component does not use a data model, you must also define the `api_info`, `flag`, and `read_from_flag` methods. Read more in the [backend guide](./backend).
What methods are mandatory for implementing a custom component in Gradio?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
A `data_model` defines the expected data format for your component, simplifying the component development process and self-documenting your code. It streamlines API usage and example caching.
What is the purpose of a `data_model` in Gradio custom components?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
Utilizing `FileData` is crucial for components that expect file uploads. It ensures secure file handling, automatic caching, and streamlined client library functionality.
Why is it important to use `FileData` for components dealing with file uploads?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
You can define event triggers in the `EVENTS` class attribute by listing the desired event names, which automatically adds corresponding methods to your component.
How can I add event triggers to my custom Gradio component?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
Yes, it is possible to create custom components without a `data_model`, but you are going to have to manually implement `api_info`, `flag`, and `read_from_flag` methods.
Can I implement a custom Gradio component without defining a `data_model`?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
We have prepared this [collection](https://huggingface.co/collections/gradio/custom-components-65497a761c5192d981710b12) of custom components on the HuggingFace Hub that you can use to get started!
Are there sample custom components I can learn from?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
We're working on creating a gallery to make it really easy to discover new custom components. In the meantime, you can search for HuggingFace Spaces that are tagged as a `gradio-custom-component` [here](https://huggingface.co/search/full-text?q=gradio-custom-component&type=space)
How can I find custom components created by the Gradio community?
https://gradio.app/guides/frequently-asked-questions
Custom Components - Frequently Asked Questions Guide
By default, all custom component packages are called `gradio_<component-name>` where `component-name` is the name of the component's python class in lowercase. As an example, let's walkthrough changing the name of a component from `gradio_mytextbox` to `supertextbox`. 1. Modify the `name` in the `pyproject.toml` file. ```bash [project] name = "supertextbox" ``` 2. Change all occurrences of `gradio_<component-name>` in `pyproject.toml` to `<component-name>` ```bash [tool.hatch.build] artifacts = ["/backend/supertextbox/templates", "*.pyi"] [tool.hatch.build.targets.wheel] packages = ["/backend/supertextbox"] ``` 3. Rename the `gradio_<component-name>` directory in `backend/` to `<component-name>` ```bash mv backend/gradio_mytextbox backend/supertextbox ``` Tip: Remember to change the import statement in `demo/app.py`!
The Package Name
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
By default, only the custom component python class is a top level export. This means that when users type `from gradio_<component-name> import ...`, the only class that will be available is the custom component class. To add more classes as top level exports, modify the `__all__` property in `__init__.py` ```python from .mytextbox import MyTextbox from .mytextbox import AdditionalClass, additional_function __all__ = ['MyTextbox', 'AdditionalClass', 'additional_function'] ```
Top Level Python Exports
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
You can add python dependencies by modifying the `dependencies` key in `pyproject.toml` ```bash dependencies = ["gradio", "numpy", "PIL"] ``` Tip: Remember to run `gradio cc install` when you add dependencies!
Python Dependencies
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
You can add JavaScript dependencies by modifying the `"dependencies"` key in `frontend/package.json` ```json "dependencies": { "@gradio/atoms": "0.2.0-beta.4", "@gradio/statustracker": "0.3.0-beta.6", "@gradio/utils": "0.2.0-beta.4", "your-npm-package": "<version>" } ```
Javascript Dependencies
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
By default, the CLI will place the Python code in `backend` and the JavaScript code in `frontend`. It is not recommended to change this structure since it makes it easy for a potential contributor to look at your source code and know where everything is. However, if you did want to this is what you would have to do: 1. Place the Python code in the subdirectory of your choosing. Remember to modify the `[tool.hatch.build]` `[tool.hatch.build.targets.wheel]` in the `pyproject.toml` to match! 2. Place the JavaScript code in the subdirectory of your choosing. 2. Add the `FRONTEND_DIR` property on the component python class. It must be the relative path from the file where the class is defined to the location of the JavaScript directory. ```python class SuperTextbox(Component): FRONTEND_DIR = "../../frontend/" ``` The JavaScript and Python directories must be under the same common directory!
Directory Structure
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
Sticking to the defaults will make it easy for others to understand and contribute to your custom component. After all, the beauty of open source is that anyone can help improve your code! But if you ever need to deviate from the defaults, you know how!
Conclusion
https://gradio.app/guides/configuration
Custom Components - Configuration Guide
The documentation will be generated when running `gradio cc build`. You can pass the `--no-generate-docs` argument to turn off this behaviour. There is also a standalone `docs` command that allows for greater customisation. If you are running this command manually it should be run _after_ the `version` in your `pyproject.toml` has been bumped but before building the component. All arguments are optional. ```bash gradio cc docs path The directory of the custom component. --demo-dir Path to the demo directory. --demo-name Name of the demo file --space-url URL of the Hugging Face Space to link to --generate-space create a documentation space. --no-generate-space do not create a documentation space --readme-path Path to the README.md file. --generate-readme create a REAMDE.md file --no-generate-readme do not create a README.md file --suppress-demo-check suppress validation checks and warnings ```
How do I use it?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
The `gradio cc docs` command will generate an interactive Gradio app and a static README file with various features. You can see an example here: - [Gradio app deployed on Hugging Face Spaces]() - [README.md rendered by GitHub]() The README.md and space both have the following features: - A description. - Installation instructions. - A fully functioning code snippet. - Optional links to PyPi, GitHub, and Hugging Face Spaces. - API documentation including: - An argument table for component initialisation showing types, defaults, and descriptions. - A description of how the component affects the user's predict function. - A table of events and their descriptions. - Any additional interfaces or classes that may be used during initialisation or in the pre- or post- processors. Additionally, the Gradio includes: - A live demo. - A richer, interactive version of the parameter tables. - Nicer styling!
What gets generated?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
The documentation generator uses existing standards to extract the necessary information, namely Type Hints and Docstrings. There are no Gradio-specific APIs for documentation, so following best practices will generally yield the best results. If you already use type hints and docstrings in your component source code, you don't need to do much to benefit from this feature, but there are some details that you should be aware of. Python version To get the best documentation experience, you need to use Python `3.10` or greater when generating documentation. This is because some introspection features used to generate the documentation were only added in `3.10`. Type hints Python type hints are used extensively to provide helpful information for users. <details> <summary> What are type hints?</summary> If you need to become more familiar with type hints in Python, they are a simple way to express what Python types are expected for arguments and return values of functions and methods. They provide a helpful in-editor experience, aid in maintenance, and integrate with various other tools. These types can be simple primitives, like `list` `str` `bool`; they could be more compound types like `list[str]`, `str | None` or `tuple[str, float | int]`; or they can be more complex types using utility classed like [`TypedDict`](https://peps.python.org/pep-0589/abstract). [Read more about type hints in Python.](https://realpython.com/lessons/type-hinting/) </details> What do I need to add hints to? You do not need to add type hints to every part of your code. For the documentation to work correctly, you will need to add type hints to the following component methods: - `__init__` parameters should be typed. - `postprocess` parameters and return value should be typed. - `preprocess` parameters and return value should be typed. If you are using `gradio cc create`, these types should already exist, but you may need to tweak them based on any changes you ma
What do I need to do?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
be typed. - `preprocess` parameters and return value should be typed. If you are using `gradio cc create`, these types should already exist, but you may need to tweak them based on any changes you make. `__init__` Here, you only need to type the parameters. If you have cloned a template with `gradio` cc create`, these should already be in place. You will only need to add new hints for anything you have added or changed: ```py def __init__( self, value: str | None = None, *, sources: Literal["upload", "microphone"] = "upload, every: Timer | float | None = None, ... ): ... ``` `preprocess` and `postprocess` The `preprocess` and `postprocess` methods determine the value passed to the user function and the value that needs to be returned. Even if the design of your component is primarily as an input or an output, it is worth adding type hints to both the input parameters and the return values because Gradio has no way of limiting how components can be used. In this case, we specifically care about: - The return type of `preprocess`. - The input type of `postprocess`. ```py def preprocess( self, payload: FileData | None input is optional ) -> tuple[int, str] | str | None: user function input is the preprocess return ▲ user function output is the postprocess input ▼ def postprocess( self, value: tuple[int, str] | None ) -> FileData | bytes | None: return is optional ... ``` Docstrings Docstrings are also used extensively to extract more meaningful, human-readable descriptions of certain parts of the API. <details> <summary> What are docstrings?</summary> If you need to become more familiar with docstrings in Python, they are a way to annotate parts of your code with human-readable decisions and explanations. They offer a rich in-editor experience like type hints, but unlike type hints, they don't have any specific syntax requirements. They are simple strings and can take almost any form. The only requirement i
What do I need to do?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
offer a rich in-editor experience like type hints, but unlike type hints, they don't have any specific syntax requirements. They are simple strings and can take almost any form. The only requirement is where they appear. Docstrings should be "a string literal that occurs as the first statement in a module, function, class, or method definition". [Read more about Python docstrings.](https://peps.python.org/pep-0257/what-is-a-docstring) </details> While docstrings don't have any syntax requirements, we need a particular structure for documentation purposes. As with type hint, the specific information we care about is as follows: - `__init__` parameter docstrings. - `preprocess` return docstrings. - `postprocess` input parameter docstrings. Everything else is optional. Docstrings should always take this format to be picked up by the documentation generator: Classes ```py """ A description of the class. This can span multiple lines and can _contain_ *markdown*. """ ``` Methods and functions Markdown in these descriptions will not be converted into formatted text. ```py """ Parameters: param_one: A description for this parameter. param_two: A description for this parameter. Returns: A description for this return value. """ ``` Events In custom components, events are expressed as a list stored on the `events` field of the component class. While we do not need types for events, we _do_ need a human-readable description so users can understand the behaviour of the event. To facilitate this, we must create the event in a specific way. There are two ways to add events to a custom component. Built-in events Gradio comes with a variety of built-in events that may be enough for your component. If you are using built-in events, you do not need to do anything as they already have descriptions we can extract: ```py from gradio.events import Events class ParamViewer(Component): ... EVENTS = [ Events.change, Events.up
What do I need to do?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
do not need to do anything as they already have descriptions we can extract: ```py from gradio.events import Events class ParamViewer(Component): ... EVENTS = [ Events.change, Events.upload, ] ``` Custom events You can define a custom event if the built-in events are unsuitable for your use case. This is a straightforward process, but you must create the event in this way for docstrings to work correctly: ```py from gradio.events import Events, EventListener class ParamViewer(Component): ... EVENTS = [ Events.change, EventListener( "bingbong", doc="This listener is triggered when the user does a bingbong." ) ] ``` Demo The `demo/app.py`, often used for developing the component, generates the live demo and code snippet. The only strict rule here is that the `demo.launch()` command must be contained with a `__name__ == "__main__"` conditional as below: ```py if __name__ == "__main__": demo.launch() ``` The documentation generator will scan for such a clause and error if absent. If you are _not_ launching the demo inside the `demo/app.py`, then you can pass `--suppress-demo-check` to turn off this check. Demo recommendations Although there are no additional rules, there are some best practices you should bear in mind to get the best experience from the documentation generator. These are only guidelines, and every situation is unique, but they are sound principles to remember. Keep the demo compact Compact demos look better and make it easier for users to understand what the demo does. Try to remove as many extraneous UI elements as possible to focus the users' attention on the core use case. Sometimes, it might make sense to have a `demo/app.py` just for the docs and an additional, more complex app for your testing purposes. You can also create other spaces, showcasing more complex examples and linking to them from the main class docstring or the `pyproject.toml` description.
What do I need to do?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide
ore complex app for your testing purposes. You can also create other spaces, showcasing more complex examples and linking to them from the main class docstring or the `pyproject.toml` description. Keep the code concise The 'getting started' snippet utilises the demo code, which should be as short as possible to keep users engaged and avoid confusion. It isn't the job of the sample snippet to demonstrate the whole API; this snippet should be the shortest path to success for a new user. It should be easy to type or copy-paste and easy to understand. Explanatory comments should be brief and to the point. Avoid external dependencies As mentioned above, users should be able to copy-paste a snippet and have a fully working app. Try to avoid third-party library dependencies to facilitate this. You should carefully consider any examples; avoiding examples that require additional files or that make assumptions about the environment is generally a good idea. Ensure the `demo` directory is self-contained Only the `demo` directory will be uploaded to Hugging Face spaces in certain instances, as the component will be installed via PyPi if possible. It is essential that this directory is self-contained and any files needed for the correct running of the demo are present. Additional URLs The documentation generator will generate a few buttons, providing helpful information and links to users. They are obtained automatically in some cases, but some need to be explicitly included in the `pyproject.yaml`. - PyPi Version and link - This is generated automatically. - GitHub Repository - This is populated via the `pyproject.toml`'s `project.urls.repository`. - Hugging Face Space - This is populated via the `pyproject.toml`'s `project.urls.space`. An example `pyproject.toml` urls section might look like this: ```toml [project.urls] repository = "https://github.com/user/repo-name" space = "https://huggingface.co/spaces/user/space-name" ```
What do I need to do?
https://gradio.app/guides/documenting-custom-components
Custom Components - Documenting Custom Components Guide