text
stringlengths
0
2k
heading1
stringlengths
3
79
source_page_url
stringclasses
185 values
source_page_title
stringclasses
185 values
Gradio also supports browser state, where data persists in the browser's localStorage even after the page is refreshed or closed. This is useful for storing user preferences, settings, API keys, or other data that should persist across sessions. To use local state: 1. Create a `gr.BrowserState` object. You can optionally provide an initial default value and a key to identify the data in the browser's localStorage. 2. Use it like a regular `gr.State` component in event listeners as inputs and outputs. Here's a simple example that saves a user's username and password across sessions: $code_browserstate Note: The value stored in `gr.BrowserState` does not persist if the Grado app is restarted. To persist it, you can hardcode specific values of `storage_key` and `secret` in the `gr.BrowserState` component and restart the Gradio app on the same server name and server port. However, this should only be done if you are running trusted Gradio apps, as in principle, this can allow one Gradio app to access localStorage data that was created by a different Gradio app.
Browser State
https://gradio.app/guides/state-in-blocks
Building With Blocks - State In Blocks Guide
Gradio themes are the easiest way to customize the look and feel of your app. You can choose from a variety of themes, or create your own. To do so, pass the `theme=` kwarg to the `launch()` method of the `Blocks` constructor. For example: ```python with gr.Blocks() as demo: ... your code here demo.launch(theme=gr.themes.Glass()) ... ``` Gradio comes with a set of prebuilt themes which you can load from `gr.themes.*`. You can extend these themes or create your own themes from scratch - see the [Theming guide](/guides/theming-guide) for more details. For additional styling ability, you can pass any CSS to your app as a string using the `css=` kwarg in the `launch()` method. You can also pass a pathlib.Path to a css file or a list of such paths to the `css_paths=` kwarg in the `launch()` method. **Warning**: The use of query selectors in custom JS and CSS is _not_ guaranteed to work across Gradio versions that bind to Gradio's own HTML elements as the Gradio HTML DOM may change. We recommend using query selectors sparingly. The base class for the Gradio app is `gradio-container`, so here's an example that changes the background color of the Gradio app: ```python with gr.Blocks() as demo: ... your code here demo.launch(css=".gradio-container {background-color: red}") ... ``` If you'd like to reference external files in your css, preface the file path (which can be a relative or absolute path) with `"/gradio_api/file="`, for example: ```python with gr.Blocks() as demo: ... your code here demo.launch(css=".gradio-container {background: url('/gradio_api/file=clouds.jpg')}") ... ``` Note: By default, most files in the host machine are not accessible to users running the Gradio app. As a result, you should make sure that any referenced files (such as `clouds.jpg` here) are either URLs or [allowed paths, as described here](/main/guides/file-access).
Adding custom CSS to your demo
https://gradio.app/guides/custom-CSS-and-JS
Building With Blocks - Custom Css And Js Guide
You can `elem_id` to add an HTML element `id` to any component, and `elem_classes` to add a class or list of classes. This will allow you to select elements more easily with CSS. This approach is also more likely to be stable across Gradio versions as built-in class names or ids may change (however, as mentioned in the warning above, we cannot guarantee complete compatibility between Gradio versions if you use custom CSS as the DOM elements may themselves change). ```python css = """ warning {background-color: FFCCCB} .feedback textarea {font-size: 24px !important} """ with gr.Blocks() as demo: box1 = gr.Textbox(value="Good Job", elem_classes="feedback") box2 = gr.Textbox(value="Failure", elem_id="warning", elem_classes="feedback") demo.launch(css=css) ``` The CSS `warning` ruleset will only target the second Textbox, while the `.feedback` ruleset will target both. Note that when targeting classes, you might need to put the `!important` selector to override the default Gradio styles.
The `elem_id` and `elem_classes` Arguments
https://gradio.app/guides/custom-CSS-and-JS
Building With Blocks - Custom Css And Js Guide
There are 3 ways to add javascript code to your Gradio demo: 1. You can add JavaScript code as a string to the `js` parameter of the `Blocks` or `Interface` initializer. This will run the JavaScript code when the demo is first loaded. Below is an example of adding custom js to show an animated welcome message when the demo first loads. $code_blocks_js_load $demo_blocks_js_load 2. When using `Blocks` and event listeners, events have a `js` argument that can take a JavaScript function as a string and treat it just like a Python event listener function. You can pass both a JavaScript function and a Python function (in which case the JavaScript function is run first) or only Javascript (and set the Python `fn` to `None`). Take a look at the code below: $code_blocks_js_methods $demo_blocks_js_methods 3. Lastly, you can add JavaScript code to the `head` param of the `Blocks` initializer. This will add the code to the head of the HTML document. For example, you can add Google Analytics to your demo like so: ```python head = f""" <script async src="https://www.googletagmanager.com/gtag/js?id={google_analytics_tracking_id}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){{dataLayer.push(arguments);}} gtag('js', new Date()); gtag('config', '{google_analytics_tracking_id}'); </script> """ with gr.Blocks() as demo: gr.HTML("<h1>My App</h1>") demo.launch(head=head) ``` The `head` parameter accepts any HTML tags you would normally insert into the `<head>` of a page. For example, you can also include `<meta>` tags to `head` in order to update the social sharing preview for your Gradio app like this: ```py import gradio as gr custom_head = """ <!-- HTML Meta Tags --> <title>Sample App</title> <meta name="description" content="An open-source web application showcasing various features and capabilities."> <!-- Facebook Meta Tags --> <meta property="og:url" content="https://example.com"> <meta property="og:type" content="webs
Adding custom JavaScript to your demo
https://gradio.app/guides/custom-CSS-and-JS
Building With Blocks - Custom Css And Js Guide
n open-source web application showcasing various features and capabilities."> <!-- Facebook Meta Tags --> <meta property="og:url" content="https://example.com"> <meta property="og:type" content="website"> <meta property="og:title" content="Sample App"> <meta property="og:description" content="An open-source web application showcasing various features and capabilities."> <meta property="og:image" content="https://cdn.britannica.com/98/152298-050-8E45510A/Cheetah.jpg"> <!-- Twitter Meta Tags --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:creator" content="@example_user"> <meta name="twitter:title" content="Sample App"> <meta name="twitter:description" content="An open-source web application showcasing various features and capabilities."> <meta name="twitter:image" content="https://cdn.britannica.com/98/152298-050-8E45510A/Cheetah.jpg"> <meta property="twitter:domain" content="example.com"> <meta property="twitter:url" content="https://example.com"> """ with gr.Blocks(title="My App") as demo: gr.HTML("<h1>My App</h1>") demo.launch(head=custom_head) ``` Note that injecting custom JS can affect browser behavior and accessibility (e.g. keyboard shortcuts may be lead to unexpected behavior if your Gradio app is embedded in another webpage). You should test your interface across different browsers and be mindful of how scripts may interact with browser defaults. Here's an example where pressing `Shift + s` triggers the `click` event of a specific `Button` component if the browser focus is _not_ on an input component (e.g. `Textbox` component): ```python import gradio as gr shortcut_js = """ <script> function shortcuts(e) { var event = document.all ? window.event : e; switch (e.target.tagName.toLowerCase()) { case "input": case "textarea": break; default: if (e.key.toLowerCase() == "s" && e.shiftKey) { document.getElementById("my_btn").click(); } } } docum
Adding custom JavaScript to your demo
https://gradio.app/guides/custom-CSS-and-JS
Building With Blocks - Custom Css And Js Guide
"input": case "textarea": break; default: if (e.key.toLowerCase() == "s" && e.shiftKey) { document.getElementById("my_btn").click(); } } } document.addEventListener('keypress', shortcuts, false); </script> """ with gr.Blocks() as demo: action_button = gr.Button(value="Name", elem_id="my_btn") textbox = gr.Textbox() action_button.click(lambda : "button pressed", None, textbox) demo.launch(head=shortcut_js) ```
Adding custom JavaScript to your demo
https://gradio.app/guides/custom-CSS-and-JS
Building With Blocks - Custom Css And Js Guide
The `gr.HTML` component can also be used to create custom input components by triggering events. You will provide `js_on_load`, javascript code that runs when the component loads. The code has access to the `trigger` function to trigger events that Gradio can listen to, and the object `props` which has access to all the props of the component, including `value`. $code_star_rating_events $demo_star_rating_events Take a look at the `js_on_load` code above. We add click event listeners to each star image to update the value via `props.value` when a star is clicked. This also re-renders the template to show the updated value. We also add a click event listener to the submit button that triggers the `submit` event. In our app, we listen to this trigger to run a function that outputs the `value` of the star rating. The `js_on_load` scope also includes an `upload` async function that lets you upload a JavaScript `File` object directly to the Gradio server. It returns a dictionary with `path` (the server-side file path) and `url` (the public URL to access the file). ```js const { path, url } = await upload(file); ``` Here is an example of a custom file-upload widget built with `gr.HTML`: $code_html_upload $demo_html_upload You can update any other props of the component via `props.<prop_name>`, and trigger events via `trigger('<event_name>')`. The trigger event can also be send event data, e.g. ```js trigger('event_name', { key: value, count: 123 }); ``` This event data will be accessible the Python event listener functions via gr.EventData. ```python def handle_event(evt: gr.EventData): print(evt.key) print(evt.count) star_rating.event(fn=handle_event, inputs=[], outputs=[]) ``` Keep in mind that event listeners attached in `js_on_load` are only attached once when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component load
Triggering Events and Custom Input Components
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
ce when the component is first rendered. If your component creates new elements dynamically that need event listeners, attach the event listener to a parent element that exists when the component loads, and check for the target. For example: ```js element.addEventListener('click', (e) => if (e.target && e.target.matches('.child-element')) { props.value = e.target.dataset.value; } ); ``` You can trigger an event with any name. As long as the event name appears enclosed in quotes in your `js_on_load` string, you can attach a Python listener using `component.do_something(fn, ...)`.
Triggering Events and Custom Input Components
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
The `watch` function, available inside `js_on_load`, lets you run a callback whenever specific props change when the component is an output to a Python event listener. Read current values directly from `props` inside the callback. ```js // Watch a single prop watch('value', () => { console.log('value is now:', props.value); }); // Watch multiple props watch(['value', 'color'], () => { console.log('value or color changed'); }); ```
Watching Props with `watch`
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
The `head` parameter lets you load external JavaScript or CSS libraries directly on the component. The `head` content is injected and loaded **before** `js_on_load` runs, so your code can immediately use the library. ```python gr.HTML( value=[30, 70, 45, 90, 60], html_template="<canvas id='chart'></canvas>", js_on_load=""" new Chart(element.querySelector('chart'), { type: 'bar', data: { labels: props.value.map((_, i) => 'Item ' + (i + 1)), datasets: [{ label: 'Values', data: props.value }] } }); """, head='<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>', ) ```
Loading Third-Party Scripts with `head`
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
You can call Python functions directly from your `js_on_load` code using the `server_functions` parameter. Pass a list of Python functions to `server_functions`, and they become available as async methods on a `server` object inside `js_on_load`. $code_html_server_functions $demo_html_server_functions
Server Functions
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
If you are reusing the same HTML component in multiple places, you can create a custom component class by subclassing `gr.HTML` and setting default values for the templates and other arguments. Here's an example of creating a reusable StarRating component. $code_star_rating_component $demo_star_rating_component Note: Gradio requires all components to accept certain arguments, such as `render`. You do not need to handle these arguments, but you do need to accept them in your component constructor and pass them to the parent `gr.HTML` class. Otherwise, your component may not behave correctly. The easiest way is to add `**kwargs` to your `__init__` method and pass it to `super().__init__()`, just like in the code example above. We've created several custom HTML components as reusable components as examples you can reference in [this directory](https://github.com/gradio-app/gradio/tree/main/gradio/components/custom_html_components).
Component Classes
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
The `gr.HTML` component can also be used as a container for other Gradio components using the `@children` placeholder. This allows you to create custom layouts with HTML/CSS. The `@children` must be at the top-level of the `html_template`. Since children cannot be nested inside the template, target the parent element directly with your CSS and JavaScript if you need to style or interact with the container of the children. Here's a basic example: $code_html_children $demo_html_children In this example, the `@children` placeholder marks where the child components (the Name and Email textboxes) will be rendered. Notice how in the `css_template` we target the parent element to style the container div that wraps the children. API / MCP support To make your custom HTML component work with Gradio's built-in support for API and MCP (Model Context Protocol) usage, you need to define how its data should be serialized. There are two ways to do this: **Option 1: Define an `api_info()` method** Add an `api_info()` method that returns a JSON schema dictionary describing your component's data format. This is what we do in the StarRating class above. **Option 2: Define a Pydantic data model** For more complex data structures, you can define a Pydantic model that inherits from `GradioModel` or `GradioRootModel`: ```python from gradio.data_classes import GradioModel, GradioRootModel class MyComponentData(GradioModel): items: List[str] count: int class MyComponent(gr.HTML): data_model = MyComponentData ``` Use `GradioModel` when your data is a dictionary with named fields, or `GradioRootModel` when your data is a simple type (string, list, etc.) that doesn't need to be wrapped in a dictionary. By defining a `data_model`, your component automatically implements API methods.
Embedding Components in HTML
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
Once you've built a custom HTML component, you can share it with the community by pushing it to the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery). The gallery lets anyone browse, interact with, and copy the Python code for community-contributed components. Call `push_to_hub` on any `gr.HTML` instance or subclass: ```python star_rating = StarRating() star_rating.push_to_hub( name="Star Rating", description="Interactive 5-star rating with click-to-rate", author="your-hf-username", tags=["input", "rating"], repo_url="https://github.com/your-username/your-repo", ) ``` This opens a pull request on the gallery's HuggingFace dataset repo. Once approved, your component will appear in the gallery for others to discover and use. Tip: The `push_to_hub` method has a `head` parameter that deserves special attention. If your component uses an external library loaded via the `head` parameter of `launch` (e.g. `head='<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>'`), pass the same `head` string to `push_to_hub` so that the gallery can load those scripts when rendering your component. Authentication You need a HuggingFace **write token** to push components. Either pass it directly: ```python star_rating.push_to_hub(..., token="hf_xxxxx") ``` Or log in beforehand with the HuggingFace CLI, and the cached token will be used automatically: ```bash huggingface-cli login ```
Sharing Components with `push_to_hub`
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
Keep in mind that using `gr.HTML` to create custom components involves injecting raw HTML and JavaScript into your Gradio app. Be cautious about using untrusted user input into `html_template` and `js_on_load`, as this could lead to cross-site scripting (XSS) vulnerabilities. You should also expect that any Python event listeners that take your `gr.HTML` component as input could have any arbitrary value passed to them, not just the values you expect the frontend to be able to set for `value`. Sanitize and validate user input appropriately in public applications.
Security Considerations
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
- Browse the [HTML Components Gallery](https://www.gradio.app/custom-components/html-gallery) to see what the community has built and copy components into your own apps. - Check out more examples in [this directory](https://github.com/gradio-app/gradio/tree/main/gradio/components/custom_html_components). - Share your own components with `push_to_hub` to help others!
Next Steps
https://gradio.app/guides/custom-HTML-components
Building With Blocks - Custom Html Components Guide
In the example below, we will create a variable number of Textboxes. When the user edits the input Textbox, we create a Textbox for each letter in the input. Try it out below: $code_render_split_simple $demo_render_split_simple See how we can now create a variable number of Textboxes using our custom logic - in this case, a simple `for` loop. The `@gr.render` decorator enables this with the following steps: 1. Create a function and attach the @gr.render decorator to it. 2. Add the input components to the `inputs=` argument of @gr.render, and create a corresponding argument in your function for each component. This function will automatically re-run on any change to a component. 3. Add all components inside the function that you want to render based on the inputs. Now whenever the inputs change, the function re-runs, and replaces the components created from the previous function run with the latest run. Pretty straightforward! Let's add a little more complexity to this app: $code_render_split $demo_render_split By default, `@gr.render` re-runs are triggered by the `.load` listener to the app and the `.change` listener to any input component provided. We can override this by explicitly setting the triggers in the decorator, as we have in this app to only trigger on `input_text.submit` instead. If you are setting custom triggers, and you also want an automatic render at the start of the app, make sure to add `demo.load` to your list of triggers.
Dynamic Number of Components
https://gradio.app/guides/dynamic-apps-with-render-decorator
Building With Blocks - Dynamic Apps With Render Decorator Guide
If you're creating components, you probably want to attach event listeners to them as well. Let's take a look at an example that takes in a variable number of Textbox as input, and merges all the text into a single box. $code_render_merge_simple $demo_render_merge_simple Let's take a look at what's happening here: 1. The state variable `text_count` is keeping track of the number of Textboxes to create. By clicking on the Add button, we increase `text_count` which triggers the render decorator. 2. Note that in every single Textbox we create in the render function, we explicitly set a `key=` argument. This key allows us to preserve the value of this Component between re-renders. If you type in a value in a textbox, and then click the Add button, all the Textboxes re-render, but their values aren't cleared because the `key=` maintains the the value of a Component across a render. 3. We've stored the Textboxes created in a list, and provide this list as input to the merge button event listener. Note that **all event listeners that use Components created inside a render function must also be defined inside that render function**. The event listener can still reference Components outside the render function, as we do here by referencing `merge_btn` and `output` which are both defined outside the render function. Just as with Components, whenever a function re-renders, the event listeners created from the previous render are cleared and the new event listeners from the latest run are attached. This allows us to create highly customizable and complex interactions!
Dynamic Event Listeners
https://gradio.app/guides/dynamic-apps-with-render-decorator
Building With Blocks - Dynamic Apps With Render Decorator Guide
The `key=` argument is used to let Gradio know that the same component is being generated when your render function re-runs. This does two things: 1. The same element in the browser is re-used from the previous render for this Component. This gives browser performance gains - as there's no need to destroy and rebuild a component on a render - and preserves any browser attributes that the Component may have had. If your Component is nested within layout items like `gr.Row`, make sure they are keyed as well because the keys of the parents must also match. 2. Properties that may be changed by the user or by other event listeners are preserved. By default, only the "value" of Component is preserved, but you can specify any list of properties to preserve using the `preserved_by_key=` kwarg. See the example below: $code_render_preserve_key $demo_render_preserve_key You'll see in this example, when you change the `number_of_boxes` slider, there's a new re-render to update the number of box rows. If you click the "Change Label" buttons, they change the `label` and `info` properties of the corresponding textbox. You can also enter text in any textbox to change its value. If you change number of boxes after this, the re-renders "reset" the `info`, but the `label` and any entered `value` is still preserved. Note you can also key any event listener, e.g. `button.click(key=...)` if the same listener is being recreated with the same inputs and outputs across renders. This gives performance benefits, and also prevents errors from occurring if an event was triggered in a previous render, then a re-render occurs, and then the previous event finishes processing. By keying your listener, Gradio knows where to send the data properly.
Closer Look at `keys=` parameter
https://gradio.app/guides/dynamic-apps-with-render-decorator
Building With Blocks - Dynamic Apps With Render Decorator Guide
Let's look at two examples that use all the features above. First, try out the to-do list app below: $code_todo_list $demo_todo_list Note that almost the entire app is inside a single `gr.render` that reacts to the tasks `gr.State` variable. This variable is a nested list, which presents some complexity. If you design a `gr.render` to react to a list or dict structure, ensure you do the following: 1. Any event listener that modifies a state variable in a manner that should trigger a re-render must set the state variable as an output. This lets Gradio know to check if the variable has changed behind the scenes. 2. In a `gr.render`, if a variable in a loop is used inside an event listener function, that variable should be "frozen" via setting it to itself as a default argument in the function header. See how we have `task=task` in both `mark_done` and `delete`. This freezes the variable to its "loop-time" value. Let's take a look at one last example that uses everything we learned. Below is an audio mixer. Provide multiple audio tracks and mix them together. $code_audio_mixer $demo_audio_mixer Two things to note in this app: 1. Here we provide `key=` to all the components! We need to do this so that if we add another track after setting the values for an existing track, our input values to the existing track do not get reset on re-render. 2. When there are lots of components of different types and arbitrary counts passed to an event listener, it is easier to use the set and dictionary notation for inputs rather than list notation. Above, we make one large set of all the input `gr.Audio` and `gr.Slider` components when we pass the inputs to the `merge` function. In the function body we query the component values as a dict. The `gr.render` expands gradio capabilities extensively - see what you can make out of it!
Putting it Together
https://gradio.app/guides/dynamic-apps-with-render-decorator
Building With Blocks - Dynamic Apps With Render Decorator Guide
Elements within a `with gr.Row` clause will all be displayed horizontally. For example, to display two Buttons side by side: ```python with gr.Blocks() as demo: with gr.Row(): btn1 = gr.Button("Button 1") btn2 = gr.Button("Button 2") ``` You can set every element in a Row to have the same height. Configure this with the `equal_height` argument. ```python with gr.Blocks() as demo: with gr.Row(equal_height=True): textbox = gr.Textbox() btn2 = gr.Button("Button 2") ``` The widths of elements in a Row can be controlled via a combination of `scale` and `min_width` arguments that are present in every Component. - `scale` is an integer that defines how an element will take up space in a Row. If scale is set to `0`, the element will not expand to take up space. If scale is set to `1` or greater, the element will expand. Multiple elements in a row will expand proportional to their scale. Below, `btn2` will expand twice as much as `btn1`, while `btn0` will not expand at all: ```python with gr.Blocks() as demo: with gr.Row(): btn0 = gr.Button("Button 0", scale=0) btn1 = gr.Button("Button 1", scale=1) btn2 = gr.Button("Button 2", scale=2) ``` - `min_width` will set the minimum width the element will take. The Row will wrap if there isn't sufficient space to satisfy all `min_width` values. Learn more about Rows in the [docs](https://gradio.app/docs/row).
Rows
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
Components within a Column will be placed vertically atop each other. Since the vertical layout is the default layout for Blocks apps anyway, to be useful, Columns are usually nested within Rows. For example: $code_rows_and_columns $demo_rows_and_columns See how the first column has two Textboxes arranged vertically. The second column has an Image and Button arranged vertically. Notice how the relative widths of the two columns is set by the `scale` parameter. The column with twice the `scale` value takes up twice the width. Learn more about Columns in the [docs](https://gradio.app/docs/column). Fill Browser Height / Width To make an app take the full width of the browser by removing the side padding, use `gr.Blocks(fill_width=True)`. To make top level Components expand to take the full height of the browser, use `fill_height` and apply scale to the expanding Components. ```python import gradio as gr with gr.Blocks(fill_height=True) as demo: gr.Chatbot(scale=1) gr.Textbox(scale=0) ```
Columns and Nesting
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
Some components support setting height and width. These parameters accept either a number (interpreted as pixels) or a string. Using a string allows the direct application of any CSS unit to the encapsulating Block element. Below is an example illustrating the use of viewport width (vw): ```python import gradio as gr with gr.Blocks() as demo: im = gr.ImageEditor(width="50vw") demo.launch() ```
Dimensions
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
You can also create Tabs using the `with gr.Tab('tab_name'):` clause. Any component created inside of a `with gr.Tab('tab_name'):` context appears in that tab. Consecutive Tab clauses are grouped together so that a single tab can be selected at one time, and only the components within that Tab's context are shown. For example: $code_blocks_flipper $demo_blocks_flipper Also note the `gr.Accordion('label')` in this example. The Accordion is a layout that can be toggled open or closed. Like `Tabs`, it is a layout element that can selectively hide or show content. Any components that are defined inside of a `with gr.Accordion('label'):` will be hidden or shown when the accordion's toggle icon is clicked. Learn more about [Tabs](https://gradio.app/docs/tab) and [Accordions](https://gradio.app/docs/accordion) in the docs.
Tabs and Accordions
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
The sidebar is a collapsible panel that renders child components on the left side of the screen and can be expanded or collapsed. For example: $code_blocks_sidebar Learn more about [Sidebar](https://gradio.app/docs/gradio/sidebar) in the docs.
Sidebar
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
In order to provide a guided set of ordered steps, a controlled workflow, you can use the `Walkthrough` component with accompanying `Step` components. The `Walkthrough` component has a visual style and user experience tailored for this usecase. Authoring this component is very similar to `Tab`, except it is the app developers responsibility to progress through each step, by setting the appropriate ID for the parent `Walkthrough` which should correspond to an ID provided to an indvidual `Step`. $demo_walkthrough Learn more about [Walkthrough](https://gradio.app/docs/gradio/walkthrough) in the docs.
Multi-step walkthroughs
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
Both Components and Layout elements have a `visible` argument that can set initially and also updated. Setting `gr.Column(visible=...)` on a Column can be used to show or hide a set of Components. $code_blocks_form $demo_blocks_form
Visibility
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
In some cases, you might want to define components before you actually render them in your UI. For instance, you might want to show an examples section using `gr.Examples` above the corresponding `gr.Textbox` input. Since `gr.Examples` requires as a parameter the input component object, you will need to first define the input component, but then render it later, after you have defined the `gr.Examples` object. The solution to this is to define the `gr.Textbox` outside of the `gr.Blocks()` scope and use the component's `.render()` method wherever you'd like it placed in the UI. Here's a full code example: ```python input_textbox = gr.Textbox() with gr.Blocks() as demo: gr.Examples(["hello", "bonjour", "merhaba"], input_textbox) input_textbox.render() ``` Similarly, if you have already defined a component in a Gradio app, but wish to unrender it so that you can define in a different part of your application, then you can call the `.unrender()` method. In the following example, the `Textbox` will appear in the third column: ```py import gradio as gr with gr.Blocks() as demo: with gr.Row(): with gr.Column(): gr.Markdown("Row 1") textbox = gr.Textbox() with gr.Column(): gr.Markdown("Row 2") textbox.unrender() with gr.Column(): gr.Markdown("Row 3") textbox.render() demo.launch() ```
Defining and Rendering Components Separately
https://gradio.app/guides/controlling-layout
Building With Blocks - Controlling Layout Guide
Take a look at the demo below. $code_hello_blocks $demo_hello_blocks - First, note the `with gr.Blocks() as demo:` clause. The Blocks app code will be contained within this clause. - Next come the Components. These are the same Components used in `Interface`. However, instead of being passed to some constructor, Components are automatically added to the Blocks as they are created within the `with` clause. - Finally, the `click()` event listener. Event listeners define the data flow within the app. In the example above, the listener ties the two Textboxes together. The Textbox `name` acts as the input and Textbox `output` acts as the output to the `greet` method. This dataflow is triggered when the Button `greet_btn` is clicked. Like an Interface, an event listener can take multiple inputs or outputs. You can also attach event listeners using decorators - skip the `fn` argument and assign `inputs` and `outputs` directly: $code_hello_blocks_decorator
Blocks Structure
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
In the example above, you'll notice that you are able to edit Textbox `name`, but not Textbox `output`. This is because any Component that acts as an input to an event listener is made interactive. However, since Textbox `output` acts only as an output, Gradio determines that it should not be made interactive. You can override the default behavior and directly configure the interactivity of a Component with the boolean `interactive` keyword argument, e.g. `gr.Textbox(interactive=True)`. ```python output = gr.Textbox(label="Output", interactive=True) ``` _Note_: What happens if a Gradio component is neither an input nor an output? If a component is constructed with a default value, then it is presumed to be displaying content and is rendered non-interactive. Otherwise, it is rendered interactive. Again, this behavior can be overridden by specifying a value for the `interactive` argument.
Event Listeners and Interactivity
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
Take a look at the demo below: $code_blocks_hello $demo_blocks_hello Instead of being triggered by a click, the `welcome` function is triggered by typing in the Textbox `inp`. This is due to the `change()` event listener. Different Components support different event listeners. For example, the `Video` Component supports a `play()` event listener, triggered when a user presses play. See the [Docs](http://gradio.app/docscomponents) for the event listeners for each Component.
Types of Event Listeners
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
A Blocks app is not limited to a single data flow the way Interfaces are. Take a look at the demo below: $code_reversible_flow $demo_reversible_flow Note that `num1` can act as input to `num2`, and also vice-versa! As your apps get more complex, you will have many data flows connecting various Components. Here's an example of a "multi-step" demo, where the output of one model (a speech-to-text model) gets fed into the next model (a sentiment classifier). $code_blocks_speech_text_sentiment $demo_blocks_speech_text_sentiment
Multiple Data Flows
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
The event listeners you've seen so far have a single input component. If you'd like to have multiple input components pass data to the function, you have two options on how the function can accept input component values: 1. as a list of arguments, or 2. as a single dictionary of values, keyed by the component Let's see an example of each: $code_calculator_list_and_dict Both `add()` and `sub()` take `a` and `b` as inputs. However, the syntax is different between these listeners. 1. To the `add_btn` listener, we pass the inputs as a list. The function `add()` takes each of these inputs as arguments. The value of `a` maps to the argument `num1`, and the value of `b` maps to the argument `num2`. 2. To the `sub_btn` listener, we pass the inputs as a set (note the curly brackets!). When you pass a set, the function `sub()` receives a single dictionary argument `data`, where the keys are the input components and the values are the values of those components. It is a matter of preference which syntax you prefer! For functions with many input components, option 2 may be easier to manage. $demo_calculator_list_and_dict
Function Input List vs Set
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
Similarly, you may return values for multiple output components either as: 1. a list of values, or 2. a dictionary keyed by the component Let's first see an example of (1), where we set the values of two output components by returning two values: ```python with gr.Blocks() as demo: food_box = gr.Number(value=10, label="Food Count") status_box = gr.Textbox() def eat(food): if food > 0: return food - 1, "full" else: return 0, "hungry" gr.Button("Eat").click( fn=eat, inputs=food_box, outputs=[food_box, status_box] ) ``` Above, each return statement returns two values corresponding to `food_box` and `status_box`, respectively. **Note:** if your event listener has a single output component, you should **not** return it as a single-item list. This will not work, since Gradio does not know whether to interpret that outer list as part of your return value. You should instead just return that value directly. Now, let's see option (2). Instead of returning a list of values corresponding to each output component in order, you can also return a dictionary, with the key corresponding to the output component and the value as the new value. This also allows you to skip updating some output components. ```python with gr.Blocks() as demo: food_box = gr.Number(value=10, label="Food Count") status_box = gr.Textbox() def eat(food): if food > 0: return {food_box: food - 1, status_box: "full"} else: return {status_box: "hungry"} gr.Button("Eat").click( fn=eat, inputs=food_box, outputs=[food_box, status_box] ) ``` Notice how when there is no food, we only update the `status_box` element. We skipped updating the `food_box` component. Dictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others. Keep in mind that with dictionary returns,
Function Return List vs Dict
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
d_box` component. Dictionary returns are helpful when an event listener affects many components on return, or conditionally affects outputs and not others. Keep in mind that with dictionary returns, we still need to specify the possible outputs in the event listener.
Function Return List vs Dict
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
The return value of an event listener function is usually the updated value of the corresponding output Component. Sometimes we want to update the configuration of the Component as well, such as the visibility. In this case, we return a new Component, setting the properties we want to change. $code_blocks_essay_simple $demo_blocks_essay_simple See how we can configure the Textbox itself through a new `gr.Textbox()` method. The `value=` argument can still be used to update the value along with Component configuration. Any arguments we do not set will preserve their previous values.
Updating Component Configurations
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
In some cases, you may want to leave a component's value unchanged. Gradio includes a special function, `gr.skip()`, which can be returned from your function. Returning this function will keep the output component (or components') values as is. Let us illustrate with an example: $code_skip $demo_skip Note the difference between returning `None` (which generally resets a component's value to an empty state) versus returning `gr.skip()`, which leaves the component value unchanged. Tip: if you have multiple output components, and you want to leave all of their values unchanged, you can just return a single `gr.skip()` instead of returning a tuple of skips, one for each element.
Not Changing a Component's Value
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
You can also run events consecutively by using the `then` method of an event listener. This will run an event after the previous event has finished running. This is useful for running events that update components in multiple steps. For example, in the chatbot example below, we first update the chatbot with the user message immediately, and then update the chatbot with the computer response after a simulated delay. $code_chatbot_consecutive $demo_chatbot_consecutive The `.then()` method of an event listener executes the subsequent event regardless of whether the previous event raised any errors. If you'd like to only run subsequent events if the previous event executed successfully, use the `.success()` method, which takes the same arguments as `.then()`. Conversely, if you'd like to only run subsequent events if the previous event failed (i.e., raised an error), use the `.failure()` method. This is particularly useful for error handling workflows, such as displaying error messages or restoring previous states when an operation fails.
Running Events Consecutively
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
Often times, you may want to bind multiple triggers to the same function. For example, you may want to allow a user to click a submit button, or press enter to submit a form. You can do this using the `gr.on` method and passing a list of triggers to the `trigger`. $code_on_listener_basic $demo_on_listener_basic You can use decorator syntax as well: $code_on_listener_decorator You can use `gr.on` to create "live" events by binding to the `change` event of components that implement it. If you do not specify any triggers, the function will automatically bind to all `change` event of all input components that include a `change` event (for example `gr.Textbox` has a `change` event whereas `gr.Button` does not). $code_on_listener_live $demo_on_listener_live You can follow `gr.on` with `.then`, just like any regular event listener. This handy method should save you from having to write a lot of repetitive code!
Binding Multiple Triggers to a Function
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners Guide
If you want to set a Component's value to always be a function of the value of other Components, you can use the following shorthand: ```python with gr.Blocks() as demo: num1 = gr.Number() num2 = gr.Number() product = gr.Number(lambda a, b: a * b, inputs=[num1, num2]) ``` This functionally the same as: ```python with gr.Blocks() as demo: num1 = gr.Number() num2 = gr.Number() product = gr.Number() gr.on( [num1.change, num2.change, demo.load], lambda a, b: a * b, inputs=[num1, num2], outputs=product ) ```
Binding a Component Value Directly to a Function of Other Components
https://gradio.app/guides/blocks-and-event-listeners
Building With Blocks - Blocks And Event Listeners 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
Use `gradio.Server` instead of `gr.Blocks` when any of the following apply: - You want a **completely custom (potentially vibe-coded) UI** (your own HTML, React, Svelte, etc.) powered by Gradio's backend - You want **full FastAPI control** (custom GET/POST routes, middleware, dependency injection) alongside Gradio API endpoints - You're building a service to **host on Spaces** with or without ZeroGPU but don't need Gradio components If you're happy with Gradio's built-in UI components, use `gr.Blocks`, `gr.ChatInterface`, or `gr.Interface` instead.
When to use `gradio.Server`
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
`gradio.Server` is included in the main Gradio package. If you want MCP support, install the extra: ```bash pip install "gradio[mcp]" ```
Installation
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
Here's the simplest possible Server mode app — a single API endpoint with no UI: ```python from gradio import Server app = Server() @app.api(name="hello") def hello(name: str) -> str: return f"Hello, {name}!" app.launch() ``` That's it. When you run this script, you get: - A Gradio API endpoint at `/gradio_api/call/hello` with queuing and SSE streaming - Auto-generated API docs at `/gradio_api/info` - A Python and JavaScript client that can call `/hello` by name You can test it with the Gradio Python client: ```python from gradio_client import Client client = Client("http://localhost:7860") result = client.predict("World", api_name="/hello") print(result) "Hello, World!" ```
A Minimal Example
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
Since `gradio.Server` inherits from FastAPI, you can add any route directly: ```python from gradio import Server from fastapi.responses import HTMLResponse app = Server() @app.api(name="hello") def hello(name: str) -> str: return f"Hello, {name}!" @app.get("/", response_class=HTMLResponse) async def homepage(): return "<h1>Welcome to my API</h1>" @app.get("/health") async def health(): return {"status": "ok"} app.launch() ``` Your custom routes take priority over Gradio's default routes. For example, your `GET /` replaces Gradio's default UI page. You can also use all standard FastAPI features — `app.add_middleware()`, `app.include_router()`, dependency injection, exception handlers, and so on.
Custom Routes
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
To expose your API endpoints as MCP tools, add the `@app.mcp.tool()` decorator and pass `mcp_server=True` to `launch()`: ```python from gradio import Server app = Server() @app.mcp.tool(name="hello") @app.api(name="hello") def hello(name: str) -> str: """Greet someone by name.""" return f"Hello, {name}!" app.launch(mcp_server=True) ``` The `@app.mcp.tool()` and `@app.api()` decorators are independent — you can have API-only endpoints or MCP-only tools. Stack both when you want a function available through both.
MCP Tools
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
This example combines everything: custom HTML served at `/`, Gradio API endpoints with concurrency limits, MCP tools, and a custom REST endpoint, and two connected via [the Gradio JavaScript client](/guides/getting-started-with-the-js-client). $code_server_app Run it with: ```bash python run.py ``` Then open `http://localhost:7860` in your browser. The custom HTML page uses the `@gradio/client` JavaScript library to call the Gradio API endpoints. Meanwhile, the same endpoints are available as MCP tools and through the REST API at `/gradio_api/call/add` and `/gradio_api/call/multiply`.
A Complete Example with the JavaScript Client
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode Guide
`app.api()` supports all of the same concurrency and streaming options as `gr.api()`: ```python @app.api(name="generate", concurrency_limit=2, stream_every=0.5) async def generate(prompt: str): for token in model.generate(prompt): yield token ``` Generator functions automatically stream results via SSE, just like in a regular Gradio app. The `concurrency_limit` parameter controls how many concurrent calls to this endpoint are allowed. By default, this is set to 1, since many ML workloads that run on GPU can only support a single user at a time. However, you can increase this, or set to `None` to use FastAPI defaults, if you are e.g. calling an external API. For the full API reference, see the [`Server` documentation](/docs/gradio/server).
Concurrency and Streaming
https://gradio.app/guides/server-mode
Gradio Clients And Lite - Server Mode 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
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
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
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