跳到正文
Skillpedia
API 与服务器(后端)5.4k · #14845

app-ai-binding

它能做什么

这项技能教智能体如何为运行在 Cloudflare 上的应用添加基于模型的 AI 功能。它说明内置 AI 绑定如何在服务器端使用,以及哪些调用可以放心依赖。

适用场景

  • ✓当用户想在 Cloudflare 应用中添加聊天机器人、摘要或分类器时。
  • ✓当用户想在 Cloudflare 应用中内置嵌入或语义搜索时。
  • ✓当用户想由 Workers AI 模型处理图像理解或转录时。

技能链接

https://github.com/cloudflare/vibesdk/blob/main/worker/agents/think/skills/app-ai-binding/SKILL.md

复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。

使用方法

最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/cloudflare/vibesdk/blob/main/worker/agents/think/skills/app-ai-binding/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 AI

“请帮我在 Cloudflare 的应用中添加一个聊天机器人,让它用内置的 AI 绑定回答问题。”

每周 5 个新技能,1 分钟读完。

工作原理

智能体会在服务器端的应用类中调用 AI 绑定,并指定模型和输入消息。浏览器只调用应用的路由,因此模型访问始终保留在服务器上。

技术内容(原始 SKILL.md)

作者在 GitHub 上的英文原文。

Generated apps can call Workers AI from the App Durable Object through this.env.AI. The platform provides this binding automatically in Dynamic Worker previews and native Cloudflare deployments. Do not add an ai section to the generated app's wrangler.json.

Use only AI.run(model, inputs, options?). Preview uses a restricted proxy with this method, while deployed Workers receive the native Workers AI binding. Methods such as AI.gateway(), AI.models(), AI.autorag(), and AI.toMarkdown() are not portable between preview and deployment.

Type and usage

import { DurableObject } from "cloudflare:workers";

interface Env {
  AI: Ai;
}

export class App extends DurableObject<Env> {
  async fetch(request: Request): Promise<Response> {
    const { prompt } = await request.json<{ prompt: string }>();
    const result = await this.env.AI.run("@cf/meta/llama-4-scout-17b-16e-instruct", {
      messages: [
        { role: "system", content: "Answer clearly and concisely." },
        { role: "user", content: prompt },
      ],
    });
    return Response.json(result);
  }
}

Keep AI calls in the server-side App class. Browser code should call an app API route; it must never receive model credentials or call the binding directly.

Common tasks

Text generation

Use @cf/meta/llama-4-scout-17b-16e-instruct with either prompt or messages:

const result = await this.env.AI.run("@cf/meta/llama-4-scout-17b-16e-instruct", {
  messages: [{ role: "user", content: userPrompt }],
  max_tokens: 512,
});

Embeddings

Use @cf/baai/bge-base-en-v1.5. The response contains embedding vectors in data:

const result = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", {
  text: ["first document", "second document"],
});

Image classification

Use @cf/microsoft/resnet-50 with image bytes converted to a number array:

const image = [...new Uint8Array(await request.arrayBuffer())];
const result = await this.env.AI.run("@cf/microsoft/resnet-50", { image });

Speech transcription

Use @cf/openai/whisper with audio bytes:

const audio = [...new Uint8Array(await request.arrayBuffer())];
const result = await this.env.AI.run("@cf/openai/whisper", { audio });

Model input and output shapes differ. Keep model-specific parsing close to the call and validate user input before inference. Use only active model IDs from the current Workers AI model catalog; never generate code with a deprecated model.

Limits and errors

Dynamic Worker previews enforce a per-app AI call limit. AI features must fail transparently when inference is unavailable.

  • Never return canned, random, mock, placeholder, or hard-coded content as a fallback for an AI response.
  • Never catch an AI.run() error and continue with an apparently successful response.
  • Never return 200 with fields such as fallbackUsed after inference fails.
  • Return a non-2xx JSON response containing a safe, useful error message. The frontend must display that error to the user.
  • Do not retry rate-limit failures in a loop.
try {
  const result = await this.env.AI.run("@cf/meta/llama-4-scout-17b-16e-instruct", {
    messages: [{ role: "user", content: userPrompt }],
  });
  return Response.json(result);
} catch (error) {
  const message = error instanceof Error ? error.message : "AI inference failed";
  return Response.json({ error: "AI inference failed", details: message }, { status: 503 });
}

Frontend callers must inspect both the HTTP status and error body:

const response = await fetch("./api/chat", requestOptions);
const body = await response.json<{ content?: string; error?: string; details?: string }>();
if (!response.ok) throw new Error(body.details || body.error || "AI request failed");

Use non-streaming calls for preview-compatible code. Native Workers AI deployments support { stream: true }, but streaming across the preview proxy is not guaranteed.

常见问题

我需要在配置文件中添加 AI 部分吗?

不需要。技能说明,平台会自动提供 AI 绑定。

浏览器可以直接调用模型吗?

不可以。技能说明,浏览器代码应调用应用路由,而不是直接调用绑定。

应该使用哪种 AI 方法?

技能建议使用 run 方法,因为其他 AI 方法在预览和部署之间不能通用。

详情

作者的原始描述

Build AI features in generated apps using the platform-provided Workers AI binding. Load this skill for chatbots, summarization, classification, embeddings, semantic search, image understanding, transcription, translation, or other model inference.

repo: cloudflare/vibesdk

热度

GitHub 星标
5.4k
排名
#14845
许可证
MIT
更新时间
2026/10/21

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能