text
stringlengths
0
2k
heading1
stringlengths
4
79
source_page_url
stringclasses
180 values
source_page_title
stringclasses
180 values
Most of Gradio's frontend components are published on [npm](https://www.npmjs.com/), the javascript package repository. This means that you can use them to save yourself time while incorporating common patterns in your component, like uploading files. For example, the `@gradio/upload` package has `Upload` and `ModifyUpload` components for properly uploading files to the Gradio server. Here is how you can use them to create a user interface to upload and display PDF files. ```svelte <script> import { type FileData, Upload, ModifyUpload } from "@gradio/upload"; import { Empty, UploadText, BlockLabel } from "@gradio/atoms"; </script> <BlockLabel Icon={File} label={label || "PDF"} /> {if value === null && interactive} <Upload filetype="application/pdf" on:load={handle_load} {root} > <UploadText type="file" i18n={gradio.i18n} /> </Upload> {:else if value !== null} {if interactive} <ModifyUpload i18n={gradio.i18n} on:clear={handle_clear}/> {/if} <iframe title={value.orig_name || "PDF"} src={value.data} height="{height}px" width="100%"></iframe> {:else} <Empty size="large"> <File/> </Empty> {/if} ``` You can also combine existing Gradio components to create entirely unique experiences. Like rendering a gallery of chatbot conversations. The possibilities are endless, please read the documentation on our javascript packages [here](https://gradio.app/main/docs/js). We'll be adding more packages and documentation over the coming weeks!
Leveraging Existing Gradio Components
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
You can explore our component library via Storybook. You'll be able to interact with our components and see them in their various states. For those interested in design customization, we provide the CSS variables consisting of our color palette, radii, spacing, and the icons we use - so you can easily match up your custom component with the style of our core components. This Storybook will be regularly updated with any new additions or changes. [Storybook Link](https://gradio.app/main/docs/js/storybook)
Matching Gradio Core's Design System
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
If you want to make use of the vast vite ecosystem, you can use the `gradio.config.js` file to configure your component's build process. This allows you to make use of tools like tailwindcss, mdsvex, and more. Currently, it is possible to configure the following: Vite options: - `plugins`: A list of vite plugins to use. Svelte options: - `preprocess`: A list of svelte preprocessors to use. - `extensions`: A list of file extensions to compile to `.svelte` files. - `build.target`: The target to build for, this may be necessary to support newer javascript features. See the [esbuild docs](https://esbuild.github.io/api/target) for more information. The `gradio.config.js` file should be placed in the root of your component's `frontend` directory. A default config file is created for you when you create a new component. But you can also create your own config file, if one doesn't exist, and use it to customize your component's build process. Example for a Vite plugin Custom components can use Vite plugins to customize the build process. Check out the [Vite Docs](https://vitejs.dev/guide/using-plugins.html) for more information. Here we configure [TailwindCSS](https://tailwindcss.com), a utility-first CSS framework. Setup is easiest using the version 4 prerelease. ``` npm install tailwindcss@next @tailwindcss/vite@next ``` In `gradio.config.js`: ```typescript import tailwindcss from "@tailwindcss/vite"; export default { plugins: [tailwindcss()] }; ``` Then create a `style.css` file with the following content: ```css @import "tailwindcss"; ``` Import this file into `Index.svelte`. Note, that you need to import the css file containing `@import` and cannot just use a `<style>` tag and use `@import` there. ```svelte <script lang="ts"> [...] import "./style.css"; [...] </script> ``` Example for Svelte options In `gradio.config.js` you can also specify a some Svelte options to apply to the Svelte compilation. In this example we will add support for
Custom configuration
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
.css"; [...] </script> ``` Example for Svelte options In `gradio.config.js` you can also specify a some Svelte options to apply to the Svelte compilation. In this example we will add support for [`mdsvex`](https://mdsvex.pngwn.io), a Markdown preprocessor for Svelte. In order to do this we will need to add a [Svelte Preprocessor](https://svelte.dev/docs/svelte-compilerpreprocess) to the `svelte` object in `gradio.config.js` and configure the [`extensions`](https://github.com/sveltejs/vite-plugin-svelte/blob/HEAD/docs/config.mdconfig-file) field. Other options are not currently supported. First, install the `mdsvex` plugin: ```bash npm install mdsvex ``` Then add the following to `gradio.config.js`: ```typescript import { mdsvex } from "mdsvex"; export default { svelte: { preprocess: [ mdsvex() ], extensions: [".svelte", ".svx"] } }; ``` Now we can create `mdsvex` documents in our component's `frontend` directory and they will be compiled to `.svelte` files. ```md <!-- HelloWorld.svx --> <script lang="ts"> import { Block } from "@gradio/atoms"; export let title = "Hello World"; </script> <Block label="Hello World"> {title} This is a markdown file. </Block> ``` We can then use the `HelloWorld.svx` file in our components: ```svelte <script lang="ts"> import HelloWorld from "./HelloWorld.svx"; </script> <HelloWorld /> ```
Custom configuration
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
You now know how to create delightful frontends for your components!
Conclusion
https://gradio.app/guides/frontend
Custom Components - Frontend Guide
All components inherit from one of three classes `Component`, `FormComponent`, or `BlockContext`. You need to inherit from one so that your component behaves like all other gradio components. When you start from a template with `gradio cc create --template`, you don't need to worry about which one to choose since the template uses the correct one. For completeness, and in the event that you need to make your own component from scratch, we explain what each class is for. * `FormComponent`: Use this when you want your component to be grouped together in the same `Form` layout with other `FormComponents`. The `Slider`, `Textbox`, and `Number` components are all `FormComponents`. * `BlockContext`: Use this when you want to place other components "inside" your component. This enabled `with MyComponent() as component:` syntax. * `Component`: Use this for all other cases. Tip: If your component supports streaming output, inherit from the `StreamingOutput` class. Tip: If you inherit from `BlockContext`, you also need to set the metaclass to be `ComponentMeta`. See example below. ```python from gradio.blocks import BlockContext from gradio.component_meta import ComponentMeta @document() class Row(BlockContext, metaclass=ComponentMeta): pass ```
Which Class to Inherit From
https://gradio.app/guides/backend
Custom Components - Backend Guide
When you inherit from any of these classes, the following methods must be implemented. Otherwise the Python interpreter will raise an error when you instantiate your component! `preprocess` and `postprocess` Explained in the [Key Concepts](./key-component-conceptsthe-value-and-how-it-is-preprocessed-postprocessed) guide. They handle the conversion from the data sent by the frontend to the format expected by the python function. ```python def preprocess(self, x: Any) -> Any: """ Convert from the web-friendly (typically JSON) value in the frontend to the format expected by the python function. """ return x def postprocess(self, y): """ Convert from the data returned by the python function to the web-friendly (typically JSON) value expected by the frontend. """ return y ``` `process_example` Takes in the original Python value and returns the modified value that should be displayed in the examples preview in the app. If not provided, the `.postprocess()` method is used instead. Let's look at the following example from the `SimpleDropdown` component. ```python def process_example(self, input_data): return next((c[0] for c in self.choices if c[1] == input_data), None) ``` Since `self.choices` is a list of tuples corresponding to (`display_name`, `value`), this converts the value that a user provides to the display value (or if the value is not present in `self.choices`, it is converted to `None`). `api_info` A JSON-schema representation of the value that the `preprocess` expects. This powers api usage via the gradio clients. You do **not** need to implement this yourself if you components specifies a `data_model`. The `data_model` in the following section. ```python def api_info(self) -> dict[str, list[str]]: """ A JSON-schema representation of the value that the `preprocess` expects and the `postprocess` returns. """ pass ``` `example_payload` A
The methods you need to implement
https://gradio.app/guides/backend
Custom Components - Backend Guide
pi_info(self) -> dict[str, list[str]]: """ A JSON-schema representation of the value that the `preprocess` expects and the `postprocess` returns. """ pass ``` `example_payload` An example payload for your component, e.g. something that can be passed into the `.preprocess()` method of your component. The example input is displayed in the `View API` page of a Gradio app that uses your custom component. Must be JSON-serializable. If your component expects a file, it is best to use a publicly accessible URL. ```python def example_payload(self) -> Any: """ The example inputs for this component for API usage. Must be JSON-serializable. """ pass ``` `example_value` An example value for your component, e.g. something that can be passed into the `.postprocess()` method of your component. This is used as the example value in the default app that is created in custom component development. ```python def example_payload(self) -> Any: """ The example inputs for this component for API usage. Must be JSON-serializable. """ pass ``` `flag` Write the component's value to a format that can be stored in the `csv` or `json` file used for flagging. You do **not** need to implement this yourself if you components specifies a `data_model`. The `data_model` in the following section. ```python def flag(self, x: Any | GradioDataModel, flag_dir: str | Path = "") -> str: pass ``` `read_from_flag` Convert from the format stored in the `csv` or `json` file used for flagging to the component's python `value`. You do **not** need to implement this yourself if you components specifies a `data_model`. The `data_model` in the following section. ```python def read_from_flag( self, x: Any, ) -> GradioDataModel | Any: """ Convert the data from the csv or jsonl file into the component state. """ return x ```
The methods you need to implement
https://gradio.app/guides/backend
Custom Components - Backend Guide
""" Convert the data from the csv or jsonl file into the component state. """ return x ```
The methods you need to implement
https://gradio.app/guides/backend
Custom Components - Backend Guide
The `data_model` is how you define the expected data format your component's value will be stored in the frontend. It specifies the data format your `preprocess` method expects and the format the `postprocess` method returns. It is not necessary to define a `data_model` for your component but it greatly simplifies the process of creating a custom component. If you define a custom component you only need to implement four methods - `preprocess`, `postprocess`, `example_payload`, and `example_value`! You define a `data_model` by defining a [pydantic model](https://docs.pydantic.dev/latest/concepts/models/basic-model-usage) that inherits from either `GradioModel` or `GradioRootModel`. This is best explained with an example. Let's look at the core `Video` component, which stores the video data as a JSON object with two keys `video` and `subtitles` which point to separate files. ```python from gradio.data_classes import FileData, GradioModel class VideoData(GradioModel): video: FileData subtitles: Optional[FileData] = None class Video(Component): data_model = VideoData ``` By adding these four lines of code, your component automatically implements the methods needed for API usage, the flagging methods, and example caching methods! It also has the added benefit of self-documenting your code. Anyone who reads your component code will know exactly the data it expects. Tip: If your component expects files to be uploaded from the frontend, your must use the `FileData` model! It will be explained in the following section. Tip: Read the pydantic docs [here](https://docs.pydantic.dev/latest/concepts/models/basic-model-usage). The difference between a `GradioModel` and a `GradioRootModel` is that the `RootModel` will not serialize the data to a dictionary. For example, the `Names` model will serialize the data to `{'names': ['freddy', 'pete']}` whereas the `NamesRoot` model will serialize it to `['freddy', 'pete']`. ```python from typing import List clas
The `data_model`
https://gradio.app/guides/backend
Custom Components - Backend Guide
example, the `Names` model will serialize the data to `{'names': ['freddy', 'pete']}` whereas the `NamesRoot` model will serialize it to `['freddy', 'pete']`. ```python from typing import List class Names(GradioModel): names: List[str] class NamesRoot(GradioRootModel): root: List[str] ``` Even if your component does not expect a "complex" JSON data structure it can be beneficial to define a `GradioRootModel` so that you don't have to worry about implementing the API and flagging methods. Tip: Use classes from the Python typing library to type your models. e.g. `List` instead of `list`.
The `data_model`
https://gradio.app/guides/backend
Custom Components - Backend Guide
If your component expects uploaded files as input, or returns saved files to the frontend, you **MUST** use the `FileData` to type the files in your `data_model`. When you use the `FileData`: * Gradio knows that it should allow serving this file to the frontend. Gradio automatically blocks requests to serve arbitrary files in the computer running the server. * Gradio will automatically place the file in a cache so that duplicate copies of the file don't get saved. * The client libraries will automatically know that they should upload input files prior to sending the request. They will also automatically download files. If you do not use the `FileData`, your component will not work as expected!
Handling Files
https://gradio.app/guides/backend
Custom Components - Backend Guide
The events triggers for your component are defined in the `EVENTS` class attribute. This is a list that contains the string names of the events. Adding an event to this list will automatically add a method with that same name to your component! You can import the `Events` enum from `gradio.events` to access commonly used events in the core gradio components. For example, the following code will define `text_submit`, `file_upload` and `change` methods in the `MyComponent` class. ```python from gradio.events import Events from gradio.components import FormComponent class MyComponent(FormComponent): EVENTS = [ "text_submit", "file_upload", Events.change ] ``` Tip: Don't forget to also handle these events in the JavaScript code!
Adding Event Triggers To Your Component
https://gradio.app/guides/backend
Custom Components - Backend Guide
Conclusion
https://gradio.app/guides/backend
Custom Components - Backend Guide
Make sure you have gradio 5.0 or higher installed as well as node 20+. As of the time of publication, the latest release is 4.1.1. Also, please read the [Five Minute Tour](./custom-components-in-five-minutes) of custom components and the [Key Concepts](./key-component-concepts) guide before starting.
Step 0: Prerequisites
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Navigate to a directory of your choosing and run the following command: ```bash gradio cc create PDF ``` Tip: You should change the name of the component. Some of the screenshots assume the component is called `PDF` but the concepts are the same! This will create a subdirectory called `pdf` in your current working directory. There are three main subdirectories in `pdf`: `frontend`, `backend`, and `demo`. If you open `pdf` in your code editor, it will look like this: ![directory structure](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/CodeStructure.png) Tip: For this demo we are not templating off a current gradio component. But you can see the list of available templates with `gradio cc show` and then pass the template name to the `--template` option, e.g. `gradio cc create <Name> --template <foo>`
Step 1: Creating the custom component
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to use the [pdfjs](https://mozilla.github.io/pdf.js/) javascript library to display the pdfs in the frontend. Let's start off by adding it to our frontend project's dependencies, as well as adding a couple of other projects we'll need. From within the `frontend` directory, run `npm install @gradio/client @gradio/upload @gradio/icons @gradio/button` and `npm install --save-dev [email protected]`. Also, let's uninstall the `@zerodevx/svelte-json-view` dependency by running `npm uninstall @zerodevx/svelte-json-view`. The complete `package.json` should look like this: ```json { "name": "gradio_pdf", "version": "0.2.0", "description": "Gradio component for displaying PDFs", "type": "module", "author": "", "license": "ISC", "private": false, "main_changeset": true, "exports": { ".": "./Index.svelte", "./example": "./Example.svelte", "./package.json": "./package.json" }, "devDependencies": { "pdfjs-dist": "3.11.174" }, "dependencies": { "@gradio/atoms": "0.2.0", "@gradio/statustracker": "0.3.0", "@gradio/utils": "0.2.0", "@gradio/client": "0.7.1", "@gradio/upload": "0.3.2", "@gradio/icons": "0.2.0", "@gradio/button": "0.2.3", "pdfjs-dist": "3.11.174" } } ``` Tip: Running `npm install` will install the latest version of the package available. You can install a specific version with `npm install package@<version>`. You can find all of the gradio javascript package documentation [here](https://www.gradio.app/main/docs/js). It is recommended you use the same versions as me as the API can change. Navigate to `Index.svelte` and delete mentions of `JSONView` ```ts import { JsonView } from "@zerodevx/svelte-json-view"; ``` ```svelte <JsonView json={value} /> ```
Step 2: Frontend - modify javascript dependencies
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Run the `dev` command to launch the development server. This will open the demo in `demo/app.py` in an environment where changes to the `frontend` and `backend` directories will reflect instantaneously in the launched app. After launching the dev server, you should see a link printed to your console that says `Frontend Server (Go here): ... `. ![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/dev_server_terminal.png) You should see the following: ![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/frontend_start.png) Its not impressive yet but we're ready to start coding!
Step 3: Frontend - Launching the Dev Server
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to start off by first writing the skeleton of our frontend and then adding the pdf rendering logic. Add the following imports and expose the following properties to the top of your file in the `<script>` tag. You may get some warnings from your code editor that some props are not used. That's ok. ```ts import { tick } from "svelte"; import type { Gradio } from "@gradio/utils"; import { Block, BlockLabel } from "@gradio/atoms"; import { File } from "@gradio/icons"; import { StatusTracker } from "@gradio/statustracker"; import type { LoadingStatus } from "@gradio/statustracker"; import type { FileData } from "@gradio/client"; import { Upload, ModifyUpload } from "@gradio/upload"; export let elem_id = ""; export let elem_classes: string[] = []; export let visible = true; export let value: FileData | null = null; export let container = true; export let scale: number | null = null; export let root: string; export let height: number | null = 500; export let label: string; export let proxy_url: string; export let min_width: number | undefined = undefined; export let loading_status: LoadingStatus; export let gradio: Gradio<{ change: never; upload: never; }>; let _value = value; let old_value = _value; ``` Tip: The `gradio`` object passed in here contains some metadata about the application as well as some utility methods. One of these utilities is a dispatch method. We want to dispatch change and upload events whenever our PDF is changed or updated. This line provides type hints that these are the only events we will be dispatching. We want our frontend component to let users upload a PDF document if there isn't one already loaded. If it is loaded, we want to display it underneath a "clear" button that lets our users upload a new document. We're going to use the `Upload` and `ModifyUpload` components that come with the `@gradio/upload` package to do this. Underneath the `</script>` tag, delete all
Step 4: Frontend - The basic skeleton
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
lets our users upload a new document. We're going to use the `Upload` and `ModifyUpload` components that come with the `@gradio/upload` package to do this. Underneath the `</script>` tag, delete all the current code and add the following: ```svelte <Block {visible} {elem_id} {elem_classes} {container} {scale} {min_width}> {if loading_status} <StatusTracker autoscroll={gradio.autoscroll} i18n={gradio.i18n} {...loading_status} /> {/if} <BlockLabel show_label={label !== null} Icon={File} float={value === null} label={label || "File"} /> {if _value} <ModifyUpload i18n={gradio.i18n} absolute /> {:else} <Upload filetype={"application/pdf"} file_count="single" {root} > Upload your PDF </Upload> {/if} </Block> ``` You should see the following when you navigate to your app after saving your current changes: ![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/frontend_1.png)
Step 4: Frontend - The basic skeleton
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
The `Upload your PDF` text looks a bit small and barebones. Lets customize it! Create a new file called `PdfUploadText.svelte` and copy the following code. Its creating a new div to display our "upload text" with some custom styling. Tip: Notice that we're leveraging Gradio core's existing css variables here: `var(--size-60)` and `var(--body-text-color-subdued)`. This allows our component to work nicely in light mode and dark mode, as well as with Gradio's built-in themes. ```svelte <script lang="ts"> import { Upload as UploadIcon } from "@gradio/icons"; export let hovered = false; </script> <div class="wrap"> <span class="icon-wrap" class:hovered><UploadIcon /> </span> Drop PDF <span class="or">- or -</span> Click to Upload </div> <style> .wrap { display: flex; flex-direction: column; justify-content: center; align-items: center; min-height: var(--size-60); color: var(--block-label-text-color); line-height: var(--line-md); height: 100%; padding-top: var(--size-3); } .or { color: var(--body-text-color-subdued); display: flex; } .icon-wrap { width: 30px; margin-bottom: var(--spacing-lg); } @media (--screen-md) { .wrap { font-size: var(--text-lg); } } .hovered { color: var(--color-accent); } </style> ``` Now import `PdfUploadText.svelte` in your `<script>` and pass it to the `Upload` component! ```svelte import PdfUploadText from "./PdfUploadText.svelte"; ... <Upload filetype={"application/pdf"} file_count="single" {root} > <PdfUploadText /> </Upload> ``` After saving your code, the frontend should now look like this: ![](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/better_upload.png)
Step 5: Frontend - Nicer Upload Text
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
This is the most advanced javascript part. It took me a while to figure it out! Do not worry if you have trouble, the important thing is to not be discouraged 💪 Ask for help in the gradio [discord](https://discord.gg/hugging-face-879548962464493619) if you need and ask for help. With that out of the way, let's start off by importing `pdfjs` and loading the code of the pdf worker from the mozilla cdn. ```ts import pdfjsLib from "pdfjs-dist"; ... pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js"; ``` Also create the following variables: ```ts let pdfDoc; let numPages = 1; let currentPage = 1; let canvasRef; ``` Now, we will use `pdfjs` to render a given page of the PDF onto an `html` document. Add the following code to `Index.svelte`: ```ts async function get_doc(value: FileData) { const loadingTask = pdfjsLib.getDocument(value.url); pdfDoc = await loadingTask.promise; numPages = pdfDoc.numPages; render_page(); } function render_page() { // Render a specific page of the PDF onto the canvas pdfDoc.getPage(currentPage).then(page => { const ctx = canvasRef.getContext('2d') ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); let viewport = page.getViewport({ scale: 1 }); let scale = height / viewport.height; viewport = page.getViewport({ scale: scale }); const renderContext = { canvasContext: ctx, viewport, }; canvasRef.width = viewport.width; canvasRef.height = viewport.height; page.render(renderContext); }); } // If the value changes, render the PDF of the currentPage $: if(JSON.stringify(old_value) != JSON.stringify(_value)) { if (_value){ get_doc(_value); } old_value = _value; gradio.dispatch("change"); } ```
Step 6: PDF Rendering logic
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
$: if(JSON.stringify(old_value) != JSON.stringify(_value)) { if (_value){ get_doc(_value); } old_value = _value; gradio.dispatch("change"); } ``` Tip: The `$:` syntax in svelte is how you declare statements to be reactive. Whenever any of the inputs of the statement change, svelte will automatically re-run that statement. Now place the `canvas` underneath the `ModifyUpload` component: ```svelte <div class="pdf-canvas" style="height: {height}px"> <canvas bind:this={canvasRef}></canvas> </div> ``` And add the following styles to the `<style>` tag: ```svelte <style> .pdf-canvas { display: flex; justify-content: center; align-items: center; } </style> ```
Step 6: PDF Rendering logic
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Now for the fun part - actually rendering the PDF when the file is uploaded! Add the following functions to the `<script>` tag: ```ts async function handle_clear() { _value = null; await tick(); gradio.dispatch("change"); } async function handle_upload({detail}: CustomEvent<FileData>): Promise<void> { value = detail; await tick(); gradio.dispatch("change"); gradio.dispatch("upload"); } ``` Tip: The `gradio.dispatch` method is actually what is triggering the `change` or `upload` events in the backend. For every event defined in the component's backend, we will explain how to do this in Step 9, there must be at least one `gradio.dispatch("<event-name>")` call. These are called `gradio` events and they can be listended from the entire Gradio application. You can dispatch a built-in `svelte` event with the `dispatch` function. These events can only be listened to from the component's direct parent. Learn about svelte events from the [official documentation](https://learn.svelte.dev/tutorial/component-events). Now we will run these functions whenever the `Upload` component uploads a file and whenever the `ModifyUpload` component clears the current file. The `<Upload>` component dispatches a `load` event with a payload of type `FileData` corresponding to the uploaded file. The `on:load` syntax tells `Svelte` to automatically run this function in response to the event. ```svelte <ModifyUpload i18n={gradio.i18n} on:clear={handle_clear} absolute /> ... <Upload on:load={handle_upload} filetype={"application/pdf"} file_count="single" {root} > <PdfUploadText/> </Upload> ``` Congratulations! You have a working pdf uploader! ![upload-gif](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/pdf_component_gif_docs.gif)
Step 7: Handling The File Upload And Clear
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
If a user uploads a PDF document with multiple pages, they will only be able to see the first one. Let's add some buttons to help them navigate the page. We will use the `BaseButton` from `@gradio/button` so that they look like regular Gradio buttons. Import the `BaseButton` and add the following functions that will render the next and previous page of the PDF. ```ts import { BaseButton } from "@gradio/button"; ... function next_page() { if (currentPage >= numPages) { return; } currentPage++; render_page(); } function prev_page() { if (currentPage == 1) { return; } currentPage--; render_page(); } ``` Now we will add them underneath the canvas in a separate `<div>` ```svelte ... <ModifyUpload i18n={gradio.i18n} on:clear={handle_clear} absolute /> <div class="pdf-canvas" style="height: {height}px"> <canvas bind:this={canvasRef}></canvas> </div> <div class="button-row"> <BaseButton on:click={prev_page}> ⬅️ </BaseButton> <span class="page-count"> {currentPage} / {numPages} </span> <BaseButton on:click={next_page}> ➡️ </BaseButton> </div> ... <style> .button-row { display: flex; flex-direction: row; width: 100%; justify-content: center; align-items: center; } .page-count { margin: 0 10px; font-family: var(--font-mono); } ``` Congratulations! The frontend is almost complete 🎉 ![multipage-pdf-gif](https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/pdf_multipage.gif)
Step 8: Adding buttons to navigate pages
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
We're going to want users of our component to get a preview of the PDF if its used as an `example` in a `gr.Interface` or `gr.Examples`. To do so, we're going to add some of the pdf rendering logic in `Index.svelte` to `Example.svelte`. ```svelte <script lang="ts"> export let value: string; export let type: "gallery" | "table"; export let selected = false; import pdfjsLib from "pdfjs-dist"; pdfjsLib.GlobalWorkerOptions.workerSrc = "https://cdn.bootcss.com/pdf.js/3.11.174/pdf.worker.js"; let pdfDoc; let canvasRef; async function get_doc(url: string) { const loadingTask = pdfjsLib.getDocument(url); pdfDoc = await loadingTask.promise; renderPage(); } function renderPage() { // Render a specific page of the PDF onto the canvas pdfDoc.getPage(1).then(page => { const ctx = canvasRef.getContext('2d') ctx.clearRect(0, 0, canvasRef.width, canvasRef.height); const viewport = page.getViewport({ scale: 0.2 }); const renderContext = { canvasContext: ctx, viewport }; canvasRef.width = viewport.width; canvasRef.height = viewport.height; page.render(renderContext); }); } $: get_doc(value); </script> <div class:table={type === "table"} class:gallery={type === "gallery"} class:selected style="justify-content: center; align-items: center; display: flex; flex-direction: column;" > <canvas bind:this={canvasRef}></canvas> </div> <style> .gallery { padding: var(--size-1) var(--size-2); } </style> ``` Tip: Exercise for the reader - reduce the code duplication between `Index.svelte` and `Example.svelte` 😊 You will not be able to render examples until we make some changes to the backend code in the next step!
Step 8.5: The Example view
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
The backend changes needed are smaller. We're almost done! What we're going to do is: * Add `change` and `upload` events to our component. * Add a `height` property to let users control the height of the PDF. * Set the `data_model` of our component to be `FileData`. This is so that Gradio can automatically cache and safely serve any files that are processed by our component. * Modify the `preprocess` method to return a string corresponding to the path of our uploaded PDF. * Modify the `postprocess` to turn a path to a PDF created in an event handler to a `FileData`. When all is said an done, your component's backend code should look like this: ```python from __future__ import annotations from typing import Any, Callable, TYPE_CHECKING from gradio.components.base import Component from gradio.data_classes import FileData from gradio import processing_utils if TYPE_CHECKING: from gradio.components import Timer class PDF(Component): EVENTS = ["change", "upload"] data_model = FileData def __init__(self, value: Any = None, *, height: int | None = None, label: str | I18nData | None = None, info: str | I18nData | None = None, show_label: bool | None = None, container: bool = True, scale: int | None = None, min_width: int | None = None, interactive: bool | None = None, visible: bool = True, elem_id: str | None = None, elem_classes: list[str] | str | None = None, render: bool = True, load_fn: Callable[..., Any] | None = None, every: Timer | float | None = None): super().__init__(value, label=label, info=info, show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible,
Step 9: The backend
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
show_label=show_label, container=container, scale=scale, min_width=min_width, interactive=interactive, visible=visible, elem_id=elem_id, elem_classes=elem_classes, render=render, load_fn=load_fn, every=every) self.height = height def preprocess(self, payload: FileData) -> str: return payload.path def postprocess(self, value: str | None) -> FileData: if not value: return None return FileData(path=value) def example_payload(self): return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf" def example_value(self): return "https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/fw9.pdf" ```
Step 9: The backend
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
To test our backend code, let's add a more complex demo that performs Document Question and Answering with huggingface transformers. In our `demo` directory, create a `requirements.txt` file with the following packages ``` torch transformers pdf2image pytesseract ``` Tip: Remember to install these yourself and restart the dev server! You may need to install extra non-python dependencies for `pdf2image`. See [here](https://pypi.org/project/pdf2image/). Feel free to write your own demo if you have trouble. ```python import gradio as gr from gradio_pdf import PDF from pdf2image import convert_from_path from transformers import pipeline from pathlib import Path dir_ = Path(__file__).parent p = pipeline( "document-question-answering", model="impira/layoutlm-document-qa", ) def qa(question: str, doc: str) -> str: img = convert_from_path(doc)[0] output = p(img, question) return sorted(output, key=lambda x: x["score"], reverse=True)[0]['answer'] demo = gr.Interface( qa, [gr.Textbox(label="Question"), PDF(label="Document")], gr.Textbox(), ) demo.launch() ``` See our demo in action below! <video autoplay muted loop> <source src="https://gradio-builds.s3.amazonaws.com/assets/pdf-guide/PDFDemo.mov" type="video/mp4" /> </video> Finally lets build our component with `gradio cc build` and publish it with the `gradio cc publish` command! This will guide you through the process of uploading your component to [PyPi](https://pypi.org/) and [HuggingFace Spaces](https://huggingface.co/spaces). Tip: You may need to add the following lines to the `Dockerfile` of your HuggingFace Space. ```Dockerfile RUN mkdir -p /tmp/cache/ RUN chmod a+rwx -R /tmp/cache/ RUN apt-get update && apt-get install -y poppler-utils tesseract-ocr ENV TRANSFORMERS_CACHE=/tmp/cache/ ```
Step 10: Add a demo and publish!
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
In order to use our new component in **any** gradio 4.0 app, simply install it with pip, e.g. `pip install gradio-pdf`. Then you can use it like the built-in `gr.File()` component (except that it will only accept and display PDF files). Here is a simple demo with the Blocks api: ```python import gradio as gr from gradio_pdf import PDF with gr.Blocks() as demo: pdf = PDF(label="Upload a PDF", interactive=True) name = gr.Textbox() pdf.upload(lambda f: f, pdf, name) demo.launch() ``` I hope you enjoyed this tutorial! The complete source code for our component is [here](https://huggingface.co/spaces/freddyaboulton/gradio_pdf/tree/main/src). Please don't hesitate to reach out to the gradio community on the [HuggingFace Discord](https://discord.gg/hugging-face-879548962464493619) if you get stuck.
Conclusion
https://gradio.app/guides/pdf-component-example
Custom Components - Pdf Component Example Guide
Plots accept a pandas Dataframe as their value. The plot also takes `x` and `y` which represent the names of the columns that represent the x and y axes respectively. Here's a simple example: $code_plot_guide_line $demo_plot_guide_line All plots have the same API, so you could swap this out with a `gr.ScatterPlot`: $code_plot_guide_scatter $demo_plot_guide_scatter The y axis column in the dataframe should have a numeric type, but the x axis column can be anything from strings, numbers, categories, or datetimes. $code_plot_guide_scatter_nominal $demo_plot_guide_scatter_nominal
Creating a Plot with a pd.Dataframe
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can break out your plot into series using the `color` argument. $code_plot_guide_series_nominal $demo_plot_guide_series_nominal If you wish to assign series specific colors, use the `color_map` arg, e.g. `gr.ScatterPlot(..., color_map={'white': 'FF9988', 'asian': '88EEAA', 'black': '333388'})` The color column can be numeric type as well. $code_plot_guide_series_quantitative $demo_plot_guide_series_quantitative
Breaking out Series by Color
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can aggregate values into groups using the `x_bin` and `y_aggregate` arguments. If your x-axis is numeric, providing an `x_bin` will create a histogram-style binning: $code_plot_guide_aggregate_quantitative $demo_plot_guide_aggregate_quantitative If your x-axis is a string type instead, they will act as the category bins automatically: $code_plot_guide_aggregate_nominal $demo_plot_guide_aggregate_nominal
Aggregating Values
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
You can use the `.select` listener to select regions of a plot. Click and drag on the plot below to select part of the plot. $code_plot_guide_selection $demo_plot_guide_selection You can combine this and the `.double_click` listener to create some zoom in/out effects by changing `x_lim` which sets the bounds of the x-axis: $code_plot_guide_zoom $demo_plot_guide_zoom If you had multiple plots with the same x column, your event listeners could target the x limits of all other plots so that the x-axes stay in sync. $code_plot_guide_zoom_sync $demo_plot_guide_zoom_sync
Selecting Regions
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
Take a look how you can have an interactive dashboard where the plots are functions of other Components. $code_plot_guide_interactive $demo_plot_guide_interactive It's that simple to filter and control the data presented in your visualization!
Making an Interactive Dashboard
https://gradio.app/guides/creating-plots
Data Science And Plots - Creating Plots Guide
```python from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///your_database.db') with gr.Blocks() as demo: gr.LinePlot(pd.read_sql_query("SELECT time, price from flight_info;", engine), x="time", y="price") ``` Let's see a a more interactive plot involving filters that modify your SQL query: ```python from sqlalchemy import create_engine import pandas as pd engine = create_engine('sqlite:///your_database.db') with gr.Blocks() as demo: origin = gr.Dropdown(["DFW", "DAL", "HOU"], value="DFW", label="Origin") gr.LinePlot(lambda origin: pd.read_sql_query(f"SELECT time, price from flight_info WHERE origin = {origin};", engine), inputs=origin, x="time", y="price") ```
SQLite
https://gradio.app/guides/connecting-to-a-database
Data Science And Plots - Connecting To A Database Guide
If you're using a different database format, all you have to do is swap out the engine, e.g. ```python engine = create_engine('postgresql://username:password@host:port/database_name') ``` ```python engine = create_engine('mysql://username:password@host:port/database_name') ``` ```python engine = create_engine('oracle://username:password@host:port/database_name') ```
Postgres, mySQL, and other databases
https://gradio.app/guides/connecting-to-a-database
Data Science And Plots - Connecting To A Database Guide
Time plots need a datetime column on the x-axis. Here's a simple example with some flight data: $code_plot_guide_temporal $demo_plot_guide_temporal
Creating a Plot with a pd.Dataframe
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
You may wish to bin data by time buckets. Use `x_bin` to do so, using a string suffix with "s", "m", "h" or "d", such as "15m" or "1d". $code_plot_guide_aggregate_temporal $demo_plot_guide_aggregate_temporal
Aggregating by Time
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
You can use `gr.DateTime` to accept input datetime data. This works well with plots for defining the x-axis range for the data. $code_plot_guide_datetime $demo_plot_guide_datetime Note how `gr.DateTime` can accept a full datetime string, or a shorthand using `now - [0-9]+[smhd]` format to refer to a past time. You will often have many time plots in which case you'd like to keep the x-axes in sync. The `DateTimeRange` custom component keeps a set of datetime plots in sync, and also uses the `.select` listener of plots to allow you to zoom into plots while keeping plots in sync. Because it is a custom component, you first need to `pip install gradio_datetimerange`. Then run the following: $code_plot_guide_datetimerange $demo_plot_guide_datetimerange Try zooming around in the plots and see how DateTimeRange updates. All the plots updates their `x_lim` in sync. You also have a "Back" link in the component to allow you to quickly zoom in and out.
DateTime Components
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
In many cases, you're working with live, realtime date, not a static dataframe. In this case, you'd update the plot regularly with a `gr.Timer()`. Assuming there's a `get_data` method that gets the latest dataframe: ```python with gr.Blocks() as demo: timer = gr.Timer(5) plot1 = gr.BarPlot(x="time", y="price") plot2 = gr.BarPlot(x="time", y="price", color="origin") timer.tick(lambda: [get_data(), get_data()], outputs=[plot1, plot2]) ``` You can also use the `every` shorthand to attach a `Timer` to a component that has a function value: ```python with gr.Blocks() as demo: timer = gr.Timer(5) plot1 = gr.BarPlot(get_data, x="time", y="price", every=timer) plot2 = gr.BarPlot(get_data, x="time", y="price", color="origin", every=timer) ```
RealTime Data
https://gradio.app/guides/time-plots
Data Science And Plots - Time Plots Guide
Use any of the standard Gradio form components to filter your data. You can do this via event listeners or function-as-value syntax. Let's look at the event listener approach first: $code_plot_guide_filters_events $demo_plot_guide_filters_events And this would be the function-as-value approach for the same demo. $code_plot_guide_filters
Filters
https://gradio.app/guides/filters-tables-and-stats
Data Science And Plots - Filters Tables And Stats Guide
Add `gr.DataFrame` and `gr.Label` to your dashboard for some hard numbers. $code_plot_guide_tables_stats $demo_plot_guide_tables_stats
Tables and Stats
https://gradio.app/guides/filters-tables-and-stats
Data Science And Plots - Filters Tables And Stats Guide
Let's start by using `llama-index` on top of `openai` to build a RAG chatbot on any text or PDF files that you can demo and share in less than 30 lines of code. You'll need to have an OpenAI key for this example (keep reading for the free, open-source equivalent!) $code_llm_llamaindex
Llama Index
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
Here's an example using `langchain` on top of `openai` to build a general-purpose chatbot. As before, you'll need to have an OpenAI key for this example. $code_llm_langchain Tip: For quick prototyping, the community-maintained <a href='https://github.com/AK391/langchain-gradio'>langchain-gradio repo</a> makes it even easier to build chatbots on top of LangChain.
LangChain
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
Of course, we could also use the `openai` library directy. Here a similar example to the LangChain , but this time with streaming as well: Tip: For quick prototyping, the <a href='https://github.com/gradio-app/openai-gradio'>openai-gradio library</a> makes it even easier to build chatbots on top of OpenAI models.
OpenAI
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
Of course, in many cases you want to run a chatbot locally. Here's the equivalent example using the SmolLM2-135M-Instruct model using the Hugging Face `transformers` library. $code_llm_hf_transformers
Hugging Face `transformers`
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
The SambaNova Cloud API provides access to full-precision open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the SambaNova API $code_llm_sambanova Tip: For quick prototyping, the <a href='https://github.com/gradio-app/sambanova-gradio'>sambanova-gradio library</a> makes it even easier to build chatbots on top of SambaNova models.
SambaNova
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
The Hyperbolic AI API provides access to many open-source models, such as the Llama family. Here's an example of how to build a Gradio app around the Hyperbolic $code_llm_hyperbolic Tip: For quick prototyping, the <a href='https://github.com/HyperbolicLabs/hyperbolic-gradio'>hyperbolic-gradio library</a> makes it even easier to build chatbots on top of Hyperbolic models.
Hyperbolic
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
Anthropic's Claude model can also be used via API. Here's a simple 20 questions-style game built on top of the Anthropic API: $code_llm_claude
Anthropic's Claude
https://gradio.app/guides/chatinterface-examples
Chatbots - Chatinterface Examples Guide
**Important Note**: if you are getting started, we recommend using the `gr.ChatInterface` to create chatbots -- its a high-level abstraction that makes it possible to create beautiful chatbot applications fast, often with a single line of code. [Read more about it here](/guides/creating-a-chatbot-fast). This tutorial will show how to make chatbot UIs from scratch with Gradio's low-level Blocks API. This will give you full control over your Chatbot UI. You'll start by first creating a a simple chatbot to display text, a second one to stream text responses, and finally a chatbot that can handle media files as well. The chatbot interface that we create will look something like this: $demo_chatbot_streaming **Prerequisite**: We'll be using the `gradio.Blocks` class to build our Chatbot demo. You can [read the Guide to Blocks first](https://gradio.app/blocks-and-event-listeners) if you are not already familiar with it. Also please make sure you are using the **latest version** version of Gradio: `pip install --upgrade gradio`.
Introduction
https://gradio.app/guides/creating-a-custom-chatbot-with-blocks
Chatbots - Creating A Custom Chatbot With Blocks Guide
Let's start with recreating the simple demo above. As you may have noticed, our bot simply randomly responds "How are you?", "Today is a great day", or "I'm very hungry" to any input. Here's the code to create this with Gradio: $code_chatbot_simple There are three Gradio components here: - A `Chatbot`, whose value stores the entire history of the conversation, as a list of response pairs between the user and bot. - A `Textbox` where the user can type their message, and then hit enter/submit to trigger the chatbot response - A `ClearButton` button to clear the Textbox and entire Chatbot history We have a single function, `respond()`, which takes in the entire history of the chatbot, appends a random message, waits 1 second, and then returns the updated chat history. The `respond()` function also clears the textbox when it returns. Of course, in practice, you would replace `respond()` with your own more complex function, which might call a pretrained model or an API, to generate a response. $demo_chatbot_simple Tip: For better type hinting and auto-completion in your IDE, you can use the `gr.ChatMessage` dataclass: ```python from gradio import ChatMessage def chat_function(message, history): history.append(ChatMessage(role="user", content=message)) history.append(ChatMessage(role="assistant", content="Hello, how can I help you?")) return history ```
A Simple Chatbot Demo
https://gradio.app/guides/creating-a-custom-chatbot-with-blocks
Chatbots - Creating A Custom Chatbot With Blocks Guide
There are several ways we can improve the user experience of the chatbot above. First, we can stream responses so the user doesn't have to wait as long for a message to be generated. Second, we can have the user message appear immediately in the chat history, while the chatbot's response is being generated. Here's the code to achieve that: $code_chatbot_streaming You'll notice that when a user submits their message, we now _chain_ two event events with `.then()`: 1. The first method `user()` updates the chatbot with the user message and clears the input field. Because we want this to happen instantly, we set `queue=False`, which would skip any queue had it been enabled. The chatbot's history is appended with `{"role": "user", "content": user_message}`. 2. The second method, `bot()` updates the chatbot history with the bot's response. Finally, we construct the message character by character and `yield` the intermediate outputs as they are being constructed. Gradio automatically turns any function with the `yield` keyword [into a streaming output interface](/guides/key-features/iterative-outputs). Of course, in practice, you would replace `bot()` with your own more complex function, which might call a pretrained model or an API, to generate a response.
Add Streaming to your Chatbot
https://gradio.app/guides/creating-a-custom-chatbot-with-blocks
Chatbots - Creating A Custom Chatbot With Blocks Guide
The `gr.Chatbot` component supports a subset of markdown including bold, italics, and code. For example, we could write a function that responds to a user's message, with a bold **That's cool!**, like this: ```py def bot(history): response = {"role": "assistant", "content": "**That's cool!**"} history.append(response) return history ``` In addition, it can handle media files, such as images, audio, and video. You can use the `MultimodalTextbox` component to easily upload all types of media files to your chatbot. You can customize the `MultimodalTextbox` further by passing in the `sources` parameter, which is a list of sources to enable. To pass in a media file, we must pass in the file a dictionary with a `path` key pointing to a local file and an `alt_text` key. The `alt_text` is optional, so you can also just pass in a tuple with a single element `{"path": "filepath"}`, like this: ```python def add_message(history, message): for x in message["files"]: history.append({"role": "user", "content": {"path": x}}) if message["text"] is not None: history.append({"role": "user", "content": message["text"]}) return history, gr.MultimodalTextbox(value=None, interactive=False, file_types=["image"], sources=["upload", "microphone"]) ``` Putting this together, we can create a _multimodal_ chatbot with a multimodal textbox for a user to submit text and media files. The rest of the code looks pretty much the same as before: $code_chatbot_multimodal $demo_chatbot_multimodal And you're done! That's all the code you need to build an interface for your chatbot model. Finally, we'll end our Guide with some links to Chatbots that are running on Spaces so that you can get an idea of what else is possible: - [project-baize/Baize-7B](https://huggingface.co/spaces/project-baize/Baize-7B): A stylized chatbot that allows you to stop generation as well as regenerate responses. - [MAGAer13/mPLUG-Owl](https://huggingface.co/spaces/MAGAer13/mPLUG-Ow
Adding Markdown, Images, Audio, or Videos
https://gradio.app/guides/creating-a-custom-chatbot-with-blocks
Chatbots - Creating A Custom Chatbot With Blocks Guide
ingface.co/spaces/project-baize/Baize-7B): A stylized chatbot that allows you to stop generation as well as regenerate responses. - [MAGAer13/mPLUG-Owl](https://huggingface.co/spaces/MAGAer13/mPLUG-Owl): A multimodal chatbot that allows you to upvote and downvote responses.
Adding Markdown, Images, Audio, or Videos
https://gradio.app/guides/creating-a-custom-chatbot-with-blocks
Chatbots - Creating A Custom Chatbot With Blocks Guide
The chat widget appears as a small button in the corner of your website. When clicked, it opens a chat interface that communicates with your Gradio app via the JavaScript Client API. Users can ask questions and receive responses directly within the widget.
How does it work?
https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot
Chatbots - Creating A Website Widget From A Gradio Chatbot Guide
* A running Gradio app (local or on Hugging Face Spaces). In this example, we'll use the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which helps generate code for Gradio apps based on natural language descriptions. 1. Create and Style the Chat Widget First, add this HTML and CSS to your website: ```html <div id="chat-widget" class="chat-widget"> <button id="chat-toggle" class="chat-toggle">💬</button> <div id="chat-container" class="chat-container hidden"> <div id="chat-header"> <h3>Gradio Assistant</h3> <button id="close-chat">×</button> </div> <div id="chat-messages"></div> <div id="chat-input-area"> <input type="text" id="chat-input" placeholder="Ask a question..."> <button id="send-message">Send</button> </div> </div> </div> <style> .chat-widget { position: fixed; bottom: 20px; right: 20px; z-index: 1000; } .chat-toggle { width: 50px; height: 50px; border-radius: 50%; background: 007bff; border: none; color: white; font-size: 24px; cursor: pointer; } .chat-container { position: fixed; bottom: 80px; right: 20px; width: 300px; height: 400px; background: white; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); display: flex; flex-direction: column; } .chat-container.hidden { display: none; } chat-header { padding: 10px; background: 007bff; color: white; border-radius: 10px 10px 0 0; display: flex; justify-content: space-between; align-items: center; } chat-messages { flex-grow: 1; overflow-y: auto; padding: 10px; } chat-input-area { padding: 10px; border-top: 1px solid eee; display: flex; } chat-input { flex-grow: 1; padding: 8px; border: 1px solid ddd; border-radius: 4px; margin-right: 8px; } .message { margin: 8px 0; pad
Prerequisites
https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot
Chatbots - Creating A Website Widget From A Gradio Chatbot Guide
solid eee; display: flex; } chat-input { flex-grow: 1; padding: 8px; border: 1px solid ddd; border-radius: 4px; margin-right: 8px; } .message { margin: 8px 0; padding: 8px; border-radius: 4px; } .user-message { background: e9ecef; margin-left: 20px; } .bot-message { background: f8f9fa; margin-right: 20px; } </style> ``` 2. Add the JavaScript Then, add the following JavaScript code (which uses the Gradio JavaScript Client to connect to the Space) to your website by including this in the `<head>` section of your website: ```html <script type="module"> import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client/dist/index.min.js"; async function initChatWidget() { const client = await Client.connect("https://abidlabs-gradio-playground-bot.hf.space"); const chatToggle = document.getElementById('chat-toggle'); const chatContainer = document.getElementById('chat-container'); const closeChat = document.getElementById('close-chat'); const chatInput = document.getElementById('chat-input'); const sendButton = document.getElementById('send-message'); const messagesContainer = document.getElementById('chat-messages'); chatToggle.addEventListener('click', () => { chatContainer.classList.remove('hidden'); }); closeChat.addEventListener('click', () => { chatContainer.classList.add('hidden'); }); async function sendMessage() { const userMessage = chatInput.value.trim(); if (!userMessage) return; appendMessage(userMessage, 'user'); chatInput.value = ''; try { const result = await client.predict("/chat", { message: {"text": userMessage, "files": []} }); const message = result.data[0]; console.log(result.data[0]
Prerequisites
https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot
Chatbots - Creating A Website Widget From A Gradio Chatbot Guide
client.predict("/chat", { message: {"text": userMessage, "files": []} }); const message = result.data[0]; console.log(result.data[0]); const botMessage = result.data[0].join('\n'); appendMessage(botMessage, 'bot'); } catch (error) { console.error('Error:', error); appendMessage('Sorry, there was an error processing your request.', 'bot'); } } function appendMessage(text, sender) { const messageDiv = document.createElement('div'); messageDiv.className = `message ${sender}-message`; if (sender === 'bot') { messageDiv.innerHTML = marked.parse(text); } else { messageDiv.textContent = text; } messagesContainer.appendChild(messageDiv); messagesContainer.scrollTop = messagesContainer.scrollHeight; } sendButton.addEventListener('click', sendMessage); chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') sendMessage(); }); } initChatWidget(); </script> ``` 3. That's it! Your website now has a chat widget that connects to your Gradio app! Users can click the chat button to open the widget and start interacting with your app. Customization You can customize the appearance of the widget by modifying the CSS. Some ideas: - Change the colors to match your website's theme - Adjust the size and position of the widget - Add animations for opening/closing - Modify the message styling ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.32.46%E2%80%AFPM.gif) If you build a website widget from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are hap
Prerequisites
https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot
Chatbots - Creating A Website Widget From A Gradio Chatbot Guide
%20Recording%202024-12-19%20at%203.32.46%E2%80%AFPM.gif) If you build a website widget from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!
Prerequisites
https://gradio.app/guides/creating-a-website-widget-from-a-gradio-chatbot
Chatbots - Creating A Website Widget From A Gradio Chatbot Guide
The Discord bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API. Because Gradio's API is very flexible, you can create Discord bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-18%20at%204.26.55%E2%80%AFPM.gif)
How does it work?
https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app
Chatbots - Creating A Discord Bot From A Gradio App Guide
* Install the latest version of `gradio` and the `discord.py` libraries: ``` pip install --upgrade gradio discord.py~=2.0 ``` * Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app. Now, we are ready to get started! 1. Create a Discord application First, go to the [Discord apps dashboard](https://discord.com/developers/applications). Look for the "New Application" button and click it. Give your application a name, and then click "Create". ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-4.png) On the resulting screen, you will see basic information about your application. Under the Settings section, click on the "Bot" option. You can update your bot's username if you would like. Then click on the "Reset Token" button. A new token will be generated. Copy it as we will need it for the next step. Scroll down to the section that says "Privileged Gateway Intents". Your bot will need certain permissions to work correctly. In this tutorial, we will only be using the "Message Content Intent" so click the toggle to enable this intent. Save the changes. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-3.png) 2. Write a Discord bot Let's start by writing a very simple Discord bot, just to make sure that everything is working. Write the following Python code in a file called `bot.py`, pasting the discord bot token from the previous step: ```python bot.py import discord TOKEN = PASTE YOUR DISCORD BOT TOKEN HERE client = discord.Client() @client.event async def on_ready(): print(f'{client.user} has connected to Discord!') client.run(TOKEN) ``` Now, run this file: `python bot.py`, w
Prerequisites
https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app
Chatbots - Creating A Discord Bot From A Gradio App Guide
CORD BOT TOKEN HERE client = discord.Client() @client.event async def on_ready(): print(f'{client.user} has connected to Discord!') client.run(TOKEN) ``` Now, run this file: `python bot.py`, which should run and print a message like: ```text We have logged in as GradioPlaygroundBot1451 ``` If that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file: ```python import discord from gradio_client import Client, handle_file import httpx import os TOKEN = PASTE YOUR DISCORD BOT TOKEN HERE intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) gradio_client = Client("abidlabs/gradio-playground-bot") def download_image(attachment): response = httpx.get(attachment.url) image_path = f"./images/{attachment.filename}" os.makedirs("./images", exist_ok=True) with open(image_path, "wb") as f: f.write(response.content) return image_path @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): Ignore messages from the bot itself if message.author == client.user: return Check if the bot is mentioned in the message and reply if client.user in message.mentions: Extract the message content without the bot mention clean_message = message.content.replace(f"<@{client.user.id}>", "").strip() Handle images (only the first image is used) files = [] if message.attachments: for attachment in message.attachments: if any(attachment.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']): image_path = download_image(attachment) files.append(handle_file(image_path))
Prerequisites
https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app
Chatbots - Creating A Discord Bot From A Gradio App Guide
.filename.lower().endswith(ext) for ext in ['png', 'jpg', 'jpeg', 'gif', 'webp']): image_path = download_image(attachment) files.append(handle_file(image_path)) break Stream the responses to the channel for response in gradio_client.submit( message={"text": clean_message, "files": files}, ): await message.channel.send(response[-1]) client.run(TOKEN) ``` 3. Add the bot to your Discord Server Now we are ready to install the bot on our server. Go back to the [Discord apps dashboard](https://discord.com/developers/applications). Under the Settings section, click on the "OAuth2" option. Scroll down to the "OAuth2 URL Generator" box and select the "bot" checkbox: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-2.png) Then in "Bot Permissions" box that pops up underneath, enable the following permissions: ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/discord-1.png) Copy the generated URL that appears underneath, which should look something like: ```text https://discord.com/oauth2/authorize?client_id=1319011745452265575&permissions=377957238784&integration_type=0&scope=bot ``` Paste it into your browser, which should allow you to add the Discord bot to any Discord server that you manage. 4. That's it! Now you can mention your bot from any channel in your Discord server, optionally attach an image, and it will respond with generated Gradio app code! The bot will: 1. Listen for mentions 2. Process any attached images 3. Send the text and images to your Gradio app 4. Stream the responses back to the Discord channel This is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/
Prerequisites
https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app
Chatbots - Creating A Discord Bot From A Gradio App Guide
c example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-18%20at%204.26.55%E2%80%AFPM.gif) If you build a Discord bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!
Prerequisites
https://gradio.app/guides/creating-a-discord-bot-from-a-gradio-app
Chatbots - Creating A Discord Bot From A Gradio App Guide
The Slack bot will listen to messages mentioning it in channels. When it receives a message (which can include text as well as files), it will send it to your Gradio app via Gradio's built-in API. Your bot will reply with the response it receives from the API. Because Gradio's API is very flexible, you can create Slack bots that support text, images, audio, streaming, chat history, and a wide variety of other features very easily. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif)
How does it work?
https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app
Chatbots - Creating A Slack Bot From A Gradio App Guide
* Install the latest version of `gradio` and the `slack-bolt` library: ```bash pip install --upgrade gradio slack-bolt~=1.0 ``` * Have a running Gradio app. This app can be running locally or on Hugging Face Spaces. In this example, we will be using the [Gradio Playground Space](https://huggingface.co/spaces/abidlabs/gradio-playground-bot), which takes in an image and/or text and generates the code to generate the corresponding Gradio app. Now, we are ready to get started! 1. Create a Slack App 1. Go to [api.slack.com/apps](https://api.slack.com/apps) and click "Create New App" 2. Choose "From scratch" and give your app a name 3. Select the workspace where you want to develop your app 4. Under "OAuth & Permissions", scroll to "Scopes" and add these Bot Token Scopes: - `app_mentions:read` - `chat:write` - `files:read` - `files:write` 5. In the same "OAuth & Permissions" page, scroll back up and click the button to install the app to your workspace. 6. Note the "Bot User OAuth Token" (starts with `xoxb-`) that appears as we'll need it later 7. Click on "Socket Mode" in the menu bar. When the page loads, click the toggle to "Enable Socket Mode" 8. Give your token a name, such as `socket-token` and copy the token that is generated (starts with `xapp-`) as we'll need it later. 9. Finally, go to the "Event Subscription" option in the menu bar. Click the toggle to "Enable Events" and subscribe to the `app_mention` bot event. 2. Write a Slack bot Let's start by writing a very simple Slack bot, just to make sure that everything is working. Write the following Python code in a file called `bot.py`, pasting the two tokens from step 6 and step 8 in the previous section. ```py from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE app = App(token=SLACK_BOT_TOKEN) @app.event("app_mention") def handle_app_mention_ev
Prerequisites
https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app
Chatbots - Creating A Slack Bot From A Gradio App Guide
eHandler SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE app = App(token=SLACK_BOT_TOKEN) @app.event("app_mention") def handle_app_mention_events(body, say): user_id = body["event"]["user"] say(f"Hi <@{user_id}>! You mentioned me and said: {body['event']['text']}") if __name__ == "__main__": handler = SocketModeHandler(app, SLACK_APP_TOKEN) handler.start() ``` If that is working, we are ready to add Gradio-specific code. We will be using the [Gradio Python Client](https://www.gradio.app/guides/getting-started-with-the-python-client) to query the Gradio Playground Space mentioned above. Here's the updated `bot.py` file: ```python from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler SLACK_BOT_TOKEN = PASTE YOUR SLACK BOT TOKEN HERE SLACK_APP_TOKEN = PASTE YOUR SLACK APP TOKEN HERE app = App(token=SLACK_BOT_TOKEN) gradio_client = Client("abidlabs/gradio-playground-bot") def download_image(url, filename): headers = {"Authorization": f"Bearer {SLACK_BOT_TOKEN}"} response = httpx.get(url, headers=headers) image_path = f"./images/{filename}" os.makedirs("./images", exist_ok=True) with open(image_path, "wb") as f: f.write(response.content) return image_path def slackify_message(message): Replace markdown links with slack format and remove code language specifier after triple backticks pattern = r'\[(.*?)\]\((.*?)\)' cleaned = re.sub(pattern, r'<\2|\1>', message) cleaned = re.sub(r'```\w+\n', '```', cleaned) return cleaned.strip() @app.event("app_mention") def handle_app_mention_events(body, say): Extract the message content without the bot mention text = body["event"]["text"] bot_user_id = body["authorizations"][0]["user_id"] clean_message = text.replace(f"<@{bot_user_id}>", "").strip() Handle images if present files = [] if "files" in body["event"]: for
Prerequisites
https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app
Chatbots - Creating A Slack Bot From A Gradio App Guide
= body["authorizations"][0]["user_id"] clean_message = text.replace(f"<@{bot_user_id}>", "").strip() Handle images if present files = [] if "files" in body["event"]: for file in body["event"]["files"]: if file["filetype"] in ["png", "jpg", "jpeg", "gif", "webp"]: image_path = download_image(file["url_private_download"], file["name"]) files.append(handle_file(image_path)) break Submit to Gradio and send responses back to Slack for response in gradio_client.submit( message={"text": clean_message, "files": files}, ): cleaned_response = slackify_message(response[-1]) say(cleaned_response) if __name__ == "__main__": handler = SocketModeHandler(app, SLACK_APP_TOKEN) handler.start() ``` 3. Add the bot to your Slack Workplace Now, create a new channel or navigate to an existing channel in your Slack workspace where you want to use the bot. Click the "+" button next to "Channels" in your Slack sidebar and follow the prompts to create a new channel. Finally, invite your bot to the channel: 1. In your new channel, type `/invite @YourBotName` 2. Select your bot from the dropdown 3. Click "Invite to Channel" 4. That's it! Now you can mention your bot in any channel it's in, optionally attach an image, and it will respond with generated Gradio app code! The bot will: 1. Listen for mentions 2. Process any attached images 3. Send the text and images to your Gradio app 4. Stream the responses back to the Slack channel This is just a basic example - you can extend it to handle more types of files, add error handling, or integrate with different Gradio apps! ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif) If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gr
Prerequisites
https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app
Chatbots - Creating A Slack Bot From A Gradio App Guide
/main/gradio-guides/Screen%20Recording%202024-12-19%20at%203.30.00%E2%80%AFPM.gif) If you build a Slack bot from a Gradio app, feel free to share it on X and tag [the Gradio account](https://x.com/Gradio), and we are happy to help you amplify!
Prerequisites
https://gradio.app/guides/creating-a-slack-bot-from-a-gradio-app
Chatbots - Creating A Slack Bot From A Gradio App Guide
Each message in Gradio's chatbot is a dataclass of type `ChatMessage` (this is assuming that chatbot's `type="message"`, which is strongly recommended). The schema of `ChatMessage` is as follows: ```py @dataclass class ChatMessage: content: str | Component role: Literal["user", "assistant"] metadata: MetadataDict = None options: list[OptionDict] = None class MetadataDict(TypedDict): title: NotRequired[str] id: NotRequired[int | str] parent_id: NotRequired[int | str] log: NotRequired[str] duration: NotRequired[float] status: NotRequired[Literal["pending", "done"]] class OptionDict(TypedDict): label: NotRequired[str] value: str ``` For our purposes, the most important key is the `metadata` key, which accepts a dictionary. If this dictionary includes a `title` for the message, it will be displayed in a collapsible accordion representing a thought. It's that simple! Take a look at this example: ```python import gradio as gr with gr.Blocks() as demo: chatbot = gr.Chatbot( type="messages", value=[ gr.ChatMessage( role="user", content="What is the weather in San Francisco?" ), gr.ChatMessage( role="assistant", content="I need to use the weather API tool?", metadata={"title": "🧠 Thinking"} ] ) demo.launch() ``` In addition to `title`, the dictionary provided to `metadata` can take several optional keys: * `log`: an optional string value to be displayed in a subdued font next to the thought title. * `duration`: an optional numeric value representing the duration of the thought/tool usage, in seconds. Displayed in a subdued font next inside parentheses next to the thought title. * `status`: if set to `"pending"`, a spinner appears next to the thought title and the accordion is initialized open. If `status` is `"done"`, the thought accordion is initialized closed. I
The `ChatMessage` dataclass
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
ht title. * `status`: if set to `"pending"`, a spinner appears next to the thought title and the accordion is initialized open. If `status` is `"done"`, the thought accordion is initialized closed. If `status` is not provided, the thought accordion is initialized open and no spinner is displayed. * `id` and `parent_id`: if these are provided, they can be used to nest thoughts inside other thoughts. Below, we show several complete examples of using `gr.Chatbot` and `gr.ChatInterface` to display tool use or thinking UIs.
The `ChatMessage` dataclass
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
A real example using transformers.agents We'll create a Gradio application simple agent that has access to a text-to-image tool. Tip: Make sure you read the [smolagents documentation](https://huggingface.co/docs/smolagents/index) first We'll start by importing the necessary classes from transformers and gradio. ```python import gradio as gr from gradio import ChatMessage from transformers import Tool, ReactCodeAgent type: ignore from transformers.agents import stream_to_gradio, HfApiEngine type: ignore Import tool from Hub image_generation_tool = Tool.from_space( space_id="black-forest-labs/FLUX.1-schnell", name="image_generator", description="Generates an image following your prompt. Returns a PIL Image.", api_name="/infer", ) llm_engine = HfApiEngine("Qwen/Qwen2.5-Coder-32B-Instruct") Initialize the agent with both tools and engine agent = ReactCodeAgent(tools=[image_generation_tool], llm_engine=llm_engine) ``` Then we'll build the UI: ```python def interact_with_agent(prompt, history): messages = [] yield messages for msg in stream_to_gradio(agent, prompt): messages.append(asdict(msg)) yield messages yield messages demo = gr.ChatInterface( interact_with_agent, chatbot= gr.Chatbot( label="Agent", type="messages", avatar_images=( None, "https://em-content.zobj.net/source/twitter/53/robot-face_1f916.png", ), ), examples=[ ["Generate an image of an astronaut riding an alligator"], ["I am writing a children's book for my daughter. Can you help me with some illustrations?"], ], type="messages", ) ``` You can see the full demo code [here](https://huggingface.co/spaces/gradio/agent_chatbot/blob/main/app.py). ![transformers_agent_code](https://github.com/freddyaboulton/freddyboulton/assets/41651716/c8d21336-e0e6-4878-88ea-e6fcfef3552d) A real example using langchain agents We'll create a UI for l
Building with Agents
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
![transformers_agent_code](https://github.com/freddyaboulton/freddyboulton/assets/41651716/c8d21336-e0e6-4878-88ea-e6fcfef3552d) A real example using langchain agents We'll create a UI for langchain agent that has access to a search engine. We'll begin with imports and setting up the langchain agent. Note that you'll need an .env file with the following environment variables set - ``` SERPAPI_API_KEY= HF_TOKEN= OPENAI_API_KEY= ``` ```python from langchain import hub from langchain.agents import AgentExecutor, create_openai_tools_agent, load_tools from langchain_openai import ChatOpenAI from gradio import ChatMessage import gradio as gr from dotenv import load_dotenv load_dotenv() model = ChatOpenAI(temperature=0, streaming=True) tools = load_tools(["serpapi"]) Get the prompt to use - you can modify this! prompt = hub.pull("hwchase17/openai-tools-agent") agent = create_openai_tools_agent( model.with_config({"tags": ["agent_llm"]}), tools, prompt ) agent_executor = AgentExecutor(agent=agent, tools=tools).with_config( {"run_name": "Agent"} ) ``` Then we'll create the Gradio UI ```python async def interact_with_langchain_agent(prompt, messages): messages.append(ChatMessage(role="user", content=prompt)) yield messages async for chunk in agent_executor.astream( {"input": prompt} ): if "steps" in chunk: for step in chunk["steps"]: messages.append(ChatMessage(role="assistant", content=step.action.log, metadata={"title": f"🛠️ Used tool {step.action.tool}"})) yield messages if "output" in chunk: messages.append(ChatMessage(role="assistant", content=chunk["output"])) yield messages with gr.Blocks() as demo: gr.Markdown("Chat with a LangChain Agent 🦜⛓️ and see its thoughts 💭") chatbot = gr.Chatbot( type="messages", label="Agent", avatar_images=( None,
Building with Agents
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
gr.Markdown("Chat with a LangChain Agent 🦜⛓️ and see its thoughts 💭") chatbot = gr.Chatbot( type="messages", label="Agent", avatar_images=( None, "https://em-content.zobj.net/source/twitter/141/parrot_1f99c.png", ), ) input = gr.Textbox(lines=1, label="Chat Message") input.submit(interact_with_langchain_agent, [input_2, chatbot_2], [chatbot_2]) demo.launch() ``` ![langchain_agent_code](https://github.com/freddyaboulton/freddyboulton/assets/41651716/762283e5-3937-47e5-89e0-79657279ea67) That's it! See our finished langchain demo [here](https://huggingface.co/spaces/gradio/langchain-agent).
Building with Agents
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
The Gradio Chatbot can natively display intermediate thoughts of a _thinking_ LLM. This makes it perfect for creating UIs that show how an AI model "thinks" while generating responses. Below guide will show you how to build a chatbot that displays Gemini AI's thought process in real-time. A real example using Gemini 2.0 Flash Thinking API Let's create a complete chatbot that shows its thoughts and responses in real-time. We'll use Google's Gemini API for accessing Gemini 2.0 Flash Thinking LLM and Gradio for the UI. We'll begin with imports and setting up the gemini client. Note that you'll need to [acquire a Google Gemini API key](https://aistudio.google.com/apikey) first - ```python import gradio as gr from gradio import ChatMessage from typing import Iterator import google.generativeai as genai genai.configure(api_key="your-gemini-api-key") model = genai.GenerativeModel("gemini-2.0-flash-thinking-exp-1219") ``` First, let's set up our streaming function that handles the model's output: ```python def stream_gemini_response(user_message: str, messages: list) -> Iterator[list]: """ Streams both thoughts and responses from the Gemini model. """ Initialize response from Gemini response = model.generate_content(user_message, stream=True) Initialize buffers thought_buffer = "" response_buffer = "" thinking_complete = False Add initial thinking message messages.append( ChatMessage( role="assistant", content="", metadata={"title": "⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental"} ) ) for chunk in response: parts = chunk.candidates[0].content.parts current_chunk = parts[0].text if len(parts) == 2 and not thinking_complete: Complete thought and start response thought_buffer += current_chunk messages[-1] = ChatMessage( rol
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
if len(parts) == 2 and not thinking_complete: Complete thought and start response thought_buffer += current_chunk messages[-1] = ChatMessage( role="assistant", content=thought_buffer, metadata={"title": "⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental"} ) Add response message messages.append( ChatMessage( role="assistant", content=parts[1].text ) ) thinking_complete = True elif thinking_complete: Continue streaming response response_buffer += current_chunk messages[-1] = ChatMessage( role="assistant", content=response_buffer ) else: Continue streaming thoughts thought_buffer += current_chunk messages[-1] = ChatMessage( role="assistant", content=thought_buffer, metadata={"title": "⏳Thinking: *The thoughts produced by the Gemini2.0 Flash model are experimental"} ) yield messages ``` Then, let's create the Gradio interface: ```python with gr.Blocks() as demo: gr.Markdown("Chat with Gemini 2.0 Flash and See its Thoughts 💭") chatbot = gr.Chatbot( type="messages", label="Gemini2.0 'Thinking' Chatbot", render_markdown=True, ) input_box = gr.Textbox( lines=1, label="Chat Message", placeholder="Type your message here and press Enter..." ) Set up event handlers msg_store = gr.State("") Store for preserving user message input_box.submit( lambda msg: (msg, msg, ""), Store message and clear input inputs=[input_box], outputs=[msg_store, input_box, inp
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
Store for preserving user message input_box.submit( lambda msg: (msg, msg, ""), Store message and clear input inputs=[input_box], outputs=[msg_store, input_box, input_box], queue=False ).then( user_message, Add user message to chat inputs=[msg_store, chatbot], outputs=[input_box, chatbot], queue=False ).then( stream_gemini_response, Generate and stream response inputs=[msg_store, chatbot], outputs=chatbot ) demo.launch() ``` This creates a chatbot that: - Displays the model's thoughts in a collapsible section - Streams the thoughts and final response in real-time - Maintains a clean chat history That's it! You now have a chatbot that not only responds to users but also shows its thinking process, creating a more transparent and engaging interaction. See our finished Gemini 2.0 Flash Thinking demo [here](https://huggingface.co/spaces/ysharma/Gemini2-Flash-Thinking). Building with Citations The Gradio Chatbot can display citations from LLM responses, making it perfect for creating UIs that show source documentation and references. This guide will show you how to build a chatbot that displays Claude's citations in real-time. A real example using Anthropic's Citations API Let's create a complete chatbot that shows both responses and their supporting citations. We'll use Anthropic's Claude API with citations enabled and Gradio for the UI. We'll begin with imports and setting up the Anthropic client. Note that you'll need an `ANTHROPIC_API_KEY` environment variable set: ```python import gradio as gr import anthropic import base64 from typing import List, Dict, Any client = anthropic.Anthropic() ``` First, let's set up our message formatting functions that handle document preparation: ```python def encode_pdf_to_base64(file_obj) -> str: """Convert uploaded PDF file to base64 string.""" if file_obj is None: return None
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
ng functions that handle document preparation: ```python def encode_pdf_to_base64(file_obj) -> str: """Convert uploaded PDF file to base64 string.""" if file_obj is None: return None with open(file_obj.name, 'rb') as f: return base64.b64encode(f.read()).decode('utf-8') def format_message_history( history: list, enable_citations: bool, doc_type: str, text_input: str, pdf_file: str ) -> List[Dict]: """Convert Gradio chat history to Anthropic message format.""" formatted_messages = [] Add previous messages for msg in history[:-1]: if msg["role"] == "user": formatted_messages.append({"role": "user", "content": msg["content"]}) Prepare the latest message with document latest_message = {"role": "user", "content": []} if enable_citations: if doc_type == "plain_text": latest_message["content"].append({ "type": "document", "source": { "type": "text", "media_type": "text/plain", "data": text_input.strip() }, "title": "Text Document", "citations": {"enabled": True} }) elif doc_type == "pdf" and pdf_file: pdf_data = encode_pdf_to_base64(pdf_file) if pdf_data: latest_message["content"].append({ "type": "document", "source": { "type": "base64", "media_type": "application/pdf", "data": pdf_data }, "title": pdf_file.name, "citations": {"enabled": True} }) Add the user's question latest_message["content"].append({"type": "text", "text": history[-1]["content"]}) formatted_messages.append(latest_message) return formatted_messages ``` Then,
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
the user's question latest_message["content"].append({"type": "text", "text": history[-1]["content"]}) formatted_messages.append(latest_message) return formatted_messages ``` Then, let's create our bot response handler that processes citations: ```python def bot_response( history: list, enable_citations: bool, doc_type: str, text_input: str, pdf_file: str ) -> List[Dict[str, Any]]: try: messages = format_message_history(history, enable_citations, doc_type, text_input, pdf_file) response = client.messages.create(model="claude-3-5-sonnet-20241022", max_tokens=1024, messages=messages) Initialize main response and citations main_response = "" citations = [] Process each content block for block in response.content: if block.type == "text": main_response += block.text if enable_citations and hasattr(block, 'citations') and block.citations: for citation in block.citations: if citation.cited_text not in citations: citations.append(citation.cited_text) Add main response history.append({"role": "assistant", "content": main_response}) Add citations in a collapsible section if enable_citations and citations: history.append({ "role": "assistant", "content": "\n".join([f"• {cite}" for cite in citations]), "metadata": {"title": "📚 Citations"} }) return history except Exception as e: history.append({ "role": "assistant", "content": "I apologize, but I encountered an error while processing your request." }) return history ``` Finally, let's create the Gradio interface: ```python with gr.Blocks() as demo: gr.Markdown("Chat with Citations"
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
an error while processing your request." }) return history ``` Finally, let's create the Gradio interface: ```python with gr.Blocks() as demo: gr.Markdown("Chat with Citations") with gr.Row(scale=1): with gr.Column(scale=4): chatbot = gr.Chatbot(type="messages", bubble_full_width=False, show_label=False, scale=1) msg = gr.Textbox(placeholder="Enter your message here...", show_label=False, container=False) with gr.Column(scale=1): enable_citations = gr.Checkbox(label="Enable Citations", value=True, info="Toggle citation functionality" ) doc_type_radio = gr.Radio( choices=["plain_text", "pdf"], value="plain_text", label="Document Type", info="Choose the type of document to use") text_input = gr.Textbox(label="Document Content", lines=10, info="Enter the text you want to reference") pdf_input = gr.File(label="Upload PDF", file_types=[".pdf"], file_count="single", visible=False) Handle message submission msg.submit( user_message, [msg, chatbot, enable_citations, doc_type_radio, text_input, pdf_input], [msg, chatbot] ).then( bot_response, [chatbot, enable_citations, doc_type_radio, text_input, pdf_input], chatbot ) demo.launch() ``` This creates a chatbot that: - Supports both plain text and PDF documents for Claude to cite from - Displays Citations in collapsible sections using our `metadata` feature - Shows source quotes directly from the given documents The citations feature works particularly well with the Gradio Chatbot's `metadata` support, allowing us to create collapsible sections that keep the chat interface clean while still providing easy access to source documentation. That's it! You now have a chatbot that not only responds to users but also shows its sources, creating a more transparent and trustworthy interaction. See our finished Citations demo [her
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
umentation. That's it! You now have a chatbot that not only responds to users but also shows its sources, creating a more transparent and trustworthy interaction. See our finished Citations demo [here](https://huggingface.co/spaces/ysharma/anthropic-citations-with-gradio-metadata-key).
Building with Visibly Thinking LLMs
https://gradio.app/guides/agents-and-tool-usage
Chatbots - Agents And Tool Usage Guide
Chatbots are a popular application of large language models (LLMs). Using Gradio, you can easily build a chat application and share that with your users, or try it yourself using an intuitive UI. This tutorial uses `gr.ChatInterface()`, which is a high-level abstraction that allows you to create your chatbot UI fast, often with a _few lines of Python_. It can be easily adapted to support multimodal chatbots, or chatbots that require further customization. **Prerequisites**: please make sure you are using the latest version of Gradio: ```bash $ pip install --upgrade gradio ```
Introduction
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
If you have a chat server serving an OpenAI-API compatible endpoint (such as Ollama), you can spin up a ChatInterface in a single line of Python. First, also run `pip install openai`. Then, with your own URL, model, and optional token: ```python import gradio as gr gr.load_chat("http://localhost:11434/v1/", model="llama3.2", token="***").launch() ``` Read about `gr.load_chat` in [the docs](https://www.gradio.app/docs/gradio/load_chat). If you have your own model, keep reading to see how to create an application around any chat model in Python!
Note for OpenAI-API compatible endpoints
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
To create a chat application with `gr.ChatInterface()`, the first thing you should do is define your **chat function**. In the simplest case, your chat function should accept two arguments: `message` and `history` (the arguments can be named anything, but must be in this order). - `message`: a `str` representing the user's most recent message. - `history`: a list of openai-style dictionaries with `role` and `content` keys, representing the previous conversation history. May also include additional keys representing message metadata. For example, the `history` could look like this: ```python [ {"role": "user", "content": "What is the capital of France?"}, {"role": "assistant", "content": "Paris"} ] ``` while the next `message` would be: ```py "And what is its largest city?" ``` Your chat function simply needs to return: * a `str` value, which is the chatbot's response based on the chat `history` and most recent `message`, for example, in this case: ``` Paris is also the largest city. ``` Let's take a look at a few example chat functions: **Example: a chatbot that randomly responds with yes or no** Let's write a chat function that responds `Yes` or `No` randomly. Here's our chat function: ```python import random def random_response(message, history): return random.choice(["Yes", "No"]) ``` Now, we can plug this into `gr.ChatInterface()` and call the `.launch()` method to create the web interface: ```python import gradio as gr gr.ChatInterface( fn=random_response, type="messages" ).launch() ``` Tip: Always set type="messages" in gr.ChatInterface. The default value (type="tuples") is deprecated and will be removed in a future version of Gradio. That's it! Here's our running demo, try it out: $demo_chatinterface_random_response **Example: a chatbot that alternates between agreeing and disagreeing** Of course, the previous example was very simplistic, it didn't take user input or the previous history into account! Here's another
Defining a chat function
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
ample: a chatbot that alternates between agreeing and disagreeing** Of course, the previous example was very simplistic, it didn't take user input or the previous history into account! Here's another simple example showing how to incorporate a user's input as well as the history. ```python import gradio as gr def alternatingly_agree(message, history): if len([h for h in history if h['role'] == "assistant"]) % 2 == 0: return f"Yes, I do think that: {message}" else: return "I don't think so" gr.ChatInterface( fn=alternatingly_agree, type="messages" ).launch() ``` We'll look at more realistic examples of chat functions in our next Guide, which shows [examples of using `gr.ChatInterface` with popular LLMs](../guides/chatinterface-examples).
Defining a chat function
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
In your chat function, you can use `yield` to generate a sequence of partial responses, each replacing the previous ones. This way, you'll end up with a streaming chatbot. It's that simple! ```python import time import gradio as gr def slow_echo(message, history): for i in range(len(message)): time.sleep(0.3) yield "You typed: " + message[: i+1] gr.ChatInterface( fn=slow_echo, type="messages" ).launch() ``` While the response is streaming, the "Submit" button turns into a "Stop" button that can be used to stop the generator function. Tip: Even though you are yielding the latest message at each iteration, Gradio only sends the "diff" of each message from the server to the frontend, which reduces latency and data consumption over your network.
Streaming chatbots
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
If you're familiar with Gradio's `gr.Interface` class, the `gr.ChatInterface` includes many of the same arguments that you can use to customize the look and feel of your Chatbot. For example, you can: - add a title and description above your chatbot using `title` and `description` arguments. - add a theme or custom css using `theme` and `css` arguments respectively. - add `examples` and even enable `cache_examples`, which make your Chatbot easier for users to try it out. - customize the chatbot (e.g. to change the height or add a placeholder) or textbox (e.g. to add a max number of characters or add a placeholder). **Adding examples** You can add preset examples to your `gr.ChatInterface` with the `examples` parameter, which takes a list of string examples. Any examples will appear as "buttons" within the Chatbot before any messages are sent. If you'd like to include images or other files as part of your examples, you can do so by using this dictionary format for each example instead of a string: `{"text": "What's in this image?", "files": ["cheetah.jpg"]}`. Each file will be a separate message that is added to your Chatbot history. You can change the displayed text for each example by using the `example_labels` argument. You can add icons to each example as well using the `example_icons` argument. Both of these arguments take a list of strings, which should be the same length as the `examples` list. If you'd like to cache the examples so that they are pre-computed and the results appear instantly, set `cache_examples=True`. **Customizing the chatbot or textbox component** If you want to customize the `gr.Chatbot` or `gr.Textbox` that compose the `ChatInterface`, then you can pass in your own chatbot or textbox components. Here's an example of how we to apply the parameters we've discussed in this section: ```python import gradio as gr def yes_man(message, history): if message.endswith("?"): return "Yes" else: return "Ask me anything
Customizing the Chat UI
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
parameters we've discussed in this section: ```python import gradio as gr def yes_man(message, history): if message.endswith("?"): return "Yes" else: return "Ask me anything!" gr.ChatInterface( yes_man, type="messages", chatbot=gr.Chatbot(height=300), textbox=gr.Textbox(placeholder="Ask me a yes or no question", container=False, scale=7), title="Yes Man", description="Ask Yes Man any question", theme="ocean", examples=["Hello", "Am I cool?", "Are tomatoes vegetables?"], cache_examples=True, ).launch() ``` Here's another example that adds a "placeholder" for your chat interface, which appears before the user has started chatting. The `placeholder` argument of `gr.Chatbot` accepts Markdown or HTML: ```python gr.ChatInterface( yes_man, type="messages", chatbot=gr.Chatbot(placeholder="<strong>Your Personal Yes-Man</strong><br>Ask Me Anything"), ... ``` The placeholder appears vertically and horizontally centered in the chatbot.
Customizing the Chat UI
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
You may want to add multimodal capabilities to your chat interface. For example, you may want users to be able to upload images or files to your chatbot and ask questions about them. You can make your chatbot "multimodal" by passing in a single parameter (`multimodal=True`) to the `gr.ChatInterface` class. When `multimodal=True`, the signature of your chat function changes slightly: the first parameter of your function (what we referred to as `message` above) should accept a dictionary consisting of the submitted text and uploaded files that looks like this: ```py { "text": "user input", "files": [ "updated_file_1_path.ext", "updated_file_2_path.ext", ... ] } ``` This second parameter of your chat function, `history`, will be in the same openai-style dictionary format as before. However, if the history contains uploaded files, the `content` key for a file will be not a string, but rather a single-element tuple consisting of the filepath. Each file will be a separate message in the history. So after uploading two files and asking a question, your history might look like this: ```python [ {"role": "user", "content": ("cat1.png")}, {"role": "user", "content": ("cat2.png")}, {"role": "user", "content": "What's the difference between these two images?"}, ] ``` The return type of your chat function does *not change* when setting `multimodal=True` (i.e. in the simplest case, you should still return a string value). We discuss more complex cases, e.g. returning files [below](returning-complex-responses). If you are customizing a multimodal chat interface, you should pass in an instance of `gr.MultimodalTextbox` to the `textbox` parameter. You can customize the `MultimodalTextbox` further by passing in the `sources` parameter, which is a list of sources to enable. Here's an example that illustrates how to set up and customize and multimodal chat interface: ```python import gradio as gr def count_images(message, hi
Multimodal Chat Interface
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
eter, which is a list of sources to enable. Here's an example that illustrates how to set up and customize and multimodal chat interface: ```python import gradio as gr def count_images(message, history): num_images = len(message["files"]) total_images = 0 for message in history: if isinstance(message["content"], tuple): total_images += 1 return f"You just uploaded {num_images} images, total uploaded: {total_images+num_images}" demo = gr.ChatInterface( fn=count_images, type="messages", examples=[ {"text": "No files", "files": []} ], multimodal=True, textbox=gr.MultimodalTextbox(file_count="multiple", file_types=["image"], sources=["upload", "microphone"]) ) demo.launch() ```
Multimodal Chat Interface
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
You may want to add additional inputs to your chat function and expose them to your users through the chat UI. For example, you could add a textbox for a system prompt, or a slider that sets the number of tokens in the chatbot's response. The `gr.ChatInterface` class supports an `additional_inputs` parameter which can be used to add additional input components. The `additional_inputs` parameters accepts a component or a list of components. You can pass the component instances directly, or use their string shortcuts (e.g. `"textbox"` instead of `gr.Textbox()`). If you pass in component instances, and they have _not_ already been rendered, then the components will appear underneath the chatbot within a `gr.Accordion()`. Here's a complete example: $code_chatinterface_system_prompt If the components you pass into the `additional_inputs` have already been rendered in a parent `gr.Blocks()`, then they will _not_ be re-rendered in the accordion. This provides flexibility in deciding where to lay out the input components. In the example below, we position the `gr.Textbox()` on top of the Chatbot UI, while keeping the slider underneath. ```python import gradio as gr import time def echo(message, history, system_prompt, tokens): response = f"System prompt: {system_prompt}\n Message: {message}." for i in range(min(len(response), int(tokens))): time.sleep(0.05) yield response[: i+1] with gr.Blocks() as demo: system_prompt = gr.Textbox("You are helpful AI.", label="System Prompt") slider = gr.Slider(10, 100, render=False) gr.ChatInterface( echo, additional_inputs=[system_prompt, slider], type="messages" ) demo.launch() ``` **Examples with additional inputs** You can also add example values for your additional inputs. Pass in a list of lists to the `examples` parameter, where each inner list represents one sample, and each inner list should be `1 + len(additional_inputs)` long. The first element in the inner list should
Additional Inputs
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
n a list of lists to the `examples` parameter, where each inner list represents one sample, and each inner list should be `1 + len(additional_inputs)` long. The first element in the inner list should be the example value for the chat message, and each subsequent element should be an example value for one of the additional inputs, in order. When additional inputs are provided, examples are rendered in a table underneath the chat interface. If you need to create something even more custom, then its best to construct the chatbot UI using the low-level `gr.Blocks()` API. We have [a dedicated guide for that here](/guides/creating-a-custom-chatbot-with-blocks).
Additional Inputs
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
In the same way that you can accept additional inputs into your chat function, you can also return additional outputs. Simply pass in a list of components to the `additional_outputs` parameter in `gr.ChatInterface` and return additional values for each component from your chat function. Here's an example that extracts code and outputs it into a separate `gr.Code` component: $code_chatinterface_artifacts **Note:** unlike the case of additional inputs, the components passed in `additional_outputs` must be already defined in your `gr.Blocks` context -- they are not rendered automatically. If you need to render them after your `gr.ChatInterface`, you can set `render=False` when they are first defined and then `.render()` them in the appropriate section of your `gr.Blocks()` as we do in the example above.
Additional Outputs
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
We mentioned earlier that in the simplest case, your chat function should return a `str` response, which will be rendered as Markdown in the chatbot. However, you can also return more complex responses as we discuss below: **Returning files or Gradio components** Currently, the following Gradio components can be displayed inside the chat interface: * `gr.Image` * `gr.Plot` * `gr.Audio` * `gr.HTML` * `gr.Video` * `gr.Gallery` * `gr.File` Simply return one of these components from your function to use it with `gr.ChatInterface`. Here's an example that returns an audio file: ```py import gradio as gr def music(message, history): if message.strip(): return gr.Audio("https://github.com/gradio-app/gradio/raw/main/test/test_files/audio_sample.wav") else: return "Please provide the name of an artist" gr.ChatInterface( music, type="messages", textbox=gr.Textbox(placeholder="Which artist's music do you want to listen to?", scale=7), ).launch() ``` Similarly, you could return image files with `gr.Image`, video files with `gr.Video`, or arbitrary files with the `gr.File` component. **Returning Multiple Messages** You can return multiple assistant messages from your chat function simply by returning a `list` of messages, each of which is a valid chat type. This lets you, for example, send a message along with files, as in the following example: $code_chatinterface_echo_multimodal **Displaying intermediate thoughts or tool usage** The `gr.ChatInterface` class supports displaying intermediate thoughts or tool usage direct in the chatbot. ![](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/gradio-guides/nested-thought.png) To do this, you will need to return a `gr.ChatMessage` object from your chat function. Here is the schema of the `gr.ChatMessage` data class as well as two internal typed dictionaries: ```py @dataclass class ChatMessage: content: str | Component metadata: MetadataDict =
Returning Complex Responses
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
ion. Here is the schema of the `gr.ChatMessage` data class as well as two internal typed dictionaries: ```py @dataclass class ChatMessage: content: str | Component metadata: MetadataDict = None options: list[OptionDict] = None class MetadataDict(TypedDict): title: NotRequired[str] id: NotRequired[int | str] parent_id: NotRequired[int | str] log: NotRequired[str] duration: NotRequired[float] status: NotRequired[Literal["pending", "done"]] class OptionDict(TypedDict): label: NotRequired[str] value: str ``` As you can see, the `gr.ChatMessage` dataclass is similar to the openai-style message format, e.g. it has a "content" key that refers to the chat message content. But it also includes a "metadata" key whose value is a dictionary. If this dictionary includes a "title" key, the resulting message is displayed as an intermediate thought with the title being displayed on top of the thought. Here's an example showing the usage: $code_chatinterface_thoughts You can even show nested thoughts, which is useful for agent demos in which one tool may call other tools. To display nested thoughts, include "id" and "parent_id" keys in the "metadata" dictionary. Read our [dedicated guide on displaying intermediate thoughts and tool usage](/guides/agents-and-tool-usage) for more realistic examples. **Providing preset responses** When returning an assistant message, you may want to provide preset options that a user can choose in response. To do this, again, you will again return a `gr.ChatMessage` instance from your chat function. This time, make sure to set the `options` key specifying the preset responses. As shown in the schema for `gr.ChatMessage` above, the value corresponding to the `options` key should be a list of dictionaries, each with a `value` (a string that is the value that should be sent to the chat function when this response is clicked) and an optional `label` (if provided, is the text displayed as the preset r
Returning Complex Responses
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
ies, each with a `value` (a string that is the value that should be sent to the chat function when this response is clicked) and an optional `label` (if provided, is the text displayed as the preset response instead of the `value`). This example illustrates how to use preset responses: $code_chatinterface_options
Returning Complex Responses
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
You may wish to modify the value of the chatbot with your own events, other than those prebuilt in the `gr.ChatInterface`. For example, you could create a dropdown that prefills the chat history with certain conversations or add a separate button to clear the conversation history. The `gr.ChatInterface` supports these events, but you need to use the `gr.ChatInterface.chatbot_value` as the input or output component in such events. In this example, we use a `gr.Radio` component to prefill the the chatbot with certain conversations: $code_chatinterface_prefill
Modifying the Chatbot Value Directly
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
Once you've built your Gradio chat interface and are hosting it on [Hugging Face Spaces](https://hf.space) or somewhere else, then you can query it with a simple API at the `/chat` endpoint. The endpoint just expects the user's message and will return the response, internally keeping track of the message history. ![](https://github.com/gradio-app/gradio/assets/1778297/7b10d6db-6476-4e2e-bebd-ecda802c3b8f) To use the endpoint, you should use either the [Gradio Python Client](/guides/getting-started-with-the-python-client) or the [Gradio JS client](/guides/getting-started-with-the-js-client). Or, you can deploy your Chat Interface to other platforms, such as a: * Discord bot [[tutorial]](../guides/creating-a-discord-bot-from-a-gradio-app) * Slack bot [[tutorial]](../guides/creating-a-slack-bot-from-a-gradio-app) * Website widget [[tutorial]](../guides/creating-a-website-widget-from-a-gradio-chatbot)
Using Your Chatbot via API
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide
You can enable persistent chat history for your ChatInterface, allowing users to maintain multiple conversations and easily switch between them. When enabled, conversations are stored locally and privately in the user's browser using local storage. So if you deploy a ChatInterface e.g. on [Hugging Face Spaces](https://hf.space), each user will have their own separate chat history that won't interfere with other users' conversations. This means multiple users can interact with the same ChatInterface simultaneously while maintaining their own private conversation histories. To enable this feature, simply set `gr.ChatInterface(save_history=True)` (as shown in the example in the next section). Users will then see their previous conversations in a side panel and can continue any previous chat or start a new one.
Chat History
https://gradio.app/guides/creating-a-chatbot-fast
Chatbots - Creating A Chatbot Fast Guide