Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

関数呼び出し

最終更新 Markdown で表示Agent セットアップ

関数呼び出し(Function calling)を使うと、大規模言語モデル(LLM)の応答をもとに関数を実行したり、外部 API と連携したりできます。開発者は通常、関数のセットと、各関数に必要な入力スキーマを定義します。これを tools と呼びます。モデルはツール呼び出しが必要なタイミングを判断し、別の関数や API に渡す JSON を返します。

つまり Function calling を使うと、コードの実行や追加の API 呼び出しによって、LLM でアクションを実行できます。

Function calling の使い方

Workers AI には、推論呼び出しとあわせて関数コードを実行できる 埋め込み Function calling があります。これを簡単にするためのパッケージ @cloudflare/ai-utils を公開しており、GitHub でオープンソースとして提供しています。

業界標準の Function calling については、従来型 Function calling のドキュメントを参照してください。

埋め込み Function calling の利点を示すため、従来型と埋め込み型を比較した例を次に示します。埋め込み Function calling では、コード量を 77 行から 31 行に削減できました。

# The ai-utils package enables embedded function calling
npm i @cloudflare/ai-utils
埋め込み Function calling の例js
import {
	createToolsFromOpenAPISpec,
	runWithTools,
	autoTrimTools,
} from "@cloudflare/ai-utils";

export default {
	async fetch(request, env, ctx) {
		const response = await runWithTools(
			env.AI,
			"@hf/nousresearch/hermes-2-pro-mistral-7b",
			{
				messages: [{ role: "user", content: "Who is Cloudflare on github?" }],
				tools: [
					// You can pass the OpenAPI spec link or contents directly
					...(await createToolsFromOpenAPISpec(
						"https://gist.githubusercontent.com/mchenco/fd8f20c8f06d50af40b94b0671273dc1/raw/f9d4b5cd5944cc32d6b34cad0406d96fd3acaca6/partial_api.github.com.json",
						{
							overrides: [
								{
									// for all requests on *.github.com, we'll need to add a User-Agent.
									matcher: ({ url, method }) => {
										return url.hostname === "api.github.com";
									},
									values: {
										headers: {
											"User-Agent":
												"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
										},
									},
								},
							],
						},
					)),
				],
			},
		).then((response) => {
			return response;
		});

		return new Response(JSON.stringify(response));
	},
};
従来型 Function calling の例js
export default {
	async fetch(request, env, ctx) {
		const response = await env.AI.run(
			"@hf/nousresearch/hermes-2-pro-mistral-7b",
			{
				messages: [{ role: "user", content: "Who is Cloudflare on GitHub?" }],
				tools: [
					{
						name: "getGithubUser",
						description:
							"Provides publicly available information about someone with a GitHub account.",
						parameters: {
							type: "object",
							properties: {
								username: {
									type: "string",
									description: "The handle for the GitHub user account.",
								},
							},
							required: ["username"],
						},
					},
				],
			},
		);

		const selected_tool = response.tool_calls[0];
		let res;

		if (selected_tool.name == "getGithubUser") {
			try {
				const username = selected_tool.arguments.username;
				const url = `https://api.github.com/users/${username}`;
				res = await fetch(url, {
					headers: {
						// Github API requires a User-Agent header
						"User-Agent":
							"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
					},
				}).then((res) => res.json());
			} catch (error) {
				return error;
			}
		}

		const finalResponse = await env.AI.run(
			"@hf/nousresearch/hermes-2-pro-mistral-7b",
			{
				messages: [
					{
						role: "user",
						content: "Who is Cloudflare on GitHub?",
					},
					{
						role: "assistant",
						content: JSON.stringify(selected_tool),
					},
					{
						role: "tool",
						content: JSON.stringify(res),
					},
				],
				tools: [
					{
						name: "getGithubUser",
						description:
							"Provides publicly available information about someone with a GitHub account.",
						parameters: {
							type: "object",
							properties: {
								username: {
									type: "string",
									description: "The handle for the GitHub user account.",
								},
							},
							required: ["username"],
						},
					},
				],
			},
		);
		return new Response(JSON.stringify(finalResponse));
	},
};

Function calling に対応するモデル

Function calling 向けにファインチューニングされたオープンソースモデルがあります。モデルカタログ を見るときは、Function calling の表示があるモデルを探してください。たとえば @hf/nousresearch/hermes-2-pro-mistral-7b は、Function calling に使える Mistral 7B のファインチューニング版です。

役に立ちましたか?