KV APIの使用
永続的なストレージと対話して情報を取得または保存することは、強力なユースケースを可能にします。
この例では、埋め込み関数呼び出しがCloudflare Developer Platform上の他のリソースとどのように対話できるかを数行のコードで示します。
この例を機能させるためには、まずKV名前空間をプロビジョニングする必要があります。そのためには、KV - はじめにガイドに従ってください。
重要なことに、wrangler.tomlファイルは、各自の名前空間に対するKVバインディング定義を含むように更新する必要があります。
import { runWithTools } from "@cloudflare/ai-utils";
type Env = { AI: Ai; KV: KVNamespace;};
export default { async fetch(request, env, ctx) { // 関数を定義 const updateKvValue = async ({ key, value, }: { key: string; value: string; }) => { const response = await env.KV.put(key, value); return `データベースのキーと値のペアを正常に更新しました: ${response}`; };
// 関数呼び出しでAI推論を実行 const response = await runWithTools( env.AI, "@hf/nousresearch/hermes-2-pro-mistral-7b", { messages: [ { role: "system", content: "ユーザーが指定した値をKVに入れてください" }, { role: "user", content: "バナナの値を黄色に設定してください。" }, ], tools: [ { name: "KV更新", description: "データベースのキーと値のペアを更新します", parameters: { type: "object", properties: { key: { type: "string", description: "更新するキー", }, value: { type: "string", description: "更新する値", }, }, required: ["key", "value"], }, function: updateKvValue, }, ], }, ); return new Response(JSON.stringify(response)); },} satisfies ExportedHandler<Env>;結果を確認するには、次のコマンドを実行します。
npx wrangler kv:key get banana --binding KV --local