← Cloudflare Workers AI / workers-ai / features / function-calling / embedded / examples
Použití KV API
Interakce s trvalým úložištěm pro načítání nebo ukládání informací umožňuje výkonné případy použití.
Na tomto příkladu ukážeme, jak může vestavěné volání funkcí pomocí několika řádků kódu komunikovat s dalšími prostředky na Cloudflare Developer Platform.
Předpoklady
Aby tento příklad fungoval, musíte nejprve vytvořit KV jmenný prostor. Postupujte podle KV - Get started návod.
Je důležité, aby byl váš soubor Wrangler aktualizován a obsahoval KV definici vazby do příslušného jmenného prostoru.
Kód Workeru
Příklad embedded function calling s KV API
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>;Ověřte výsledky
Chcete-li ověřit výsledky, spusťte následující příkaz
npx wrangler kv key get banana --binding KV --local