跳转到内容
搜索文档

使用 AI Gateway 设置 Workers AI

最后更新 查看 MarkdownAgent 设置

本指南将带你完成 Workers AI 项目的设置与部署。你将使用 Workers、AI Gateway 绑定(binding)以及大语言模型(LLM),在 Cloudflare 全球网络上部署第一个 AI 驱动的应用。

前提条件

  1. 注册 Cloudflare 账户
  2. 安装 Node.js

Node.js 版本管理器

使用 Voltanvm 等 Node 版本管理器,以避免权限问题并切换 Node.js 版本。本指南后续将介绍的 Wrangler 需要 Node 版本 16.17.0 或更高。

1. 创建 Worker 项目

你将使用 create-Cloudflare CLI(C3)创建新的 Worker 项目。C3 是一个命令行工具,用于帮助你设置并将新应用部署到 Cloudflare。

通过运行以下命令创建名为 hello-ai 的新项目:

npm create cloudflare@latest -- hello-ai

运行 npm create cloudflare@latest 会提示你安装 create-cloudflare 包并引导你完成设置。C3 还会安装 Wrangler(Cloudflare Developer Platform CLI)。

进行设置时,请选择以下选项:

  • 对于 What would you like to start with?,选择 Hello World example
  • 对于 Which template would you like to use?,选择 Worker only
  • 对于 Which language do you want to use?,选择 TypeScript
  • 对于 Do you want to use git for version control?,选择 Yes
  • 对于 Do you want to deploy your application?,选择 No(部署前我们还会做一些修改)。

这将创建一个新的 hello-ai 目录。新的 hello-ai 目录将包括:

进入应用目录:

cd hello-ai

2. 将 Worker 连接到 Workers AI

必须为 Worker 创建 AI 绑定(binding),才能连接到 Workers AI。绑定允许你的 Workers 与 Cloudflare Developer Platform 上的资源(如 Workers AI)交互。

要将 Workers AI 绑定到 Worker,请在 Wrangler 配置文件 末尾添加以下内容:

{
	"ai": {
		"binding": "AI",
	},
}
[ai]
binding = "AI"

你的绑定可在 Worker 代码中通过 env.AI 使用

下一步可以使用 "default" 作为 gateway ID。AI Gateway 会在首次已认证请求时自动创建默认 gateway。你也可以手动创建 gateway 并使用其 ID。

3. 在 Worker 中运行包含 AI Gateway 的推理任务

现在可以在 Worker 中运行推理任务。本例将使用 LLM llama-3.1-8b-instruct-fast 来回答问题。

用以下代码更新 hello-ai 应用目录中的 index.ts 文件:

src/index.tstypescript
export interface Env {
	// If you set another name in the [Wrangler configuration file](/workers/wrangler/configuration/) as the value for 'binding',
	// replace "AI" with the variable name you defined.
	AI: Ai;
}

export default {
	async fetch(request, env): Promise<Response> {
		// Specify the gateway label and other options here
		const response = await env.AI.run(
			"@cf/meta/llama-3.1-8b-instruct-fast",
			{
				prompt: "What is the origin of the phrase Hello, World",
			},
			{
				gateway: {
					id: "default", // Uses the default gateway, or replace with your gateway ID
					skipCache: true, // Optional: Skip cache if needed
				},
			},
		);

		// Return the AI response as a JSON object
		return new Response(JSON.stringify(response), {
			headers: { "Content-Type": "application/json" },
		});
	},
} satisfies ExportedHandler<Env>;

至此,你已为 Worker 创建了 AI 绑定,并配置 Worker 以执行 Llama 3.1 模型。现在可以先在本地测试项目,再进行全球部署。

4. 使用 Wrangler 进行本地开发

在项目目录中,通过运行 wrangler dev 在本地测试 Workers AI:

npx wrangler dev

运行 wrangler dev 后系统会提示你登录。运行 npx wrangler dev 时,Wrangler 会提供一个 URL(通常是 localhost:8787)供你查看 Worker。打开 Wrangler 提供的 URL 后,你会看到类似以下示例的消息:

{
  "response": "A fascinating question!\n\nThe phrase \"Hello, World!\" originates from a simple computer program written in the early days of programming. It is often attributed to Brian Kernighan, a Canadian computer scientist and a pioneer in the field of computer programming.\n\nIn the early 1970s, Kernighan, along with his colleague Dennis Ritchie, were working on the C programming language. They wanted to create a simple program that would output a message to the screen to demonstrate the basic structure of a program. They chose the phrase \"Hello, World!\" because it was a simple and recognizable message that would illustrate how a program could print text to the screen.\n\nThe exact code was written in the 5th edition of Kernighan and Ritchie's book \"The C Programming Language,\" published in 1988. The code, literally known as \"Hello, World!\" is as follows:\n\n    main()\n    {\n      printf(\"Hello, World!\");\n    }\n\nThis code is still often used as a starting point for learning programming languages, as it demonstrates how to output a simple message to the console.\n\nThe phrase \"Hello, World!\" has since become a catch-all phrase to indicate the start of a new program or a small test program, and is widely used in computer science and programming education.\n\nSincerely, I'm glad I could help clarify the origin of this iconic phrase for you!"
}

5. 部署你的 AI Worker

在全球部署 AI Worker 之前,先运行以下命令登录 Cloudflare 账户:

npx wrangler login

系统会打开网页,要求你登录 Cloudflare 仪表板。登录后,系统会询问 Wrangler 是否可以更改你的 Cloudflare 账户。向下滚动并选择 Allow(允许) 以继续。

最后,部署 Worker,使项目可在 Internet 上访问。运行以下命令部署:

npx wrangler deploy

部署完成后,你的 Worker 将在类似以下地址可用:

https://hello-ai.<YOUR_SUBDOMAIN>.workers.dev

Worker 将部署到你的自定义 workers.dev 子域名。现在可以访问该 URL 来运行 AI Worker。

完成本教程后,你已创建了一个 Worker,通过 AI Gateway 绑定将其连接到 Workers AI,并成功使用 Llama 3.1 模型运行了推理任务。

后续步骤

  • Workers 绑定 — 调用第三方模型、访问 gateway 方法,并与 AI SDK 集成。

这篇文档对您有帮助吗?