[ PROMPT_NODE_24442 ]
Workers AI API 参考
[ SKILL_DOCUMENTATION ]
# Workers AI API 参考
## 核心方法
typescript
const response = await env.AI.run(model, input);
## 文本生成
typescript
const result = await env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [
{ role: 'system', content: 'You are helpful' },
{ role: 'user', content: 'Hello' }
],
temperature: 0.7, // 0-1
max_tokens: 100
});
console.log(result.response);
**流式传输:**
typescript
const stream = await env.AI.run(model, { messages, stream: true });
return new Response(stream, { headers: { 'Content-Type': 'text/event-stream' } });
## 嵌入 (Embeddings)
typescript
const result = await env.AI.run('@cf/baai/bge-base-en-v1.5', {
text: ['Query', 'Doc 1', 'Doc 2'] // 批量处理以提高效率
});
const [queryEmbed, doc1Embed, doc2Embed] = result.data; // 768 维向量
## 工具调用 (Function Calling)
typescript
const tools = [{
type: 'function',
function: {
name: 'getWeather',
description: '获取位置天气',
parameters: {
type: 'object',
properties: { location: { type: 'string' } },
required: ['location']
}
}
}];
const response = await env.AI.run(model, { messages, tools });
if (response.tool_calls) {
const args = JSON.parse(response.tool_calls[0].function.arguments);
// 执行函数,将结果传回
}
## 图像生成
typescript
const image = await env.AI.run('@cf/stabilityai/stable-diffusion-xl-base-1.0', {
prompt: 'Mountain sunset',
num_steps: 20, // 1-20
guidance: 7.5 // 1-20
});
return new Response(image, { headers: { 'Content-Type': 'image/png' } });
## 语音识别
typescript
const audioArray = Array.from(new Uint8Array(await request.arrayBuffer()));
const result = await env.AI.run('@cf/openai/whisper', { audio: audioArray });
console.log(result.text);
## 翻译
typescript
const result = await env.AI.run('@cf/meta/m2m100-1.2b', {
text: 'Hello',
source_lang: 'en',
target_lang: 'es'
});
console.log(result.translated_text);
## REST API
bash
curl https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/run/@cf/meta/llama-3.1-8b-instruct
-H "Authorization: Bearer $TOKEN"
-d '{"messages":[{"role":"user","content":"Hello"}]}'
## 错误代码
| 代码 | 含义 | 修复 |
|------|---------|-----|
| 7502 | 模型未找到 | 检查拼写 |
| 7504 | 验证失败 | 验证输入模式 |
| 7505 | 速率限制 | 降低频率或升级套餐 |
| 7506 | 上下文超限 | 减少输入长度 |