Sub topic 13
Calling the Chat App from Code with gradio_client
Every Gradio app exposes an HTTP API alongside its web page. The gradio_client package is a Python wrapper around that API. In this chapter you will call a running chat app from another program, find the right endpoint name, handle streamed output, and deal with the errors that come up most often.
Prerequisites
This chapter assumes you can:
- Run a Gradio chat app locally with
gr.ChatInterface, as in the earlier chapters. - Write basic Python, including functions and iterating over generators.
- Use pip and run a script from a terminal.
Install the client in the environment where the calling program runs:
pip install gradio_clientThe client does not need Gradio itself. That is useful when a script, a worker, or a test suite only needs to talk to the app.
The working model
A running gr.ChatInterface registers its chat function as a named API endpoint. The default name is /chat. The client connects to the app's URL, reads a description of its endpoints, and lets you call them like Python functions.
Two points shape how you use it:
- The API takes the message, not the history. The browser session keeps the conversation history. A call from
gradio_clientis not part of any browser session, so the history your chat function receives from the API does not include earlier API calls. - Extra controls you added with
additional_inputsbecome extra parameters of the endpoint, in the order you declared them.
A first call
Start a basic chat app in one terminal. Save it as app.py:
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Run python app.py. Gradio serves on http://127.0.0.1:7860/ by default. In a second terminal, run this script:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
result = client.predict("Hello!", api_name="/chat")
print(result)The output is You said: Hello!. Client(...) makes a request to fetch the endpoint list. predict sends the arguments positionally and blocks until the reply arrives.
Finding the endpoint and its parameters
If you are not sure of the endpoint name or the parameter order, ask the client:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
client.view_api()view_api() prints each endpoint, its parameters with types and defaults, and its return values. Always check this output when you call an app you did not write. The same information appears on the app's web page through the "Use via API" link in the footer.
You can pass return_format="dict" to view_api to get the description as data instead of printed text. That is handy for tests that check an app still exposes the endpoint you depend on.
Apps with additional inputs
Suppose the app has a system prompt and a temperature slider, as in the earlier LLM chapter. The endpoint then takes three parameters: the message, the system prompt, and the temperature. Pass them in that order, or by keyword:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
reply = client.predict(
"Explain what a generator is in one sentence.",
"You are a terse Python tutor.",
0.2,
api_name="/chat",
)
print(reply)Keyword arguments are safer, because they survive someone reordering the inputs. The keyword names come from view_api(). They are usually derived from the parameter names of the chat function, and for additional_inputs they come from the component labels. Names can differ between Gradio versions, so check your own output rather than copying names from an example.
If you leave out an argument that has a default value in the component, the client fills in the default. If it has no default, the call fails with an error.
Streaming replies with submit
predict waits for the final value. If the chat function is a generator, as in the streaming chapter, you can instead receive partial replies as they arrive. Use submit, which returns a Job object right away:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
job = client.submit("Tell me a story.", api_name="/chat")
for partial in job:
print(partial)
print("Final:", job.result())Iterating over the job yields each output the server produces. For a chat generator, every item is the full reply so far, not just the new words. This matches how the chat function works: each yield replaces the displayed text with a longer version.
To print only the new text, keep the previous length:
from gradio_client import Client
client = Client("http://127.0.0.1:7860/")
job = client.submit("Tell me a story.", api_name="/chat")
printed = 0
for partial in job:
print(partial[printed:], end="", flush=True)
printed = len(partial)
print()The Job object has other useful members:
| Member | What it does |
|---|---|
| `job.result(timeout=None)` | Blocks until the job finishes and returns the final output. Raises the job's error if it failed. |
| `job.done()` | Returns `True` when the job has finished, successfully or not. |
| `job.status()` | Returns a status object with the queue position and progress details. |
| `job.outputs()` | Returns the list of outputs received so far. |
| `job.cancel()` | Asks the server to stop the job. It has no effect once the job is running or finished. |
Use submit with a callback if you do not want to block. Pass result_callbacks=[fn] and fn is called with the final result.
Keeping a conversation going
Because the API call does not carry the browser's history, each predict call is a fresh conversation as far as your chat function's history is concerned. If the app needs context, you have two options.
- Resend the context inside the message. Build a single string that contains the earlier turns. This is simple but couples your client to how the app interprets text.
- Keep history on the client and use an endpoint designed for it. If you control the app, expose a separate function through
gr.apior agr.Blocksevent that accepts the full message list.
Check what your own app does before relying on either approach. Test it by sending two related messages in sequence and reading the reply to the second one. A chat function that prints len(history) is a quick way to see what the API call really passes in.
Connecting to protected and remote apps
The client works with deployed apps, not only local ones.
import os
from gradio_client import Client
client = Client(
"https://my-chat.example.com/",
auth=(os.environ["CHAT_USER"], os.environ["CHAT_PASSWORD"]),
)
print(client.predict("Hello!", api_name="/chat"))authtakes a(username, password)tuple. Use it when the app was launched withauth=.... Read the credentials from environment variables, as in the deployment chapter, so they never appear in source control.- For a Hugging Face Space, pass the Space id, such as
Client("username/space-name"). For a private Space, addtoken=os.environ["HF_TOKEN"](older client versions call this argumenthf_token). - A URL with a trailing path works only if it points at the root of the Gradio app. If the app is mounted under a sub-path behind a proxy, give the client the full mounted URL.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError` saying the API name was not found | The endpoint is not called `/chat`, for example because you customized it with `api_name` | Run `client.view_api()` and use the name it prints |
| Connection refused | The app is not running, or it listens on a different port | Check the terminal running the app and the URL it printed |
| Connection works locally but not from another machine | The app is bound to `127.0.0.1` | Launch with `server_name="0.0.0.0"` and open the firewall port |
| Login failure or HTTP 401 | The app requires authentication | Pass `auth=(user, password)` |
| Error raised from `predict` that mentions a hidden or upstream failure | The chat function raised an exception on the server | Read the server's terminal output. Use `gr.Error` in the app for messages you want clients to see |
| Wrong number of arguments | `additional_inputs` changed on the server | Compare your call to the current `view_api()` output |
| Call hangs | The app's queue is full or the model is slow | Use `submit`, check `job.status()`, and set a timeout in `job.result(timeout=...)` |
Exceptions raised inside the chat function reach the client as a generic failure. Only messages raised with gr.Error are shown in detail by default. This is a deliberate protection against leaking server internals, so debug from the server logs.
Gotchas
predictreturns only the final output. If the chat function streams,predictstill waits for the generator to finish and returns the last yielded value.- Output shape depends on the app. A plain
ChatInterfacereturns a string. A multimodal app, or one built withgr.Blocks, may return a list or a dictionary. Print the result before writing code that parses it. - Concurrency is limited by the server. Gradio queues requests. If many scripts call the same app, they wait in line, and the default concurrency limit for an event is small. Slow model calls will back up quickly.
- The client is not a model SDK. It talks to your Gradio app, not directly to the LLM provider. Your chat function still holds the provider key. This is good for security, but it means your Gradio server is the bottleneck and the place where you enforce limits.
- Version drift. Parameter names and defaults change between Gradio releases. Pin versions of both
gradioandgradio_clientinrequirements.txt, and keep them close to each other.
A small reusable wrapper
Wrapping the client in a function keeps the rest of your code free of Gradio details:
import os
from gradio_client import Client
_client = None
def ask(message: str, timeout: float = 60.0) -> str:
global _client
if _client is None:
_client = Client(os.environ.get("CHAT_URL", "http://127.0.0.1:7860/"))
job = _client.submit(message, api_name="/chat")
return job.result(timeout=timeout)
if __name__ == "__main__":
print(ask("Say hello in French."))The wrapper creates the client once, because the constructor makes a network request. It reads the URL from an environment variable so the same code works locally and in deployment. It also applies a timeout, so a stuck server does not freeze your program.
Exercise
You call a deployed chat app with client.predict("Hi", api_name="/chat") and get an error that the API name is not found. The app works in the browser. What do you do first, and why might the name differ?
Show answer
Run client.view_api() to print the endpoints the app actually exposes. The app author may have set a custom api_name, or the app may be built with gr.Blocks where the endpoint is named after the event function. Use the name from the output.
Exercise
Your script uses submit on a streaming chat app and prints every item from the job. The output repeats the beginning of the reply many times. Why, and how do you print only new text?
Show answer
Each item the job yields is the full reply so far, because the chat function yields the growing text. Track how much you have printed, for example printed = 0, then print partial[printed:] and set printed = len(partial) after each item.