See and control AI spend · Exercise 02

Add AI Gateway

Create an AI Gateway, then configure the application to route all AI requests through it and see the results in the application logs.

Add AI Gateway

The starter sends requests directly to Workers AI with a hard coded model string. Workers AI provides usage reporting, but these requests don’t appear in AI Gateway logs.

In this exercise, you’ll create AI Gateway and connect the application to it. You’ll inspect individual requests in AI Gateway logs, including the model, token usage, duration, and estimated cost.

BeforeAfterYour WorkerWorkers AIYour WorkerAI GatewayWorkers AI

AI Gateway now sits between your Worker and Workers AI, recording each request so you can inspect its model, usage, and estimated cost.

Create an AI Gateway

Create a gateway using the cf CLI with logging enabled and caching disabled.

Create a gateway named support-copilot with the following command:

Terminalcf ai-gateway gateways create --id support-copilot --authentication true \
  --collect-logs true --cache-ttl 0 --cache-invalidate-on-update true \
  --rate-limiting-interval 0 --rate-limiting-limit 0 --rate-limiting-technique sliding

In the Cloudflare dashboard, you can view AI Gateway logs by opening AI > AI Gateway > support-copilot > Logs. The logs will be empty to start since the starter isn’t configured to use AI Gateway yet.

Configure AI Gateway

When adding the configuration for AI Gateway in code, you’ll need to reference it by the name you just created, support-copilot. Instead of hard-coding that string in the application, it’s better to set it as public text variable. Do this with a text binding by adding the following line in cloudflare.config.ts.

cloudflare.config.ts env: {
  GATEWAY_ID: bindings.text("support-copilot"),
  //...
},

This allows you to reference the value support-copilot in your Worker as env.GATEWAY_ID.

As mentioned above, this project is already configured to make AI calls to Workers AI. This is configured based on the AI binding in cloudflare.config.ts.

env: {
  AI: bindings.ai({ dev: { remote: true } }),
},

With the binding in place, the application makes calls with env.AI.run(). To ensure that each of these calls runs through the new AI Gateway that you just created, you’ll need to pass the AI Gateway configuration as a prop.

In src/index.ts, add gateway to the existing options object in env.AI.run().

src/index.tsconst result = await env.AI.run(
  MODEL,
  {
    messages: [{ role: "user", content: USER_TYPES[userType].prompt }],
    max_tokens: 8,
  },
  {
    returnRawResponse: true,
    gateway: {
      id: env.GATEWAY_ID,
      collectLog: true,
      skipCache: true,
    },
  },
);

View the results

Open the running app, and click Free user, Pro user, and Background bot to send requests. You should now see that each request shows as anonymous.

If you inspect the AI Gateway logs in the Cloudflare dashboard, you should see a log for each request that includes:

  • the model used
  • the request duration
  • token usage
  • the estimated cost

AI Gateway now records the requests, but you still haven’t attached specific labels identifying the callers. The application therefore displays anonymous for each successful request. In the next exercise, Add metadata to AI requests, you’ll label requests so you can distinguish between Free user, Pro user, and Background bot.