> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OpenAI Agents SDK

> Weave を使用して、OpenAI Agents SDK で構築したエージェントをトレースします。

export const AgentLensBanner = ({href}) => <Tip>
    <strong>This workflow is also available in CoreWeave Agent Lens.</strong> Agent Lens is the Forge experience built for tracing, monitoring, and analyzing AI agents, with automated insights into agent failures and user intents. It uses the same trace data as Weights & Biases Weave, so the traces you already send appear there with nothing to migrate.{' '}
    <a href={href || '/products/agent-lens'}>{href ? 'See how to do this in Agent Lens' : 'Learn about Agent Lens'}</a>.
  </Tip>;

<AgentLensBanner href="/ja/products/agent-lens/integrations/openai-agents-sdk" />

OpenAI Agents SDK は、OpenAI の API 上でエージェントやマルチエージェントのワークフローを構築するための軽量なフレームワークです。Weave は、OpenAI Agents SDK で構築されたエージェントを自動的にトレースし、各エージェントの invocation、サブエージェントへのハンドオフ、モデルの Call、ツール呼び出しを記録します。取得したデータは、プロジェクトの **Agents** ビューに表示されます。

<h2 id="trace-openai-agents-sdk-agents-with-weave">
  Weave で OpenAI Agents SDK のエージェントをトレースする
</h2>

