Cloudflare Workers AIとLlama 3.3/QwenによるサーバーレスAI Function Callingおよびチャットボット実装

単にテキストの受け答えをするだけのAIチャットボットの時代は終わりました。最新のAIアプリケーションは、**Function Calling(ツール呼び出し)**を通じて外部APIの実行やD1データベースの検索を行う自律型エージェント(Autonomous Agent)へと進化しています。
Cloudflare Workers AIは、Llama 3.3 70B (@cf/meta/llama-3.3-70b-instruct-fp8-fast) や Qwen 2.5 72B (@cf/qwen/qwen2.5-72b-instruct) などのオープンモデルをエッジネットワーク上で直接提供し、ネイティブなFunction Calling APIをサポートしています。
本記事では、JSON Schemaに基づくツールの定義、エージェントループ(Agent Loop)の構築、Zodを用いた構造化JSON出力の検証方法について解説します。
要約
- サーバーレスエッジAI推論:
env.AI.run()の1行でLlama 3.3やQwen 2.5の推論をエッジPoPで実行可能。- Native Function Callingサポート:
toolsパラメータでJSON Schemaを渡すと、LLMが適切な関数名と引数を抽出して返却します。- Agent Loopパターン: ユーザー入力 -> LLM解析 -> ツール実行 -> 結果をコンテキストに追加 -> 最終回答生成の流れを制御。
TypeScript 実装例
export interface Env {
AI: Ai;
DB: D1Database;
}
const tools = [
{
name: "get_weather",
description: "指定した都市の天気を取得します。",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "都市名 (例: Tokyo)" },
},
required: ["location"],
},
},
];
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { prompt } = await request.json<{ prompt: string }>();
const messages: Array<any> = [
{ role: "user", content: prompt }
];
let response = await env.AI.run(
"@cf/meta/llama-3.3-70b-instruct-fp8-fast",
{ messages, tools }
);
if (response.tool_calls && response.tool_calls.length > 0) {
for (const toolCall of response.tool_calls) {
const toolResult = { location: toolCall.arguments.location, temp: "20C" };
messages.push({ role: "assistant", tool_calls: [toolCall] });
messages.push({ role: "tool", name: toolCall.name, content: JSON.stringify(toolResult) });
}
response = await env.AI.run(
"@cf/meta/llama-3.3-70b-instruct-fp8-fast",
{ messages }
);
}
return Response.json({ answer: response.response });
},
};
結論
Cloudflare Workers AIを利用することで、GPUサーバーの運用コストをかけずに、超低レイテンシかつ高機能なAIエージェントをサーバーレス環境で構築できます。