See and control AI spend · Exercise 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.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Add metadata to AI requests
AI Gateway now sees every request, but it doesn’t know whether it came from a Free user, Pro user, or Background bot.
In this exercise, you’ll attach custom metadata containing one property, user_type, with a value of free, pro, or bot.
Label every request
AI Gateway allows for up to five key-value pairs in metadata per request. In the dashboard, you can use this metadata to filter logs and break down spend. Later in this course, you’ll use the metadata to have different persons use different models.
The browser sends the selected user_type, and the Worker checks that it matches a key in USER_TYPES from src/demo-data.ts before attaching it as metadata. In a real application, metadata should be derived form trusted user information and not based on request data sent from the browser.
In src/index.ts, replace the existing const metadata = {}; immediately after const { userType } = input; with:
src/index.tsconst metadata = {
user_type: userType,
};
Then, add metadata to the existing gateway options, using the object you just created:
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,
metadata,
skipCache: true,
},
},
);
View the results
Reload the application and send a mix of requests. The Request metadata column should show user_type=free, user_type=pro, and user_type=bot.
This column shows the metadata the application sends. Inspect the matching requests in AI Gateway logs to verify that Gateway recorded the expected values.
Right now, the same model is used for every user type. In the next exercise, Choose models dynamically, you’ll route requests to different models based on user_type.