Skip to content
Cloudflare Docs
非官方翻译 - 此文档为非官方中文翻译版本,仅供参考。如有疑问请以 英文官方文档 为准。

使用 fetch() 处理程序

一个非常常见的用例是为 LLM 提供通过函数调用执行 API 调用的能力。

在此示例中,LLM 将检索未来 5 天的天气预报。 为此,定义了一个 getWeather 函数,并将其作为工具传递给 LLM。

getWeather 函数从请求中提取用户的位置,并通过 Workers 的 Fetch API 调用外部天气 API 并返回结果。

带有 fetch() 的嵌入式函数调用示例
import { runWithTools } from "@cloudflare/ai-utils";
type Env = {
AI: Ai;
};
export default {
async fetch(request, env, ctx) {
// 定义函数
const getWeather = async (args: { numDays: number }) => {
const { numDays } = args;
// 根据 https://developers.cloudflare.com/workers/runtime-apis/request/#incomingrequestcfproperties 从请求中提取位置
const lat = request.cf?.latitude;
const long = request.cf?.longitude;
// 为外部 API 调用插值
const response = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${long}&daily=temperature_2m_max,precipitation_sum&timezone=GMT&forecast_days=${numDays}`,
);
return response.text();
};
// 使用函数调用运行 AI 推理
const response = await runWithTools(
env.AI,
// 支持函数调用的模型
"@hf/nousresearch/hermes-2-pro-mistral-7b",
{
// 消息
messages: [
{
role: "user",
content: "未来 5 天天气如何?以文本形式回应",
},
],
// AI 模型可以利用的可用工具的定义
tools: [
{
name: "getWeather",
description: "获取未来 [numDays] 天的天气",
parameters: {
type: "object",
properties: {
numDays: { type: "numDays", description: "天气预报的天数" },
},
required: ["numDays"],
},
// 引用先前定义的函数
function: getWeather,
},
],
},
);
return new Response(JSON.stringify(response));
},
} satisfies ExportedHandler<Env>;