> ## 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로 구축한 에이전트를 자동으로 트레이스하며, 각 에이전트 호출, 하위 에이전트 핸드오프, 모델 Call, 도구 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로 구축한 멀티턴 리서치 에이전트를 실행하여, Agent Lens가 세션 전체에서 발생하는 모든 에이전트 호출, 모델 Call, 도구 Call을 캡처하도록 하는 방법을 설명합니다.

    <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`)와 통합되어 에이전트 실행을 자동으로 트레이스합니다. `@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">
    프로젝트에 `weave.init`를 추가하고 Forge 팀 이름과 프로젝트 이름을 지정한 다음, 평소처럼 에이전트를 구축하세요. 다음 코드는 `wikipedia_search` 함수 도구와 `Research assistant` 에이전트를 정의한 뒤, OpenAI Agents SDK `Runner`로 세 가지 질문을 실행하며 그동안 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())
    ```

    이 예시는 하나의 대화에서 세 개의 턴을 실행합니다. 처음 두 턴은 Wikipedia 조회를 트리거하고, 세 번째 턴은 도구 Call 없이 이전 대화 컨텍스트를 바탕으로 요약을 생성합니다. `Runner.run`을 호출할 때마다 이전 결과의 입력 목록을 다음 요청으로 다시 전달해 대화를 이어 갑니다. 또한 모든 호출이 동일한 `group_id`를 공유하므로 Agent Lens는 세 턴을 **Conversations** 탭에서 하나의 대화로 묶어 표시합니다. 공유된 `group_id`가 없으면 각 턴은 자체 트레이스 ID를 대신 사용하므로 각각 별도의 대화로 표시됩니다.
  </Tab>

  <Tab title="TypeScript">
    `@openai/agents`를 임포트하면 Weave가 모듈 로더 훅을 통해 해당 패키지를 자동으로 계측합니다. 필요한 설정은 모듈 시스템에 따라 조금씩 다릅니다. CommonJS와 ESM의 차이점, 그리고 Weave의 로더 훅이 작동하는 방식에 대한 자세한 내용은 [TypeScript SDK 서드파티 인테그레이션 가이드](/ko/products/wandb/weave/guides/integrations/js)를 참조하세요.

    * **CommonJS 프로젝트**: 추가 설정은 필요하지 않습니다. 자동 계측이 먼저 실행되도록 `@openai/agents`보다 `weave`를 먼저 require하세요.
    * **ESM 프로젝트**: 계측이 다른 모든 모듈보다 먼저 로드되도록 `--import=weave/instrument` 플래그를 지정하여 Node를 시작하세요.

    다음 코드는 `wikipedia_search` 도구와 `Research assistant` 에이전트를 정의한 후, SDK의 `Runner`로 세 가지 질문을 실행하고 Agent Lens가 그 트레이스를 캡처합니다. 각 `run()` Call은 별도의 최상위 트레이스로 기록되므로, 이 예시에서는 공유 `groupId`를 지정한 `Runner`를 하나 생성해 세 번의 Call에서 모두 재사용합니다. 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();
    ```

    이 예시는 하나의 대화에서 세 개의 턴을 실행합니다. 처음 두 턴은 Wikipedia 조회를 트리거하고, 세 번째 턴은 이전 대화 컨텍스트를 바탕으로 도구 호출 없이 요약을 생성합니다. `runner.run`을 호출할 때마다 이전 결과의 `history`를 다음 입력으로 다시 전달하여 대화를 이어 갑니다. 또한 모든 호출이 동일한 `groupId`를 공유하므로 Agent Lens는 Conversations 탭에서 세 턴을 모두 하나의 세션으로 묶어 표시합니다.

    예시를 `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).