<Tabs>
  <Tab title="Python">
    Weave SDK は [OpenAI Agents SDK for Python](https://github.com/openai/openai-agents-python) に自動でパッチを適用するため、最小限のセットアップでエージェントのトレースを取得できます。このガイドでは、Weave を初期化したうえで、OpenAI Agents SDK で構築したマルチターンのリサーチエージェントを実行し、セッション全体のすべてのエージェントの invocation、モデルの Call、ツール呼び出しを Weave で取得する方法を説明します。

    <h3 id="prerequisites">
      前提条件
    </h3>

    開始する前に、以下を用意してください。

    * CoreWeave Forge アカウントと、`WANDB_API_KEY` 環境変数に設定した [APIキー](https://forge.coreweave.com/settings#apikeys)。
    * [OpenAI APIキー](https://platform.openai.com/api-keys)。
    * Python 3.10 以降。
  </Tab>

  <Tab title="TypeScript">
    Weave は [OpenAI Agents Node SDK](https://github.com/openai/openai-agents-js) (`@openai/agents`) と連携し、エージェントの run を自動的にトレースします。`@openai/agents` のバージョン `0.4.15` 以降が必要です。

    <h3 id="prerequisites-2">
      前提条件
    </h3>

    開始する前に、以下を用意してください。

    * CoreWeave Forge アカウントと、`WANDB_API_KEY` 環境変数に設定した [APIキー](https://forge.coreweave.com/settings#apikeys)。
    * [OpenAI APIキー](https://platform.openai.com/api-keys)。
    * Node.js 18 以降。
  </Tab>
</Tabs>

<h3 id="install-packages">
  パッケージのインストール
</h3>

Weave と SDK をスクリプトで利用できるように、開発環境に以下の packages をインストールしてください。

<CodeGroup>
  ```bash Python theme={"system"}
  pip install weave openai-agents requests
  ```

  ```bash TypeScript theme={"system"}
  npm install weave @openai/agents zod
  ```
</CodeGroup>

<h3 id="initialize-weave-in-your-code">
  コードで Weave を初期化する
</h3>

<Tabs>
  <Tab title="Python">
    `weave.init` を project に追加し、CoreWeave Forge のチーム名と project 名を指定してから、通常どおりエージェントを構築します。以下のコードは `wikipedia_search` 関数ツールと `Research assistant` エージェントを定義し、OpenAI Agents SDK の `Runner` を通じて3つの質問を実行します。その間、Weave がトレースを取得します。

    ```python lines  highlight="6" theme={"system"}
    import asyncio
    import requests
    import weave
    from agents import Agent, Runner, function_tool

    weave.init("<your-team>/<your-project-name>")

    @function_tool
    def wikipedia_search(query: str) -> str:
        """Search Wikipedia for a topic and return its title and intro paragraph."""
        r = requests.get(
            "https://en.wikipedia.org/w/api.php",
            params={
                "action": "query", "generator": "search", "gsrsearch": query, "gsrlimit": 1,
                "prop": "extracts", "exintro": True, "explaintext": True, "format": "json",
            },
            headers={"User-Agent": "weave-demo"},
        ).json()
        page = next(iter(r["query"]["pages"].values()))
        return f"{page['title']}: {page['extract']}"

    agent = Agent(
        name="Research assistant",
        instructions=(
            "You are a research assistant. Use the wikipedia_search tool to look up "
            "topics when needed, and cite the article titles you used."
        ),
        tools=[wikipedia_search],
    )

    async def main():
        history = []
        for question in [
            "Who founded Anthropic?",
            "What is Claude (the AI assistant)?",
            "Summarize what we discussed in one sentence.",
        ]:
            history.append({"role": "user", "content": question})
            print(f"USER: {question}")
            result = await Runner.run(agent, input=history)
            print(f"AGENT: {result.final_output}\n")
            history = result.to_input_list()

    asyncio.run(main())
    ```

    この例では、1つの会話で3つのターンを実行します。最初の2つのターンはWikipediaルックアップをトリガーし、3つ目は前の会話コンテキストを使用して、ツール呼び出しなしで要約を生成します。`Runner.run` への各呼び出しは、前の結果の入力リストを次のリクエストとして渡すことで会話を継続します。
  </Tab>

  <Tab title="TypeScript">
    Weave は、`@openai/agents` がインポートされると、モジュールローダーフックを介して自動的にインストルメントします。必要なセットアップはモジュールシステムによって若干異なります。CommonJS と ESM の違い、および Weave のローダーフックの仕組みの詳細については、[TypeScript SDK サードパーティ統合ガイド](/ja/products/wandb/weave/guides/integrations/js)を参照してください。

    * **CommonJS project**: 追加の設定は必要ありません。`weave` を `@openai/agents` より先に require して、自動インストルメンテーションが最初に実行されるようにしてください。
    * **ESM project**: Node を `--import=weave/instrument` フラグ付きで起動して、インストルメンテーションが他のモジュールより先にロードされるようにしてください。

    以下のコードは `wikipedia_search` ツールと `Research assistant` エージェントを定義し、Weave がトレースをキャプチャしながら SDK の `Runner` を通じて 3 つの質問を実行します。各 `run()` 呼び出しは個別のトップレベル トレースとしてトレースされるため、この例では共有 `groupId` を持つ `Runner` を作成し、3 回の呼び出しすべてで再利用します。Weave は `groupId` を使用して同じ会話からのトレースをグループ化し、`groupId` が設定されていない場合は各トレース独自の ID にフォールバックします。

    ```typescript lines  highlight="33" title="main.mjs" theme={"system"}
    import { randomUUID } from "node:crypto";
    import * as weave from "weave";
    import { Agent, Runner, tool, type AgentInputItem } from "@openai/agents";
    import { z } from "zod";

    const wikipediaSearch = tool({
        name: "wikipedia_search",
        description: "Search Wikipedia for a topic and return its title and intro paragraph.",
        parameters: z.object({
        query: z.string().describe("The topic to search for"),
        }),
        async execute({ query }) {
        const url = new URL("https://en.wikipedia.org/w/api.php");
        url.search = new URLSearchParams({
            action: "query",
            generator: "search",
            gsrsearch: query,
            gsrlimit: "1",
            prop: "extracts",
            exintro: "true",
            explaintext: "true",
            format: "json",
        }).toString();

        const response = await fetch(url, { headers: { "User-Agent": "weave-demo" } });
        const data = await response.json();
        const page = Object.values(data.query.pages)[0] as { title: string; extract: string };
        return `${page.title}: ${page.extract}`;
        },
    });

    async function main() {
        await weave.init("<your-team>/<your-project-name>");

        const agent = new Agent({
        name: "Research assistant",
        instructions:
            "You are a research assistant. Use the wikipedia_search tool to look up " +
            "topics when needed, and cite the article titles you used.",
        tools: [wikipediaSearch],
        });

        const runner = new Runner({ groupId: randomUUID() });

        const questions = [
        "Who founded Anthropic?",
        "What is Claude (the AI assistant)?",
        "Summarize what we discussed in one sentence.",
        ];

        let history: AgentInputItem[] = [];
        for (const question of questions) {
        history.push({ role: "user", content: question });
        console.log(`USER: ${question}`);
        const result = await runner.run(agent, history);
        console.log(`AGENT: ${result.finalOutput}\n`);
        history = result.history;
        }
    }

    main();
    ```

    この例では、1 つの会話で 3 ターンが実行されます。最初の 2 ターンは Wikipedia のルックアップをトリガーし、3 番目のターンは以前の会話のコンテキストを使用して、ツール呼び出しなしで要約を生成します。`runner.run` への各呼び出しは、前の結果の `history` を次の入力として渡すことで会話を継続し、同じ `groupId` を共有するため、Weave は 3 つのターンを Agents ビュー内の 1 つのセッションにグループ化します。

    例を `main.mjs` として保存し、`--import=weave/instrument` フラグを付けて実行します。これにより、ローダーフックが他のどのモジュールよりも先に実行されます:

    ```bash theme={"system"}
    node --import=weave/instrument main.mjs
    ```

    <h3 id="manual-instrumentation">
      手動インストルメンテーション
    </h3>

    手動インストルメンテーションが必要となるのは、モジュールローダーフックが実行できない場合のみです。たとえば、依存関係を単一のファイルにまとめるバンドラーを使用する場合、Node CLI フラグをサポートしない環境、またはローダーフックをバイパスする動的なモジュール読み込みパターンの場合などです。

    `instrumentOpenAIAgents()` を使用して、インストルメンテーションを明示的に登録します：

    ```typescript lines theme={"system"}
    import * as weave from "weave";

    await weave.init("<your-team>/<your-project-name>");
    await weave.instrumentOpenAIAgents();
    ```

    tracing processor に対してフルコントロールが必要な場合 (例: カスタム processor を設定したり、条件付きで登録したりする場合) には、直接作成して登録してください：

    ```typescript lines theme={"system"}
    import { addTraceProcessor } from "@openai/agents";
    import { createOpenAIAgentsTracingProcessor } from "weave";

    const processor = createOpenAIAgentsTracingProcessor();
    addTraceProcessor(processor);
    ```
  </Tab>
</Tabs>

<h3 id="see-your-agent-traces-in-the-agents-view">
  Agents ビューでエージェントのトレースを確認する
</h3>

スクリプトを実行すると、`weave.init()` によって project へのリンクが出力されます。**Agents** ビューを開くと、次の内容を確認できます。

* 会話のターンを含むセッション
* `invoke_agent` スパンとしてレンダリングされた各ターン (子として `chat` と `execute_tool` がネストされます)
* 各ステップの入力、モデル、出力、トークン使用量、ツール結果の全容

Weave で Agents データを表示する方法の詳細については、[エージェントのアクティビティを表示する](/ja/products/wandb/weave/guides/tracking/view-agent-activity)を参照してください。
