你可以使用 Workers 绑定(binding)与 Batch API 交互。
通过编写包含单个推理请求数组和 queueRequest: true 属性的 JSON payload 来发送初始批处理推理请求(该属性控制排队行为)。
export interface Env {
AI: Ai;
}
export default {
async fetch(request, env): Promise<Response> {
const embeddings = await env.AI.run(
"@cf/baai/bge-m3",
{
requests: [
{
query: "This is a story about Cloudflare",
contexts: [
{
text: "This is a story about an orange cloud",
},
{
text: "This is a story about a llama",
},
{
text: "This is a story about a hugging emoji",
},
],
},
],
},
{ queueRequest: true },
);
return Response.json(embeddings);
},
} satisfies ExportedHandler<Env>;{
"status": "queued",
"model": "@cf/baai/bge-m3",
"request_id": "000-000-000"
}你将收到包含以下值的响应:
status:表示请求已排队。request_id:批处理请求的唯一标识符。model:用于批处理推理的模型。
其中,request_id 在你需要轮询批处理状态 时很重要。
批处理请求排队后,使用 request_id 轮询其状态。处理期间,API 返回 queued 或 running 状态,表示请求仍在队列中或正在处理。
export interface Env {
AI: Ai;
}
export default {
async fetch(request, env): Promise<Response> {
const status = await env.AI.run("@cf/baai/bge-m3", {
request_id: "000-000-000",
});
return Response.json(status);
},
} satisfies ExportedHandler<Env>;{
"responses": [
{
"id": 0,
"result": {
"response": [
{ "id": 0, "score": 0.73974609375 },
{ "id": 1, "score": 0.642578125 },
{ "id": 2, "score": 0.6220703125 }
]
},
"success": true,
"external_reference": "reference-1"
}
],
"usage": { "prompt_tokens": 12, "completion_tokens": 0, "total_tokens": 12 }
}推理完成后,API 返回最终 HTTP 状态码 200 以及响应数组。每个响应对象对应一个输入 prompt,由 id 标识,该 id 映射到原始请求中 prompt 的索引。