本指南将引导你使用 Cloudflare API 为 AI Gateway 请求添加人工反馈。你将学习如何检索相关请求日志,并使用 API 提交反馈。
如果你更希望通过仪表板添加人工反馈,请参阅添加人工反馈。
- 创建 API 令牌,并授予以下权限:
AI Gateway - ReadAI Gateway - Edit
- 获取你的 Account ID。
- 使用该 API 令牌和 Account ID,向 Cloudflare API 发送
POST请求。
cf-aig-log-id 是你要添加反馈的特定日志条目的唯一标识符。以下是获取该标识符的两种方法。
此方法允许你直接在 AI Gateway 返回的响应标头中找到 cf-aig-log-id。如果你能够访问原始 API 响应,这是最直接的方法。
以下步骤说明具体操作。
- 向 AI Gateway 发起请求:可以是你的应用发送到 AI Gateway 的请求。请求完成后,响应将包含各类元数据。
- 检查响应标头:响应将包含名为
cf-aig-log-id的标头。这是你提交反馈所需的标识符。
在以下示例中,cf-aig-log-id 为 01JADMCQQQBWH3NXZ5GCRN98DP。
{
"status": "success",
"headers": {
"cf-aig-log-id": "01JADMCQQQBWH3NXZ5GCRN98DP"
},
"data": {
"response": "Sample response data"
}
}如果你没有在响应正文中获得 cf-aig-log-id,或需要事后访问它,可以通过查询日志使用 Cloudflare API 检索。
发送 GET 请求以获取日志列表,然后找到特定 ID
Required API token permissions
At least one of the following token permissions is required:AI Gateway WriteAI Gateway Read
curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/ai-gateway/gateways/$GATEWAY_ID/logs" \
--request GET \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN"{
"result": [
{
"id": "01JADMCQQQBWH3NXZ5GCRN98DP",
"cached": true,
"created_at": "2019-08-24T14:15:22Z",
"custom_cost": true,
"duration": 0,
"id": "string",
"metadata": "string",
"model": "string",
"model_type": "string",
"path": "string",
"provider": "string",
"request_content_type": "string",
"request_type": "string",
"response_content_type": "string",
"status_code": 0,
"step": 0,
"success": true,
"tokens_in": 0,
"tokens_out": 0
}
]
}你也可以使用绑定检索 cf-aig-log-id,从而简化流程。以下是直接检索日志 ID 的方法:
const resp = await env.AI.run(
"@cf/meta/llama-3-8b-instruct",
{
prompt: "tell me a joke",
},
{
gateway: {
id: "my_gateway_id",
},
},
);
const myLogId = env.AI.aiGatewayLogId;获得 API 令牌和 cf-aig-log-id 后,你可以发送 PATCH 请求以提交反馈。
Required API token permissions
At least one of the following token permissions is required:AI Gateway Write
curl "https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/ai-gateway/gateways/$GATEWAY_ID/logs/$ID" \
--request PATCH \
--header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
--json '{
"feedback": 1
}'如果是负面反馈,请将请求正文调整为 -1。
{
"feedback": -1
}你可以通过两种方式验证反馈是否已提交:
- 通过 Cloudflare 仪表板 ↗:在 AI Gateway 界面中查看更新后的反馈。
- 通过 API:再发送一次 GET 请求以检索更新后的日志条目,并确认反馈已记录。