The Client class is the primary interface for establishing and managing persistent connections to Gradio applications. It provides comprehensive functionality for predictions, streaming, file uploads, and connection lifecycle management.
Static methods for establishing connections to Gradio applications and HuggingFace Spaces.
/**
* Connect to a Gradio application
* @param app_reference - URL or HuggingFace Space reference
* @param options - Connection configuration options
* @returns Promise resolving to connected Client instance
*/
static connect(app_reference: string, options?: ClientOptions): Promise<Client>;
/**
* Duplicate and connect to a HuggingFace Space
* @param app_reference - HuggingFace Space reference
* @param options - Duplication and connection options
* @returns Promise resolving to Client connected to duplicated space
*/
static duplicate(app_reference: string, options?: DuplicateOptions): Promise<Client>;Usage Examples:
import { Client } from "@gradio/client";
// Connect to a public Gradio app
const client = await Client.connect("https://gradio-app-url");
// Connect to HuggingFace Space
const client = await Client.connect("username/space-name");
// Connect with authentication
const client = await Client.connect("private-app", {
hf_token: "your-token",
auth: ["username", "password"]
});
// Duplicate a space (requires HF token)
const client = await Client.duplicate("username/space-name", {
hf_token: "your-token",
hardware: "cpu-basic"
});Core methods for making predictions and submitting data to Gradio endpoints.
/**
* Make a single prediction request
* @param endpoint - Endpoint name or index
* @param data - Input data array matching endpoint parameters
* @param event_data - Optional event metadata
* @returns Promise resolving to prediction results
*/
predict(
endpoint: string | number,
data?: unknown[] | Record<string, unknown>,
event_data?: unknown
): Promise<PredictReturn>;
/**
* Submit data for streaming results
* @param endpoint - Endpoint name or index
* @param data - Input data array matching endpoint parameters
* @param event_data - Optional event metadata
* @param trigger_id - Optional trigger identifier
* @param all_events - Whether to receive all event types
* @returns Async iterable of streaming events
*/
submit(
endpoint: string | number,
data?: unknown[] | Record<string, unknown>,
event_data?: unknown,
trigger_id?: number | null,
all_events?: boolean
): SubmitIterable<GradioEvent>;Usage Examples:
// Simple prediction
const result = await client.predict("/predict", ["input text"]);
console.log(result.data);
// Prediction with multiple inputs
const result = await client.predict("/process", [
"text input",
42,
{ setting: "value" }
]);
// Streaming prediction
const job = client.submit("/generate", ["prompt"]);
for await (const message of job) {
switch (message.type) {
case "data":
console.log("Generated:", message.data);
break;
case "status":
console.log("Status:", message.status);
break;
case "log":
console.log("Log:", message.log);
break;
}
}
// Cancel streaming job
const job = client.submit("/long-process", ["input"]);
setTimeout(() => job.cancel(), 5000); // Cancel after 5 secondsMethods for uploading and managing files within Gradio applications.
/**
* Upload files to the Gradio server
* @param root_url - Base URL for upload endpoint
* @param files - Array of File or Blob objects to upload
* @param upload_id - Optional upload session identifier
* @returns Promise resolving to upload response with file URLs
*/
upload_files(
root_url: string,
files: (Blob | File)[],
upload_id?: string
): Promise<UploadResponse>;
/**
* Upload FileData objects with metadata
* @param file_data - Array of FileData objects to upload
* @param root_url - Base URL for upload endpoint
* @param upload_id - Optional upload session identifier
* @param max_file_size - Maximum file size limit in bytes
* @returns Promise resolving to processed FileData array
*/
upload(
file_data: FileData[],
root_url: string,
upload_id?: string,
max_file_size?: number
): Promise<(FileData | null)[] | null>;Usage Examples:
import { FileData } from "@gradio/client";
// Upload raw files
const files = [new File(["content"], "test.txt", { type: "text/plain" })];
const response = await client.upload_files("https://app-url", files);
// Upload with FileData
const fileData = new FileData({
path: "./document.pdf",
orig_name: "important-doc.pdf",
mime_type: "application/pdf"
});
const result = await client.upload([fileData], "https://app-url");Methods for retrieving application schema and endpoint information.
/**
* Get API schema information for the connected application
* @returns Promise resolving to complete API information
*/
view_api(): Promise<ApiInfo<JsApiData>>;Usage Examples:
// Get API information
const apiInfo = await client.view_api();
// Explore available endpoints
console.log("Available endpoints:");
apiInfo.named_endpoints.forEach(endpoint => {
console.log(`- ${endpoint.name}: ${endpoint.description}`);
});
// Check endpoint parameters
const endpoint = apiInfo.named_endpoints["/predict"];
console.log("Parameters:", endpoint.parameters);
console.log("Returns:", endpoint.returns);Methods for interacting with component-level server functions.
/**
* Call component server functions directly
* @param component_id - Numeric component identifier
* @param fn_name - Function name to call on the component
* @param data - Arguments array for the function call
* @returns Promise resolving to function result
*/
component_server(
component_id: number,
fn_name: string,
data: unknown[]
): Promise<unknown>;Methods for managing the client connection lifecycle.
/**
* Close the client connection and clean up resources
*/
close(): void;
/**
* Attempt to reconnect to the application
* @returns Promise resolving to connection status
*/
reconnect(): Promise<"connected" | "broken" | "changed">;
/**
* Set authentication cookies for the session
* @param raw_cookies - Raw cookie string from Set-Cookie header
*/
set_cookies(raw_cookies: string): void;Usage Examples:
// Graceful shutdown
process.on('SIGINT', () => {
client.close();
process.exit(0);
});
// Automatic reconnection
client.reconnect().then(status => {
if (status === "connected") {
console.log("Reconnected successfully");
} else {
console.log("Failed to reconnect:", status);
}
});
// Set authentication cookies
client.set_cookies("session_id=abc123; auth_token=xyz789");interface ClientOptions {
/** HuggingFace authentication token */
hf_token?: `hf_${string}`;
/** Callback for space status updates */
status_callback?: SpaceStatusCallback | null;
/** Basic authentication credentials [username, password] */
auth?: [string, string] | null;
/** Whether to include null state values in responses */
with_null_state?: boolean;
/** Event types to subscribe to */
events?: EventType[];
/** Custom HTTP headers to include with requests */
headers?: Record<string, string>;
/** Query parameters to include with requests */
query_params?: Record<string, string>;
/** Session hash for connection identification */
session_hash?: string;
}interface DuplicateOptions extends ClientOptions {
/** Hardware tier for the duplicated space */
hardware?:
| "cpu-basic"
| "cpu-upgrade"
| "t4-small"
| "t4-medium"
| "a10g-small"
| "a10g-large"
| "a100-large";
/** Timeout for space duplication in milliseconds */
timeout?: number;
/** Whether to make the duplicated space private */
private?: boolean;
}interface PredictReturn {
/** Array of output values from the prediction */
data: unknown[];
/** Execution duration in seconds */
duration?: number;
/** Average execution duration for this endpoint */
average_duration?: number;
}interface SubmitIterable<T> extends AsyncIterable<T> {
/** Cancel the streaming operation */
cancel: () => Promise<void>;
}Common error scenarios and handling patterns:
try {
const client = await Client.connect("app-url");
} catch (error) {
if (error.message.includes("Could not connect")) {
// App is not accessible
console.error("Application unavailable");
} else if (error.message.includes("queue full")) {
// Queue is at capacity
console.error("Server busy, try again later");
}
}
// Handle streaming errors
const job = client.submit("/endpoint", ["data"]);
try {
for await (const message of job) {
if (message.type === "status" && message.status?.code === "error") {
console.error("Prediction failed:", message.status.message);
break;
}
}
} catch (error) {
console.error("Stream error:", error);
}