AI Gateway 中的自定义元数据允许你使用用户 ID 或其他标识符标记请求,从而更好地跟踪和分析请求。元数据值可以是字符串、数字或布尔值,并会显示在日志中,便于搜索和过滤数据。
- 自定义标记:向请求添加用户 ID、团队名称、测试指示符和其他相关信息。
- 增强日志:元数据会出现在日志中,便于详细检查和排查问题。
- 搜索与过滤:使用元数据高效搜索和过滤已记录的请求。
- String
- Number
- Boolean
要使用 cURL 在请求中包含自定义元数据:
# Run `wrangler whoami` to get your account ID to replace $CLOUDFLARE_ACCOUNT_ID,
# and `wrangler auth token` to get an auth token to replace $CLOUDFLARE_API_TOKEN.
curl -X POST "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions" \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--header "Content-Type: application/json" \
--header 'cf-aig-metadata: {"team": "AI", "user": 12345, "test":true}' \
--data '{"model": "openai/gpt-4.1", "messages": [{"role": "user", "content": "What should I eat for lunch?"}]}'要使用 OpenAI SDK 在请求中包含自定义元数据:
import OpenAI from "openai";
export default {
async fetch(request, env, ctx) {
const openai = new OpenAI({
apiKey: env.CLOUDFLARE_API_TOKEN,
baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`,
});
try {
const chatCompletion = await openai.chat.completions.create(
{
model: "openai/gpt-4.1",
messages: [{ role: "user", content: "What should I eat for lunch?" }],
max_tokens: 50,
},
{
headers: {
"cf-aig-metadata": JSON.stringify({
user: "JaneDoe",
team: 12345,
test: true,
}),
},
},
);
const response = chatCompletion.choices[0].message;
return new Response(JSON.stringify(response));
} catch (e) {
console.log(e);
return new Response(e);
}
},
};import OpenAI from "openai";
export default {
async fetch(request, env, ctx) {
const openai = new OpenAI({
apiKey: env.CLOUDFLARE_API_TOKEN,
baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/v1`,
});
try {
const chatCompletion = await openai.chat.completions.create(
{
model: "openai/gpt-4.1",
messages: [{ role: "user", content: "What should I eat for lunch?" }],
max_tokens: 50,
},
{
headers: {
"cf-aig-metadata": JSON.stringify({
user: "JaneDoe",
team: 12345,
test: true,
}),
},
},
);
const response = chatCompletion.choices[0].message;
return new Response(JSON.stringify(response));
} catch (e) {
console.log(e);
return new Response(e);
}
},
};要使用绑定(Bindings)在请求中包含自定义元数据:
export default {
async fetch(request, env, ctx) {
const aiResp = await env.AI.run(
"@cf/mistral/mistral-7b-instruct-v0.1",
{ prompt: "What should I eat for lunch?" },
{
gateway: {
id: "gateway_id",
metadata: { team: "AI", user: 12345, test: true },
},
},
);
return new Response(aiResp);
},
};