> ## 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

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

OpenAI Agents SDK は、OpenAI の API 上でエージェントやマルチエージェントのワークフローを構築するための軽量なフレームワークです。CoreWeave Agent Lens は、OpenAI Agents SDK で構築されたエージェントを自動的にトレースします。トレース対象には、エージェントの各 invocation、サブエージェントへのハンドオフ、モデルの Call、ツール呼び出しが含まれます。

<Note>
  This integration uses the Weights & Biases Weave SDK (`weave`), because the CoreWeave Forge SDK doesn't support this framework yet. Traces you send with Weave appear in Agent Lens, because both products share the same trace data.
</Note>

<h2 id="trace-openai-agents-sdk-agents-with-agent-lens">
  Agent Lens で 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、ツール呼び出しを Agent Lens で取得する方法を説明します。

    <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 SDK は [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 と OpenAI Agents SDK を使用できるように、開発環境に次のパッケージをインストールします。

<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-agent-lens-in-your-code">
  コードで Agent Lens を初期化する
</h3>

<Tabs>
  <Tab title="Python">
    Forge のチーム名とプロジェクト名を指定して `weave.init` をプロジェクトに追加し、あとは通常どおりエージェントを構築します。次のコードでは、`wikipedia_search` 関数ツールと `Research assistant` エージェントを定義し、OpenAI Agents SDK の `Runner` で 3 つの質問を実行しながら、Agent Lens でトレースを取得します。`Runner.run` は呼び出しごとに個別のトレースを開始するため、この例では各呼び出しに共通の `group_id` を指定した `RunConfig` を渡しています。Weave は `group_id` を使用して同じ会話のトレースをグループ化します。`group_id` が設定されていない場合は、各トレース自体の ID が代わりに使用されます。

    ```python lines  highlight="7,33,42" theme={"system"}
    import asyncio
    import uuid
    import requests
    import weave
    from agents import Agent, RunConfig, Runner, function_tool

    weave.init("[YOUR-TEAM]/[YOUR-PROJECT]")

    @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():
        run_config = RunConfig(group_id=str(uuid.uuid4()))
        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, run_config=run_config)
            print(f"AGENT: {result.final_output}\n")
            history = result.to_input_list()

    asyncio.run(main())
    ```

    この例では、1 つの会話の中で 3 つのターンを実行します。最初の 2 つのターンでは Wikipedia のルックアップがトリガーされ、3 つ目のターンではツールを呼び出さずに、それまでの会話のコンテキストを使用して要約を生成します。`Runner.run` を呼び出すたびに、前回の結果の入力リストを次のリクエストとして渡すことで会話を継続します。また、すべての呼び出しで同じ `group_id` を共有するため、Agent Lens は 3 つのターンすべてを **Conversations** タブ内の 1 つの会話としてグループ化します。`group_id` を共有しない場合、各ターンはそれぞれ独自のトレース ID にフォールバックし、個別の会話として表示されます。
  </Tab>

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

    * **CommonJS プロジェクト**: 追加の設定は不要です。自動インストルメンテーションが最初に実行されるように、`@openai/agents` より前に `weave` を require します。
    * **ESM プロジェクト**: インストルメンテーションが他のモジュールより先に読み込まれるように、`--import=weave/instrument` フラグを付けて Node を起動します。

    次のコードでは、`wikipedia_search` ツールと `Research assistant` エージェントを定義し、SDK の `Runner` を通じて 3 つの質問を実行します。その間、Agent Lens がトレースを取得します。`run()` の呼び出しはそれぞれ独立したトップレベルのトレースとして記録されるため、この例では共通の `groupId` を指定した `Runner` を作成し、3 つの呼び出しすべてで再利用しています。Agent Lens は `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]");

        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` を共有します。これにより、Agent Lens は 3 つのターンすべてを Conversations タブで 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]");
    await weave.instrumentOpenAIAgents();
    ```

    カスタムプロセッサを設定したり、条件に応じて登録したりするなど、トレースプロセッサを完全に制御する必要がある場合は、次のようにプロセッサを直接作成して登録します：

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

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

### View your traces in Agent Lens

After the script runs, `weave.init()` prints a link to your project in Weave. The same traces appear in Agent Lens, because both products share the same trace data. To view them in Agent Lens:

1. Navigate to [CoreWeave Forge](https://forge.coreweave.com) and select **Agent Lens** from the product menu.
2. Select your project.
3. In the Agent Lens side menu, select **Conversations**, and then select your conversation.

Each turn renders as an `invoke_agent` span with nested `chat` and `execute_tool` spans. Each span shows its input, model, output, token usage, and tool results.

For more information, see [View agent activity](/products/agent-lens/conversations/view-activity).
