Courses

See and control AI spend

See who's driving your AI usage, route requests by user type, and limit a background bot's use of higher-cost models.

See and control AI spend

The cost of implementing AI features in your app can add up fast. However, a total usage number doesn’t tell you whether requests came from free users, paying customers, or a background bot. To control that usage, you need to know:

  • which user types generate requests
  • which models handle those requests
  • how many tokens each request uses and the associated costs

In this course, you’ll start from a sample application that allows you to simulate AI requests from three personas:

  • Free user
  • Pro user
  • Background bot

All three send a short prompt directly to Workers AI. The application then displays details of each request which are minimal to start.

You’ll connect the application to AI Gateway, label requests by user type, and use those labels to choose the appropriate model per user type. Free users will use a lower-cost model, while Pro users and the bot will use a higher-cost model with a lower-cost backup if it fails.

Finally, you’ll limit the bot to 3 requests per hour on the higher-cost model. After that, its requests go to the lower-cost model while Free and Pro users keep their existing model usage.

Free userPro userBackground botWithin allowanceAllowance usedOn failureYour appAI GatewayRequest logs and user-type rulesLower-cost modelHigher-cost modelBot allowance3 higher-cost model requests per hourLower-cost backup model

Exercises

  1. 00.Interview: Tell your agent how deep you want to go, what the three-caller demo represents, and which model providers you use.
  2. 01.Setup: Clone the starter code, install packages, and run the dev server.
  3. 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.
  4. 03.Add metadata to AI requests: Label every request to AI Gateway with custom metadata fields that includes the user type that generated the request.
  5. 04.Choose models dynamically: Create a dynamic route in AI Gateway to dynamically route specific traffic to different models based on the incoming metadata.
  6. 05.Cap AI usage: Limit your background bot's requests to the higher-cost model in the dynamic route, then switch it to a lower-cost model while human users keep working.