openai-agents について
OpenAI Agents SDKでJavaScriptおよびTypeScriptアプリを構築するためのスキルです。テキスト・音声エージェント、ツール利用、マルチエージェントの連携、検証、デプロイの方法を案内します。
主な機能
- 01テキストとリアルタイム音声エージェント
- 02スキーマ生成を伴うツール呼び出し
- 03マルチエージェントの引き継ぎと連携
- 04入出力ガードレール
- 05Zodによる構造化出力
- 06デプロイとデバッグのテンプレート
活用シーン
- 01ツールを呼び出すテキストエージェントの構築
- 02専門エージェント間でのリクエスト振り分け
- 03リアルタイム音声体験の作成
- 04エージェント操作への検証や人間による承認の追加
MCP 対応
MCPサーバー利用時のMCPトレーシングに関する問題を記載し、トレーシングの初期化を推奨しています。MCPサーバーの管理機能やクライアントに公開する機能は説明していません。
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill openai-agentsインストール後、Claude Code で/openai-agentsを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
LICENSEREADME.mdSKILL.json詳細
OpenAI Agents SDK スキル
OpenAI Agents SDK(JavaScript/TypeScript)を使用して AI アプリケーションを構築するための包括的なスキルです。テキストエージェント、リアルタイム音声エージェント、マルチエージェントワークフロー、本番環境へのデプロイパターンを網羅しています。
インストールとセットアップ
必要なパッケージをインストールします。
npm install @openai/agents zod@3
npm install @openai/agents-realtime # For voice agents
環境変数を設定します。
export OPENAI_API_KEY="your-api-key"
対応ランタイム:
- Node.js 22+
- Deno
- Bun
- Cloudflare Workers(実験的)
コアコンセプト
1. エージェント
指示とツールを備えた LLM です。
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Assistant',
instructions: 'You are helpful.',
tools: [myTool],
model: 'gpt-4o-mini',
});
2. ツール
エージェントが呼び出せる関数です。スキーマは自動生成されます。
import { tool } from '@openai/agents';
import { z } from 'zod';
const weatherTool = tool({
name: 'get_weather',
description: 'Get weather for a city',
parameters: z.object({
city: z.string(),
}),
execute: async ({ city }) => {
return `Weather in ${city}: sunny`;
},
});
3. ハンドオフ
マルチエージェントの委任です。
const specialist = new Agent({ /* ... */ });
const triageAgent = Agent.create({
name: 'Triage',
instructions: 'Route to specialists',
handoffs: [specialist],
});
4. ガードレール
安全性を確保するための入出力検証です。
const agent = new Agent({
inputGuardrails: [homeworkDetector],
outputGuardrails: [piiFilter],
});
5. 構造化出力
Zod を使用した型安全な応答です。
const agent = new Agent({
outputType: z.object({
sentiment: z.enum(['positive', 'negative', 'neutral']),
confidence: z.number(),
}),
});
テキストエージェント
基本的な使い方
import { run } from '@openai/agents';
const result = await run(agent, 'What is 2+2?');
console.log(result.finalOutput);
console.log(result.usage.totalTokens);
ストリーミング
const stream = await run(agent, 'Tell me a story', {
stream: true,
});
for await (const event of stream) {
if (event.type === 'raw_model_stream_event') {
const chunk = event.data?.choices?.[0]?.delta?.content || '';
process.stdout.write(chunk);
}
}
テンプレート:
templates/text-agents/agent-basic.tstemplates/text-agents/agent-streaming.ts
マルチエージェントのハンドオフ
特化型エージェントを作成し、エージェント間で処理を振り分けます。
const billingAgent = new Agent({
name: 'Billing',
handoffDescription: 'For billing and payment questions',
tools: [processRefundTool],
});
const techAgent = new Agent({
name: 'Technical',
handoffDescription: 'For technical issues',
tools: [createTicketTool],
});
const triageAgent = Agent.create({
name: 'Triage',
instructions: 'Route customers to the right specialist',
handoffs: [billingAgent, techAgent],
});
テンプレート:
templates/text-agents/agent-handoffs.ts
参考資料:
references/agent-patterns.md- LLM とコードによるオーケストレーション
ガードレール
入力ガードレール
処理前に入力を検証します。
const homeworkGuardrail: InputGuardrail = {
name: 'Homework Detection',
execute: async ({ input, context }) => {
const result = await run(guardrailAgent, input);
return {
tripwireTriggered: result.finalOutput.isHomework,
outputInfo: result.finalOutput,
};
},
};
const agent = new Agent({
inputGuardrails: [homeworkGuardrail],
});
出力ガードレール
応答をフィルタリングします。
const piiGuardrail: OutputGuardrail = {
name: 'PII Detection',
execute: async ({ agentOutput }) => {
const phoneRegex = /\b\d{3}[-. ]?\d{3}[-. ]?\d{4}\b/;
return {
tripwireTriggered: phoneRegex.test(agentOutput as string),
outputInfo: { detected: 'phone_number' },
};
},
};
テンプレート:
templates/text-agents/agent-guardrails-input.tstemplates/text-agents/agent-guardrails-output.ts
ヒューマン・イン・ザ・ループ
特定のアクションに承認を必須とします。
const refundTool = tool({
name: 'process_refund',
requiresApproval: true, // ← Requires human approval
execute: async ({ amount }) => {
return `Refunded $${amount}`;
},
});
// Handle approval requests
let result = await runner.run(input);
while (result.interruption) {
if (result.interruption.type === 'tool_approval') {
const approved = await promptUser(result.interruption);
result = approved
? await result.state.approve(result.interruption)
: await result.state.reject(result.interruption);
}
}
テンプレート:
templates/text-agents/agent-human-approval.ts
リアルタイム音声エージェント
音声エージェントの作成
import { RealtimeAgent, tool } from '@openai/agents-realtime';
const voiceAgent = new RealtimeAgent({
name: 'Voice Assistant',
instructions: 'Keep responses concise for voice',
tools: [weatherTool],
voice: 'alloy', // alloy, echo, fable, onyx, nova, shimmer
model: 'gpt-4o-realtime-preview',
});
ブラウザーセッション(React)
import { RealtimeSession } from '@openai/agents-realtime';
const session = new RealtimeSession(voiceAgent, {
apiKey: sessionApiKey, // From your backend!
transport: 'webrtc', // or 'websocket'
});
session.on('connected', () => console.log('Connected'));
session.on('audio.transcription.completed', (e) => console.log('User:', e.transcript));
session.on('agent.audio.done', (e) => console.log('Agent:', e.transcript));
await session.connect();
重要:メインの OPENAI_API_KEY をブラウザーに送信しないでください。サーバー側でエフェメラルセッショントークンを生成します。
音声エージェントのハンドオフ
音声エージェントのハンドオフには、次の制約があります。
- ハンドオフ中に音声は変更できません
- ハンドオフ中にモデルは変更できません
- 会話履歴は自動的に引き継がれます
const specialist = new RealtimeAgent({
voice: 'nova', // Must match parent
/* ... */
});
const triageAgent = new RealtimeAgent({
voice: 'nova',
handoffs: [specialist],
});
テンプレート:
templates/realtime-agents/realtime-agent-basic.tstemplates/realtime-agents/realtime-session-browser.tsxtemplates/realtime-agents/realtime-handoffs.ts
参考資料:
references/realtime-transports.md- WebRTC と WebSocket の比較
フレームワークとの統合
Cloudflare Workers(実験的)
import { Agent, run } from '@openai/agents';
export default {
async fetch(request: Request, env: Env) {
const { message } = await request.json();
process.env.OPENAI_API_KEY = env.OPENAI_API_KEY;
const agent = new Agent({
name: 'Assistant',
instructions: 'Be helpful and concise',
model: 'gpt-4o-mini',
});
const result = await run(agent, message, {
maxTurns: 5,
});
return new Response(JSON.stringify({
response: result.finalOutput,
tokens: result.usage.totalTokens,
}), {
headers: { 'Content-Type': 'application/json' },
});
},
};
制限事項:
- リアルタイム音声エージェントは利用できません
- CPU 時間制限(最大 30 秒)
- メモリ制限(128MB)
テンプレート:
templates/cloudflare-workers/worker-text-agent.tstemplates/cloudflare-workers/worker-agent-hono.ts
参考資料:
references/cloudflare-integration.md
Next.js App Router
// app/api/agent/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { Agent, run } from '@openai/agents';
export async function POST(request: NextRequest) {
const { message } = await request.json();
const agent = new Agent({
name: 'Assistant',
instructions: 'Be helpful',
});
const result = await run(agent, message);
return NextResponse.json({
response: result.finalOutput,
});
}
テンプレート:
templates/nextjs/api-agent-route.tstemplates/nextjs/api-realtime-route.ts
エラー処理(9 件以上のエラーを防止)
1. Zod スキーマの型エラー
エラー:ツールのパラメーターで型エラーが発生します。
回避策:スキーマをインラインで定義します。
// ❌ Can cause type errors
parameters: mySchema
// ✅ Works reliably
parameters: z.object({ field: z.string() })
出典:GitHub #188
2. MCP トレーシングエラー
エラー:MCP サーバーで「既存のトレースが見つかりません」と表示されます。
回避策:
import { initializeTracing } from '@openai/agents/tracing';
await initializeTracing();
出典:GitHub #580
3. MaxTurnsExceededError
エラー:エージェントが無限にループします。
解決策:maxTurns を増やすか、指示を改善します。
const result = await run(agent, input, {
maxTurns: 20, // Increase limit
});
// Or improve instructions
instructions: `After using tools, provide a final answer.
Do not loop endlessly.`
4. ToolCallError
エラー:ツールの実行に失敗します。
解決策:指数バックオフで再試行します。
for (let attempt = 1; attempt <= 3; attempt++) {
try {
return await run(agent, input);
} catch (error) {
if (error instanceof ToolCallError && attempt < 3) {
await sleep(1000 * Math.pow(2, attempt - 1));
continue;
}
throw error;
}
}
5. スキーマの不一致
エラー:出力が outputType と一致しません。
解決策:より高性能なモデルを使用するか、検証の指示を追加します。
const agent = new Agent({
model: 'gpt-4o', // More reliable than gpt-4o-mini
instructions: 'CRITICAL: Return JSON matching schema exactly',
outputType: mySchema,
});
すべてのエラー:references/common-errors.md を参照してください。
テンプレート:templates/shared/error-handling.ts
オーケストレーションパターン
LLM ベース
エージェントが自律的にルーティングを決定します。
const manager = Agent.create({
instructions: 'Analyze request and route to appropriate agent',
handoffs: [agent1, agent2, agent3],
});
メリット:適応性が高く、複雑な処理に対応できます
デメリット:予測しにくく、トークン消費量が多くなります
コードベース
明示的な制御フロー:
const summary = await run(summarizerAgent, text);
const sentiment = await run(sentimentAgent, summary.finalOutput);
if (sentiment.finalOutput.score < 0.3) {
await run(escalationAgent, text);
}
メリット:予測可能で、コストを抑えられます デメリット:柔軟性が低くなります
並列
複数のエージェントを同時に実行します:
const [summary, keywords, entities] = await Promise.all([
run(summarizerAgent, text),
run(keywordAgent, text),
run(entityAgent, text),
]);
テンプレート:templates/text-agents/agent-parallel.ts
参考資料:references/agent-patterns.md
デバッグとトレース
詳細なログ出力を有効にします:
process.env.DEBUG = '@openai/agents:*';
実行の詳細にアクセスします:
const result = await run(agent, input);
console.log('Tokens:', result.usage.totalTokens);
console.log('Turns:', result.history.length);
console.log('Current Agent:', result.currentAgent?.name);
テンプレート:templates/shared/tracing-setup.ts
このスキルを使用する場面
✅ 次の場合に使用します:
- マルチエージェントのワークフローを構築する
- 音声 AI アプリケーションを作成する
- ツール呼び出しパターンを実装する
- 入出力の検証(ガードレール)が必要
- 人間による承認ゲートが必要
- 複雑な AI タスクをオーケストレーションする
- Cloudflare Workers または Next.js にデプロイする
❌ 次の場合は使用しないでください:
- シンプルな OpenAI API 呼び出し(代わりに
openai-apiスキルを使用してください) - OpenAI 以外のモデルのみを使用する
- 大規模な本番環境の音声処理(LiveKit Agents を検討してください)
本番環境チェックリスト
-
OPENAI_API_KEYを環境シークレットとして設定する - すべてのエージェント呼び出しにエラー処理を実装する
- 安全性が重要なアプリケーションにガードレールを追加する
- デバッグ用のトレースを有効にする
- 暴走するコストを防ぐため、適切な
maxTurnsを設定する - コスト効率を高めるため、可能な場合は
gpt-4o-miniを使用する - レート制限を実装する
- コスト監視のためにトークン使用量を記録する
- ハンドオフのフローを十分にテストする
- API キーをブラウザーに絶対に公開しない(セッショントークンを使用する)
トークン効率
推定削減率:~60%
| タスク | スキルなし | スキルあり | 削減率 |
|---|---|---|---|
| マルチエージェントのセットアップ | ~12k トークン | ~5k トークン | 58% |
| 音声エージェント | ~10k トークン | ~4k トークン | 60% |
| エラーのデバッグ | ~8k トークン | ~3k トークン | 63% |
| 平均 | ~10k | ~4k | ~60% |
防止されたエラー:記録済みの9件の問題で、エラーを100%防止
テンプレート一覧
テキストエージェント(8):
agent-basic.ts- ツールを備えたシンプルなエージェントagent-handoffs.ts- マルチエージェントによるトリアージagent-structured-output.ts- Zod スキーマagent-streaming.ts- リアルタイムイベントagent-guardrails-input.ts- 入力検証agent-guardrails-output.ts- 出力フィルタリングagent-human-approval.ts- HITL パターンagent-parallel.ts- 並行実行
リアルタイムエージェント(3):
9. realtime-agent-basic.ts - 音声のセットアップ
10. realtime-session-browser.tsx - React クライアント
11. realtime-handoffs.ts - 音声の委任
フレームワーク統合(4):
12. worker-text-agent.ts - Cloudflare Workers
13. worker-agent-hono.ts - Hono フレームワーク
14. api-agent-route.ts - Next.js API
15. api-realtime-route.ts - Next.js 音声
ユーティリティ(2):
16. error-handling.ts - 包括的なエラー処理
17. tracing-setup.ts - デバッグ
参考資料
agent-patterns.md- オーケストレーション戦略common-errors.md- 回避策付きの9件のエラーrealtime-transports.md- WebRTC と WebSocket の比較cloudflare-integration.md- Workers の制限事項official-links.md- ドキュメントへのリンク
公式リソース
- ドキュメント:https://openai.github.io/openai-agents-js/
- GitHub:https://github.com/openai/openai-agents-js
- npm:https://www.npmjs.com/package/@openai/agents
- Issue:https://github.com/openai/openai-agents-js/issues
バージョン:SDK v0.2.1 最終確認日:2025-10-26 スキルの作成者:Jeremy Dawes (Jezweb) 本番環境でのテスト:済み