永続ストレージとやり取りして情報を取得・保存すると、強力なユースケースを実現できます。
この例では、埋め込み function calling が Cloudflare Developer Platform 上のほかのリソースと、数行のコードでやり取りできることを示します。
この例を動かすには、先に KV 名前空間を用意する必要があります。手順は KV - はじめに を参照してください。
重要な点として、Wrangler ファイルに、対象の名前空間向けの KV バインディング定義を追加する必要があります。
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