跳转到内容
搜索文档

自定义元数据

最后更新 查看 MarkdownAgent 设置

AI Gateway 中的自定义元数据允许你使用用户 ID 或其他标识符标记请求,从而更好地跟踪和分析请求。元数据值可以是字符串、数字或布尔值,并会显示在日志中,便于搜索和过滤数据。

主要功能

  • 自定义标记:向请求添加用户 ID、团队名称、测试指示符和其他相关信息。
  • 增强日志:元数据会出现在日志中,便于详细检查和排查问题。
  • 搜索与过滤:使用元数据高效搜索和过滤已记录的请求。

支持的元数据类型

  • String
  • Number
  • Boolean

实现方式

使用 cURL

要使用 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?"}]}'

使用 SDK

要使用 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);
		}
	},
};

使用 Binding

要使用绑定(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);
	},
};

这篇文档对您有帮助吗?