OpenAI Agents SDK TypeScript
import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant.',});
const result = await run( agent, 'Write a haiku about recursion in programming.',);
console.log(result.finalOutput);import { RealtimeAgent, RealtimeSession } from '@openai/agents/realtime';
const agent = new RealtimeAgent({ name: 'Assistant', instructions: 'You are a helpful assistant.',});
// Automatically connects your microphone and audio output in the browser via WebRTC.const session = new RealtimeSession(agent);await session.connect({ apiKey: '<client-api-key>',});TypeScript 版 OpenAI Agents SDK は、抽象化を最小限に抑えた軽量で使いやすいパッケージで、エージェント型の AI アプリを構築できます。これは、過去のエージェント実験である Swarm を本番運用向けにアップグレードしたもので、Python でも利用可能 です。Agents SDK にはごく少数の基本コンポーネントがあります:
- エージェント: instructions と tools を備えた LLM
- Agents as tools / ハンドオフ: 特定のタスクを他のエージェントに委譲可能
- ガードレール: エージェントへの入力を検証可能
TypeScript と組み合わせると、これらの基本コンポーネントはツールとエージェント間の複雑な関係を表現するのに十分強力で、急な学習曲線なしに実運用アプリケーションを構築できます。さらに、この SDK には組み込みの トレーシング が付属しており、エージェントフローを可視化・デバッグでき、評価やアプリ向けモデルのファインチューニングまで行えます。
Agents SDK を使う理由
Section titled “Agents SDK を使う理由”この SDK は 2 つの設計原則に基づいています:
- 使う価値があるだけの機能は備えるが、学習が速いように基本コンポーネントは少数にする
- そのままで十分よく動くが、挙動を細部までカスタマイズできる
主な機能は以下のとおりです:
- エージェントループ: ツール呼び出しを処理し、結果を LLM に返し、タスクが完了するまで継続
- TypeScript ファースト: 新しい抽象を学ばず、ネイティブな TypeScript の言語機能でエージェントをオーケストレーションおよび連鎖
- Agents as tools / ハンドオフ: 複数エージェント間での調整と委譲を可能にする強力な仕組み
- ガードレール: エージェント実行と並行して入力検証と安全性チェックを実行し、失敗時は早期に停止
- 関数ツール: 任意の TypeScript 関数を、自動スキーマ生成と Zod ベースの検証付きツールに変換
- MCP サーバーツール呼び出し: 関数ツールと同様に動作する組み込みの MCP サーバーツール連携
- セッション: エージェントループ内で作業コンテキストを維持する永続メモリ層
- Human in the loop (人間の介入): エージェントの実行全体で人間を関与させるための組み込みメカニズム
- トレーシング: ワークフローを可視化・デバッグ・監視するための組み込みトレーシング。OpenAI の評価、ファインチューニング、蒸留ツール群をサポート
- リアルタイムエージェント: 自動割り込み検知、コンテキスト管理、ガードレールなどの機能を備えた強力な音声エージェントを構築
インストール
Section titled “インストール”npm install @openai/agents zodこの SDK には Zod v4 が必要です。zod を npm でインストールすると、最新の v4 リリースが取得されます。
Hello World の例
Section titled “Hello World の例”import { Agent, run } from '@openai/agents';
const agent = new Agent({ name: 'Assistant', instructions: 'You are a helpful assistant',});
const result = await run( agent, 'Write a haiku about recursion in programming.',);console.log(result.finalOutput);
// Code within the code,// Functions calling themselves,// Infinite loop's dance.(これを実行する場合は、OPENAI_API_KEY 環境変数を設定してください)
export OPENAI_API_KEY=sk-...