Skip to content

非公式 / UnofficialCloudflare, Inc. 非提携。アカウント情報は入力しないでください。Not affiliated with Cloudflare, Inc. Do not enter Cloudflare credentials here.Official docsこのサイトについてプライバシー

独自の生成モデルを使う

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

デフォルトでは、AI Search は Workers AI モデルで応答を生成します。Workers AI 以外のモデルを使う場合は、AI Search を search に使い、取得したコンテンツを別のモデルへ渡して生成します。このガイドでは OpenAI モデルを使います。

前提条件

  1. Cloudflare アカウント ↗ に登録します。
  2. Node.js ↗ をインストールします。

Node.js のバージョンマネージャー

権限の問題を避け、Node.js のバージョンを切り替えられるよう、Volta ↗ や nvm ↗ などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。

次のものも必要です。

  • すでにインデックス済みコンテンツがある AI Search インスタンス。作成とコンテンツ追加は はじめに を参照してください。
  • OpenAI API キー ↗。

1. Worker プロジェクトを作成する

create-cloudflare CLI(C3)で新しい Worker プロジェクトを作成します。C3 ↗ は、Cloudflare への新規アプリケーションのセットアップとデプロイを助けるコマンドラインツールです。

次を実行して、byo-model という名前のプロジェクトを作成します。

npm create cloudflare@latest -- byo-model

セットアップでは、次のオプションを選びます。

  • What would you like to start with? では、Hello World example を選びます。
  • Which template would you like to use? では、Worker only を選びます。
  • Which language do you want to use? では、TypeScript を選びます。
  • Do you want to use git for version control? では、Yes を選びます。
  • Do you want to deploy your application? では、No を選びます(デプロイ前にいくつか変更します)。

アプリケーションディレクトリへ移動します。

cd byo-model

2. AI SDK と OpenAI プロバイダーをインストールする

AI SDK ↗ とその OpenAI プロバイダーをインストールします。

npm i ai @ai-sdk/openai

3. Worker をバインドし、API キーを設定する

Wrangler 設定ファイル に AI Search バインディングを追加します。

{
  "$schema": "./node_modules/wrangler/config-schema.json",
  "ai_search_namespaces": [
    {
      "binding": "AI_SEARCH",
      "namespace": "default",
      "remote": true
    }
  ]
}
[[ai_search_namespaces]]
binding = "AI_SEARCH"
namespace = "default"
remote = true

OpenAI API キーを シークレット として保存します。

npx wrangler secret put OPENAI_API_KEY

ローカル開発では、代わりにプロジェクトルートの .dev.vars ファイルにキーを追加します。

.dev.varstxt
OPENAI_API_KEY="<YOUR_OPENAI_API_KEY>"

4. コードを追加する

src/index.ts を更新します。この Worker はインスタンスを検索し、取得したチャンクを整形して、OpenAI へ渡して回答を生成します。my-instance を自分のインスタンス名に置き換えます。

src/index.jsjs
import { createOpenAI } from "@ai-sdk/openai";
import { generateText } from "ai";

export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		const userQuery = url.searchParams.get("query") ?? "What is Cloudflare?";

		// Search for documents in AI Search.
		const searchResult = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: userQuery }],
		});

		if (searchResult.chunks.length === 0) {
			return Response.json({ text: `No data found for query "${userQuery}"` });
		}

		// Join the retrieved chunks into a single string.
		const chunks = searchResult.chunks
			.map((chunk) => `<file name="${chunk.item.key}">${chunk.text}</file>`)
			.join("\n\n");

		// Send the query and retrieved content to OpenAI for the answer.
		const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY });
		const generateResult = await generateText({
			model: openai("gpt-4o-mini"),
			messages: [
				{
					role: "system",
					content:
						"You are a helpful assistant. Answer the user question using the provided files.",
				},
				{ role: "user", content: chunks },
				{ role: "user", content: userQuery },
			],
		});

		return Response.json({ text: generateResult.text });
	},
};
src/index.tsts
import { createOpenAI } from "@ai-sdk/openai";
import { generateText } from "ai";

export interface Env {
	AI_SEARCH: AiSearchNamespace;
	OPENAI_API_KEY: string;
}

export default {
	async fetch(request, env): Promise<Response> {
		const url = new URL(request.url);
		const userQuery = url.searchParams.get("query") ?? "What is Cloudflare?";

		// Search for documents in AI Search.
		const searchResult = await env.AI_SEARCH.get("my-instance").search({
			messages: [{ role: "user", content: userQuery }],
		});

		if (searchResult.chunks.length === 0) {
			return Response.json({ text: `No data found for query "${userQuery}"` });
		}

		// Join the retrieved chunks into a single string.
		const chunks = searchResult.chunks
			.map((chunk) => `<file name="${chunk.item.key}">${chunk.text}</file>`)
			.join("\n\n");

		// Send the query and retrieved content to OpenAI for the answer.
		const openai = createOpenAI({ apiKey: env.OPENAI_API_KEY });
		const generateResult = await generateText({
			model: openai("gpt-4o-mini"),
			messages: [
				{
					role: "system",
					content:
						"You are a helpful assistant. Answer the user question using the provided files.",
				},
				{ role: "user", content: chunks },
				{ role: "user", content: userQuery },
			],
		});

		return Response.json({ text: generateResult.text });
	},
} satisfies ExportedHandler<Env>;

5. 実行してデプロイする

ローカル開発サーバーを起動し、/?query=your+search+terms でクエリします。

npx wrangler dev

Cloudflare アカウントでログインしてから Worker をデプロイし、インターネットからアクセスできるようにします。

npx wrangler login
npx wrangler deploy

次のステップ

モデル

AI Gateway 経由でサードパーティモデルをネイティブに使います。

役に立ちましたか?