gradio API reference
156 public APIs from gradio (gradio-app/gradio) — 50 classes, 62 functions, 44 methods. Signatures extracted by static analysis of the actual source.
Repository: gradio-app/gradio
| Kind | Count |
|---|---|
| Classes | 50 |
| Functions | 62 |
| Methods | 44 |
API list
class
client.python.gradio_client.client.ClientThe main Client class for the Python client.
method
client.python.gradio_client.client.Client.view_api(all_endpoints:bool | None=None, print_info:bool=True, return_format:Literal['dict', 'str'] | None=None) -> dict | str | NonePrints the usage info for the API.
method
client.python.gradio_client.client.Job.cancel() -> boolCancels the job as best as possible.
method
client.python.gradio_client.client.Job.result(timeout:float | None=None) -> AnyReturn the result of the call that the future represents.
func
client.python.gradio_client.documentation.document_fn(fn:Callable, cls) -> tuple[str, list[dict], dict, str | None]Generates documentation for any function.
func
client.python.gradio_client.templates.discord_chat.on_message(message)Continue the chat
class
client.python.gradio_client.utils.InvalidAPIEndpointErrorRaised when the API endpoint is invalid.
class
client.python.gradio_client.utils.JobStatusThe job status.
class
client.python.gradio_client.utils.StatusStatus codes presented to client users.
method
client.python.gradio_client.utils.Status.ordering(status:Status) -> intOrder of messages.
class
client.python.gradio_client.utils.TooManyRequestsErrorRaised when the API returns a 429 status code.
func
client.python.gradio_client.utils.download_tmp_copy_of_file(url_path:str, token:str | None=None, dir:str | None=None) -> strKept for backwards compatibility for 3.x spaces.
func
client.python.gradio_client.utils.is_valid_url(possible_url:str) -> boolCheck if the given string is a valid URL.
func
client.python.gradio_client.utils.synchronize_async(func:Callable, *args, **kwargs) -> AnyRuns async functions in sync scopes.
func
gradio.analytics.analytics_enabled() -> boolReturns: True if analytics are enabled, False otherwise.
method
gradio.blocks.Block.get_block_class() -> strGets block's class name.
method
gradio.blocks.Block.get_block_name() -> strGets block's class name.
method
gradio.blocks.Block.recover_kwargs(props:dict[str, Any], additional_keys:list[str] | None=None)Recovers kwargs from a dict of props.
method
gradio.blocks.Block.render()Adds self into appropriate BlockContext
class
gradio.brotli_middleware.BrotliMiddlewareBrotli middleware public interface.
class
gradio.brotli_middleware.BrotliResponderBrotli Interface.
method
gradio.brotli_middleware.BrotliResponder.send_with_brotli(message:Message) -> NoneApply compression using brotli.
class
gradio.brotli_middleware.ModeBrotli available modes.
method
gradio.caching.Cache.clear() -> NoneClear all entries from the cache.
method
gradio.caching.Cache.get(key:Any) -> dict | NoneLook up a cache entry by key.
method
gradio.caching.Cache.keys() -> list[Any]Return all stored raw keys.
method
gradio.caching.Cache.set(key:Any, **data:Any) -> NoneStore arbitrary keyword data under a key.
class
gradio.caching.ProbeCacheContext manager for probe mode.
func
gradio.cli.commands.components._docs_utils.add_value(obj:dict, key:str, value:typing.Any)Adds a value to a dictionary.
func
gradio.cli.commands.components._docs_utils.format(code:str, type:str)Formats code using ruff.
func
gradio.cli.commands.components._docs_utils.format_none(value)Formats None and NonType values.
func
gradio.cli.commands.components._docs_utils.format_value(value)Formats a value.
func
gradio.cli.commands.components._docs_utils.get_param_name(param)Gets the name of a parameter.
func
gradio.cli.commands.components._docs_utils.get_return_docstring(docstring:str)Gets the docstring for a return value.
func
gradio.cli.commands.components._docs_utils.get_type_arguments(type_hint) -> tupleGets the type arguments for a type hint.
func
gradio.cli.commands.components._docs_utils.render_class_events(events:dict, name)Renders the events for a class.
class
gradio.components.api_component.ApiA generic component that holds any value.
class
gradio.components.base.ComponentA base class for defining methods that all input/output components should have.
method
gradio.components.base.Component.example_payload() -> AnyAn example input data for this component, e.g.
method
gradio.components.base.Component.example_value() -> AnyAn example output data for this component, e.g.
class
gradio.components.chatbot.OptionDictA typed dictionary to represent an option in a ChatMessage.
class
gradio.components.checkbox.CheckboxCreates a checkbox that can be set to `True` or `False`.
class
gradio.components.checkboxgroup.CheckboxGroupCreates a set of checkboxes.
method
gradio.components.code.Code.postprocess(value:str | None) -> None | strParameters: value: Expects a `str` of code.
class
gradio.components.dataset.DatasetCreates a gallery or table to display data samples.
class
gradio.components.datetime.DateTimeComponent to select a date and (optionally) a time.
method
gradio.components.datetime.DateTime.postprocess(value:float | datetime | str | None) -> str | NoneParameters: value: Expects a tuple pair of datetimes.
method
gradio.components.datetime.DateTime.preprocess(payload:str | None) -> str | float | datetime | NoneParameters: payload: the text entered in the textarea.
class
gradio.components.html.HTMLCreates a component with arbitrary HTML.
method
gradio.components.html.HTML.postprocess(value:str | None) -> str | NoneParameters: value: Expects a `str` consisting of valid HTML.
class
gradio.components.json_component.JSONUsed to display arbitrary JSON output prettily.
class
gradio.components.markdown.MarkdownUsed to render arbitrary Markdown output.
class
gradio.components.navbar.NavbarCreates a navigation bar component for multipage Gradio apps.
method
gradio.components.number.Number.preprocess(payload:float | None) -> float | int | NoneParameters: payload: the field value.
method
gradio.components.number.Number.round_to_precision(num:float | int, precision:int | None) -> float | intRound to a given precision.
method
gradio.components.plot.Plot.preprocess(payload:PlotData | None) -> PlotData | NoneParameters: payload: The data to display in the plot.
class
gradio.components.timer.TimerSpecial component that ticks at regular intervals when active.
method
gradio.components.video.Video.combine_stream(stream:list[bytes], desired_output_format:str | None=None, only_file=False) -> FileDataCombine video chunks into a single video file.
func
gradio.components.video.Video.seconds_to_vtt_timestamp(seconds:float) -> strConvert seconds to VTT timestamp format (HH:MM:SS.mmm)
method
gradio.data_classes.FileData.from_path(path:str) -> FileDataCreates a FileData object from a given file path.
method
gradio.data_classes.FileData.is_file_data(obj:Any) -> boolChecks if an object is a valid FileData instance.
class
gradio.exceptions.ErrorThis class allows you to pass custom error messages to the user.
class
gradio.exceptions.GradioVersionIncompatibleErrorRaised when loading a 3.x space with 4.0
class
gradio.exceptions.InvalidComponentErrorRaised when invalid components are used.
class
gradio.exceptions.TooManyRequestsErrorRaised when the Hugging Face API returns a 429 status code.
func
gradio.external_utils.resolve_schema_ref(schema:dict, spec:dict) -> dictResolve schema references in OpenAPI spec.
class
gradio.flagging.ChatCSVLoggerFlagging callback for chat conversations.
method
gradio.helpers.Examples.cache(example_id:int | None=None) -> NoneCaches examples so that their predictions can be shown immediately.
method
gradio.helpers.Examples.create() -> NoneCreates the Dataset component to hold the examples
method
gradio.helpers.Examples.load_from_cache(example_id:int) -> list[Any]Loads a particular cached example for the interface.
method
gradio.helpers.Progress.close(_tqdm)Removes iterable with given _tqdm.
func
gradio.helpers.update(elem_id:str | None=None, elem_classes:list[str] | str | None=None, visible:bool | Literal['hidden'] | None=None, **kwargs:Any) -> dict[str, Any]Updates a component's properties.
class
gradio.i18n.I18nHandles internationalization (i18n) for Gradio applications.
class
gradio.i18n.I18nDataA class that wraps a translation key with metadata.
method
gradio.i18n.I18nData.to_dict() -> dict[str, Any]Convert the I18nData object to a dictionary for serialization.
func
gradio.image_utils.add_watermark(base_img:np.ndarray | PIL.Image.Image | str | Path, watermark_option:WatermarkOptions) -> PIL.Image.ImageOverlays a watermark image on a base image.
func
gradio.image_utils.open_image(orig_img:np.ndarray | PIL.Image.Image | str | Path) -> PIL.Image.ImageProvided an array, PIL Image or filepath, return a PIL Image.
class
gradio.ipython_ext.CellIdTrackerDetermines the most recently run cell in the notebook.
class
gradio.layouts.tabs.TabTab (or its alias TabItem) is a layout element.
class
gradio.layouts.walkthrough.StepStep is a layout element.
class
gradio.mcp.GradioMCPServerA class for creating an MCP server around a Gradio app.
func
gradio.mcp.GradioMCPServer.call_tool(name:str, arguments:dict[str, Any]) -> self.types.CallToolResultCall a tool on the Gradio app.
method
gradio.mcp.GradioMCPServer.create_mcp_server() -> 'Server'Create an MCP server for the given Gradio Blocks app.
method
gradio.mcp.GradioMCPServer.get_base64_data(image:Image.Image, format:str) -> strReturns a base64 encoded string of the image.
method
gradio.mcp.GradioMCPServer.get_block_fn_from_endpoint_name(endpoint_name:str) -> 'BlockFunction | None'Get the BlockFunction for a given endpoint name (e.g.
method
gradio.mcp.GradioMCPServer.get_complete_schema(request) -> JSONResponseGet the complete schema of the Gradio app API.
method
gradio.mcp.GradioMCPServer.get_image(file_path:str) -> Image.Image | NoneIf a filepath is a valid image, returns a PIL Image object.
func
gradio.mcp.GradioMCPServer.get_prompt(name:str, arguments:dict[str, Any] | None=None) -> self.types.GetPromptResultGet a specific prompt with filled-in arguments.
method
gradio.mcp.GradioMCPServer.get_route_path(request:Request) -> strGets the route path of the MCP server based on the incoming request.
method
gradio.mcp.GradioMCPServer.launch_mcp_on_sse(app:Starlette, subpath:str, root_path:str) -> NoneLaunch the MCP server on the SSE transport.
func
gradio.mcp.GradioMCPServer.lifespan(app:Starlette) -> AsyncIterator[None]Context manager for managing session manager lifecycle.
func
gradio.mcp.GradioMCPServer.list_prompts() -> list[self.types.Prompt]List all available prompts.
func
gradio.mcp.GradioMCPServer.list_resource_templates() -> list[self.types.ResourceTemplate]List all available resource templates.
func
gradio.mcp.GradioMCPServer.list_resources() -> list[self.types.Resource]List all available resources.
func
gradio.mcp.GradioMCPServer.list_tools() -> list[self.types.Tool]List all tools on the Gradio app.
func
gradio.mcp.GradioMCPServer.read_resource(uri:AnyUrl | str) -> list[self.ReadResourceContents]Read a specific resource by URI.
method
gradio.mcp.GradioMCPServer.warn_about_state_inputs() -> NoneWarn about tools that have gr.State inputs.
func
gradio.mcp.prompt(name:str | None=None, description:str | None=None)Decorator to mark a function as an MCP prompt.
func
gradio.media.get_audio(filename:Optional[str]=None) -> strGet path to an audio file.
func
gradio.media.get_file(filename:Optional[str]=None) -> strGet path to a data file (CSV, JSON, text, etc.).
func
gradio.media.get_image(filename:Optional[str]=None) -> strGet path to an image file.
func
gradio.media.get_model3d(filename:Optional[str]=None) -> strGet path to a 3D model file.
func
gradio.media.get_video(filename:Optional[str]=None) -> strGet path to a video file.
func
gradio.node_server.attempt_connection(host:str, port:int) -> boolAttempts a single connection to the server.
func
gradio.node_server.drain_stderr(stream, buffer:deque[str]) -> NoneReads the Node server's stderr, keeping only the most recent lines.
func
gradio.oauth.oauth_login(request:fastapi.Request)Endpoint that redirects to HF OAuth page.
func
gradio.oauth.oauth_logout(request:fastapi.Request) -> RedirectResponseEndpoint that logs out the user (e.g.
func
gradio.oauth.oauth_redirect_callback(request:fastapi.Request) -> RedirectResponseEndpoint that handles the OAuth callback.
func
gradio.processing_utils.convert_video_to_playable_mp4(video_path:str) -> strConvert the video to mp4.
func
gradio.processing_utils.detect_audio_format(data:bytes) -> strDetect audio format from file header bytes.
func
gradio.processing_utils.extract_base64_data(x:str) -> strJust extracts the base64 data from a general base64 string.
func
gradio.processing_utils.video_is_playable(video_filepath:str) -> boolDetermines if a video is playable in the browser.
class
gradio.route_utils.GradioMultiPartParserVendored from starlette.MultipartParser.
class
gradio.route_utils.GradioUploadFileUploadFile with a sha attribute.
class
gradio.route_utils.ObjUsing a class to convert dictionaries into objects.
func
gradio.route_utils.create_url_safe_hash(data:bytes, digest_size=8)Create a URL-safe short hash of the data.
func
gradio.route_utils.delete_files_created_by_app(blocks:Blocks, age:int | None) -> NoneDelete files that are older than age.
func
gradio.route_utils.get_api_call_path(request:fastapi.Request) -> strExtracts the API call path from the request URL.
func
gradio.route_utils.get_root_url(request:fastapi.Request, route_path:str, root_path:str | None) -> strGets the root url of the Gradio app (i.e.
func
gradio.route_utils.slugify(value)Convert to ASCII.
class
gradio.routes.AppFastAPI App Wrapper
func
gradio.routes.App.split_reasoning_code(text:str) -> tuple[str, str]Extract all <reasoning>...</reasoning> and code.
func
gradio.routes.App.strip_think_blocks(text:str) -> strRemove any <think> ...
class
gradio.static_server.StaticWorkerPoolManages N static file server processes.
method
gradio.static_server.StaticWorkerPool.get_next_url() -> strRound-robin to the next static worker.
method
gradio.static_server.StaticWorkerPool.shutdown()Stop all static worker processes.
method
gradio.static_server.StaticWorkerPool.start()Spawn all static worker processes.
class
gradio.templates.FilesSets: file_count="multiple"
class
gradio.templates.ImageMaskSets: brush=Brush(colors=["#000000"], color_mode="fixed")
class
gradio.templates.ListSets: type="array", col_count=1
class
gradio.templates.MatrixSets: type="array"
class
gradio.templates.MicrophoneSets: sources=["microphone"]
class
gradio.templates.NumpySets: type="numpy"
class
gradio.templates.PaintSets: sources=()
class
gradio.templates.PlayableVideoSets: format="mp4"
class
gradio.templates.TextAreaSets: lines=7
class
gradio.utils.SyncToAsyncIteratorTreat a synchronous iterator as async one.
func
gradio.utils.async_lambda(f:Callable) -> CallableTurn a function into an async function.
func
gradio.utils.connect_heartbeat(config:BlocksConfigDict, blocks, fns=None) -> boolDetermines whether a heartbeat is required for a given config.
func
gradio.utils.deep_equal(a:Any, b:Any) -> boolDeep equality check for component values.
func
gradio.utils.delete_none(_dict:dict, skip_value:bool=False, skip_props:list[str] | None=None) -> dictDelete keys whose values are None from a dictionary
func
gradio.utils.find_user_stack_level() -> intFind the first stack frame not inside Gradio.
func
gradio.utils.is_in_or_equal(path_1:str | Path, path_2:str | Path) -> boolTrue if path_1 is a descendant (i.e.
func
gradio.utils.run_coro_in_background(func:Callable, *args, **kwargs)Runs coroutines in background.
func
gradio.utils.safe_get_lock() -> asyncio.LockGet asyncio.Lock() without fear of getting an Exception.
func
gradio.utils.set_static_paths(paths:str | Path | list[str | Path]) -> NoneSet the static paths to be served by the gradio app.
func
gradio.utils.watchfn(reloader:SourceFileReloader) -> NoneWatch python files in a given module.
class
gradio.workflow.WorkflowBuild and launch a visual AI workflow as a Gradio app.
method
gradio.workflow.Workflow.launch(*args, **kwargs)Launch the workflow as a Gradio app.
func
gradio.workflow.get_oauth_available(_data=None) -> strWhether OAuth sign-in is actually wired up.
func
gradio.workflow.get_token(_data=None, request:Optional[Request]=None, token:Optional[OAuthToken]=None) -> strReturn the HF token for this browser session.
class
gradio.workflow_api.WorkflowExecutorRuns a subject's upstream sub-DAG server-side.
method
gradio.workflow_api.WorkflowExecutor.run(subject_id:str, inputs:dict[str, Any], request:Any=None, token:Any=None) -> AnyExecute the subgraph feeding `subject_id`.
class
gradio.workflow_api.WorkflowGraphParsed, indexed view of a schema-v2 workflow dict.
func
gradio.workflow_api.upstream_node_ids(graph:WorkflowGraph, target_id:str) -> set[str]All nodes transitively feeding `target_id` (inclusive).
method
js._website.generate_jsons.chunking.TextChunker.count_tokens(text:str) -> intCount the number of tokens in a text string.
About this data
These signatures were extracted from the public source of gradio-app/gradio
using Python's ast module. Argument names, default values,
type annotations and return types are taken verbatim from the code.
Implementation bodies are never stored. See
how it works for details.