跳转到内容
搜索文档

REST API

最后更新 查看 MarkdownAgent 设置

本指南将指导你设置并部署第一个 Workers AI 项目。你将使用 Workers AI REST API 来体验大型语言模型(LLM)。

前提条件

如果尚未注册,请先注册 Cloudflare 账户

1. 获取 API token 和 Account ID

使用 REST API 需要 API token 和 Account ID。

要获取这些值:

  1. 在 Cloudflare 仪表板中,前往 Workers AI 页面。

    Go to Workers AI ↗
  2. 选择 Use REST API(使用 REST API)

  3. 获取 API token:

    1. 选择 Create a Workers AI API Token(创建 Workers AI API 令牌)
    2. 查看预填信息。
    3. 选择 Create API Token(创建 API 令牌)
    4. 选择 Copy API Token(复制 API 令牌)
    5. 保存该值以备后用。此 token 可在你的个人资料中查看。
  4. 对于 Get Account ID(获取账户 ID),复制 Account ID(账户 ID) 的值。保存该值以备后用。

2. 通过 API 运行模型

创建 API token 后,在请求中使用 API token 进行身份验证并调用 API。

你将使用 Execute AI model 端点来运行 @cf/meta/llama-3.1-8b-instruct 模型:

curl https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/ai/run/@cf/meta/llama-3.1-8b-instruct \
  -H 'Authorization: Bearer {API_TOKEN}' \
  -d '{ "prompt": "Where did the phrase Hello World come from" }'

{ACCOUNT_ID}{API_TOKEN} 替换为你的值。

API 响应如下所示:

{
	"result": {
		"response": "Hello, World first appeared in 1974 at Bell Labs when Brian Kernighan included it in the C programming language example. It became widely used as a basic test program due to simplicity and clarity. It represents an inviting greeting from a program to the world."
	},
	"success": true,
	"errors": [],
	"messages": []
}

此示例执行使用的是 @cf/meta/llama-3.1-8b-instruct 模型,但你可以使用 Workers AI 模型目录 中的任意模型。如果使用其他模型,需要将 {model} 替换为你所需的模型名称。

完成本指南后,你已创建 Cloudflare 账户(如果之前没有),并创建了授予 Workers AI 读取权限的 API token。你通过终端中的 cURL 命令执行了 @cf/meta/llama-3.1-8b-instruct 模型,并在 JSON 响应中收到了 prompt 的答案。

相关资源

  • Models - 浏览 Workers AI 模型目录。
  • AI SDK - 了解如何与 AI 模型集成。

这篇文档对您有帮助吗?