跳转到内容
搜索文档

使用 KV API

最后更新 查看 MarkdownAgent 设置

与持久存储交互以检索或存储信息可实现强大的用例。

在本示例中,我们展示嵌入式 function calling 如何仅用几行代码与 Cloudflare Developer Platform 上的其他资源交互。

前提条件

要使此示例正常工作,你需要先配置 KV namespace。请按照 KV - 快速入门 指南操作。

重要的是,必须更新 Wrangler 文件以包含指向相应 namespace 的 KV 绑定(binding)定义。

Worker 代码

Embedded function calling example with KV APIts
import { runWithTools } from "@cloudflare/ai-utils";

type Env = {
	AI: Ai;
	KV: KVNamespace;
};

export default {
	async fetch(request, env, ctx) {
		// Define function
		const updateKvValue = async ({
			key,
			value,
		}: {
			key: string;
			value: string;
		}) => {
			const response = await env.KV.put(key, value);
			return `Successfully updated key-value pair in database: ${response}`;
		};

		// Run AI inference with function calling
		const response = await runWithTools(
			env.AI,
			"@hf/nousresearch/hermes-2-pro-mistral-7b",
			{
				messages: [
					{ role: "system", content: "Put user given values in KV" },
					{ role: "user", content: "Set the value of banana to yellow." },
				],
				tools: [
					{
						name: "KV update",
						description: "Update a key-value pair in the database",
						parameters: {
							type: "object",
							properties: {
								key: {
									type: "string",
									description: "The key to update",
								},
								value: {
									type: "string",
									description: "The value to update",
								},
							},
							required: ["key", "value"],
						},
						function: updateKvValue,
					},
				],
			},
		);
		return new Response(JSON.stringify(response));
	},
} satisfies ExportedHandler<Env>;

验证结果

要验证结果,运行以下命令

npx wrangler kv key get banana --binding KV --local

这篇文档对您有帮助吗?