AI Gateway Binding Methods
This guide provides an overview of how to use the latest Cloudflare Workers AI Gateway binding methods. You will learn how to set up an AI Gateway binding, access new methods, and integrate them into your Workers.
- Ensure your Worker project is configured with an AI Gateway binding in
wrangler.json
. - Install and use the
@cloudflare/workers-types
library, version4.20250124.3
or above.
To connect your Worker to Workers AI, add the following to your wrangler.toml
file:
This configuration sets up the AI binding accessible in your Worker code as env.AI
.
To perform an inference task using Workers AI and an AI Gateway, you can use the following code:
Additionally, you can access the latest request log ID with:
You can access your AI Gateway binding using the following code:
Once you have the gateway instance, you can use the following methods:
The patchLog
method allows you to send feedback, score, and metadata for a specific log ID. All object properties are optional, so you can include any combination of the parameters:
- Returns:
Promise<void>
(Make sure toawait
the request.) - Example Use Case: Update a log entry with user feedback or additional metadata.
The getLog
method retrieves details of a specific log ID. It returns an object of type Promise<AiGatewayLog>
. You can import the AiGatewayLog
type from the @cloudflare/workers-types
library.
- Returns:
Promise<AiGatewayLog>
- Example Use Case: Retrieve log information for debugging or analytics.
The run
method allows you to execute universal requests. Users can pass either a single universal request object or an array of them. This method supports all AI Gateway providers.
Refer to the Universal endpoint documentation for details about the available inputs.
- Returns:
Promise<Response>
- Example Use Case: Perform a universal AI request to any supported provider.
With the new AI Gateway binding methods, you can now:
- Send feedback and update metadata with
patchLog
. - Retrieve detailed log information using
getLog
. - Execute universal requests to any AI Gateway provider with
run
.
These methods offer greater flexibility and control over your AI integrations, empowering you to build more sophisticated applications on the Cloudflare Workers platform.