Skip to content

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

Workers AI を使ったコードインタープリター

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

Workers AI 上の gpt-oss モデル に、Cloudflare Sandbox SDK を使って Python コードを実行する能力を与える、コードインタープリターを構築します。

所要時間: 15 分

作成するもの

自然言語のプロンプトを受け取り、Python コードの実行が必要かを GPT-OSS が判断し、分離されたサンドボックスでコードを実行し、AI による説明付きで結果を返す Cloudflare Worker です。

前提条件

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

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

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

次も必要です。

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

新しい Sandbox SDK プロジェクトを作成します。

npm create cloudflare@latest -- workers-ai-interpreter --template=cloudflare/sandbox-sdk/examples/code-interpreter
cd workers-ai-interpreter

2. 実装を確認する

テンプレートには、最新のベストプラクティスを使った実装がすべて含まれています。主要な構成要素を確認します。

// src/index.ts
import { getSandbox } from "@cloudflare/sandbox";
import { generateText, stepCountIs, tool } from "ai";
import { createWorkersAI } from "workers-ai-provider";
import { z } from "zod";

const MODEL = "@cf/openai/gpt-oss-120b" as const;

async function handleAIRequest(input: string, env: Env): Promise<string> {
	const workersai = createWorkersAI({ binding: env.AI });

	const result = await generateText({
		model: workersai(MODEL),
		messages: [{ role: "user", content: input }],
		tools: {
			execute_python: tool({
				description: "Execute Python code and return the output",
				inputSchema: z.object({
					code: z.string().describe("The Python code to execute"),
				}),
				execute: async ({ code }) => {
					return executePythonCode(env, code);
				},
			}),
		},
		stopWhen: stepCountIs(5),
	});

	return result.text || "No response generated";
}

REST API を直接呼ぶ場合と比べた主な改善点:

  • 公式パッケージ: 手動の API 呼び出しではなく workers-ai-provider を使います
  • Vercel AI SDK: 関数呼び出しを整理するため generateText() と tool() を使います
  • API キー不要: 環境変数ではなくネイティブの AI バインディングを使います
  • 型安全性: 適切な型付けによる完全な TypeScript サポート

3. 設定を確認する

テンプレートには適切な Wrangler 設定が含まれています。

{
  "name": "sandbox-code-interpreter-example",
  "main": "src/index.ts",
  // Set this to today's date
  "compatibility_date": "2026-11-14",
  "ai": {
    "binding": "AI"
  },
  "containers": [
    {
      "class_name": "Sandbox",
      "image": "./Dockerfile",
      "name": "sandbox",
      "max_instances": 1,
      "instance_type": "basic"
    }
  ],
  "durable_objects": {
    "bindings": [
      {
        "class_name": "Sandbox",
        "name": "Sandbox"
      }
    ]
  }
}
name = "sandbox-code-interpreter-example"
main = "src/index.ts"
# Set this to today's date
compatibility_date = "2026-11-14"

[ai]
binding = "AI"

[[containers]]
class_name = "Sandbox"
image = "./Dockerfile"
name = "sandbox"
max_instances = 1
instance_type = "basic"

[[durable_objects.bindings]]
class_name = "Sandbox"
name = "Sandbox"

設定のポイント:

  • AI バインディング: Workers AI モデルへ直接アクセスできます
  • コンテナ設定: Dockerfile でサンドボックスコンテナを構成します
  • Durable Objects: 状態管理付きの永続サンドボックスを提供します

4. ローカルでテストする

開発サーバーを起動します。

npm run dev

curl でテストします。

# Simple calculation
curl -X POST http://localhost:8787/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Calculate 5 factorial using Python"}'

# Complex operations
curl -X POST http://localhost:8787/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Use Python to find all prime numbers under 20"}'

# Data analysis
curl -X POST http://localhost:8787/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Create a list of the first 10 squares and calculate their sum"}'

5. デプロイする

Worker をデプロイします。

npx wrangler deploy

6. デプロイをテストする

より複雑なクエリを試します。

# Data visualization preparation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Generate sample sales data for 12 months and calculate quarterly totals"}'

# Algorithm implementation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Implement a binary search function and test it with a sorted array"}'

# Mathematical computation
curl -X POST https://workers-ai-interpreter.YOUR_SUBDOMAIN.workers.dev/run \
  -H "Content-Type: application/json" \
  -d '{"input": "Calculate the standard deviation of [2, 4, 4, 4, 5, 5, 7, 9]"}'

仕組み

  1. ユーザー入力: /run エンドポイントへ自然言語のプロンプトを送ります
  2. AI の判断: GPT-OSS は execute_python ツールを使える状態でプロンプトを受け取ります
  3. スマートな実行: モデルが Python コード実行の要否を判断します
  4. サンドボックス分離: コードは分離された Cloudflare Sandbox コンテナで実行されます
  5. AI による説明: 結果が AI の応答に統合され、最終出力になります

作成した内容

次の機能を持つコードインタープリターをデプロイしました。

  • ネイティブな Workers AI 連携: 公式の workers-ai-provider パッケージでシームレスに連携します
  • 関数呼び出し: Vercel AI SDK でツール定義と実行を整理します
  • 安全な実行: 分離されたサンドボックスコンテナで Python コードを実行します
  • 知的な応答: AI の推論とコード実行結果を組み合わせます

次のステップ

関連情報

役に立ちましたか?