> ## 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="/ko/products/agent-lens/integrations/openai-agents-sdk" />

OpenAI Agents SDK는 OpenAI의 API 위에 에이전트와 멀티 에이전트 워크플로를 구축하기 위한 경량 프레임워크입니다. Weave는 OpenAI Agents SDK로 구축된 에이전트를 자동으로 트레이스하며, 각 에이전트 호출, 하위 에이전트 handoff, 모델 Call 및 도구 Call을 포함합니다. Weave는 캡처된 데이터를 프로젝트의 **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로 구축한 멀티턴 리서치 에이전트를 실행하는 방법을 설명합니다. 이렇게 하면 Weave가 세션 전체에서 발생하는 모든 에이전트 호출, 모델 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는 [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를 사용할 수 있도록 개발 환경에 다음 패키지를 설치하세요.

<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">
    CoreWeave Forge 팀 이름과 프로젝트 이름을 지정하여 프로젝트에 `weave.init`을 추가한 다음, 평소처럼 에이전트를 구축하세요. 다음 코드는 `wikipedia_search` 함수 도구와 `Research assistant` 에이전트를 정의한 다음, OpenAI Agents SDK의 `Runner`로 세 가지 질문을 실행하며 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())
    ```

    이 예시는 하나의 대화에서 세 개의 턴을 실행합니다. 처음 두 턴은 Wikipedia 조회를 트리거하고, 세 번째 턴은 도구 Call 없이 이전 대화 컨텍스트를 사용하여 요약을 생성합니다. `Runner.run`을 호출할 때마다 이전 결과의 입력 목록을 다음 요청으로 다시 전달하여 대화를 이어갑니다.
  </Tab>

  <Tab title="TypeScript">
    Weave는 `@openai/agents`를 임포트할 때 모듈 로더 훅을 통해 자동으로 계측합니다. 필요한 설정은 모듈 시스템에 따라 조금씩 다릅니다. 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`로 세 가지 질문을 실행하며 Weave가 트레이스를 캡처합니다. 각 `run()` 호출은 별도의 최상위 트레이스로 기록되므로, 이 예시에서는 공유 `groupId`를 지정한 `Runner`를 생성하여 세 Call 모두에서 재사용합니다. 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();
    ```

    이 예시는 하나의 대화에서 세 턴을 실행합니다. 처음 두 턴은 위키백과 검색을 트리거하고, 세 번째 턴은 도구를 호출하지 않고 이전 대화의 맥락을 바탕으로 요약을 생성합니다. `runner.run`을 호출할 때마다 이전 결과의 `history`를 다음 입력으로 다시 전달해 대화를 이어가며, 모든 호출에서 동일한 `groupId`를 공유하므로 Weave는 Agents 뷰에서 세 턴을 하나의 세션으로 묶습니다.

    로더 훅이 다른 모든 모듈보다 먼저 실행되도록 예시를 `main.mjs`로 저장한 다음 `--import=weave/instrument` 플래그를 지정하여 실행하세요.

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

    <h3 id="manual-instrumentation">
      수동 계측
    </h3>

    수동 계측은 모듈 로더 훅을 실행할 수 없을 때만 필요합니다. 예를 들어 번들러가 의존성을 single file로 결합하는 경우, 노드 CLI 플래그를 지원하지 않는 환경, 또는 로더 훅을 우회하는 동적 모듈 로딩 패턴이 사용되는 경우입니다.

    계측을 명시적으로 등록하려면 `instrumentOpenAIAgents()`를 사용하세요:

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

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

    트레이싱 프로세서를 완전히 제어해야 하는 경우(예: 맞춤형 프로세서를 설정하거나 조건에 따라 등록하는 경우), 직접 생성하고 등록하세요:

    ```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()`이 프로젝트 링크를 출력합니다. **Agents** 뷰를 열어 다음을 확인하세요:

* 대화의 턴을 포함하는 세션.
* 중첩된 `chat` 및 `execute_tool` 하위 항목이 있는 `invoke_agent` span으로 표시되는 각 턴.
* 각 단계의 전체 입력, 모델, 출력, 토큰 사용량 및 도구 결과.

Weave에서 Agents 데이터를 확인하는 방법에 대한 자세한 내용은 [에이전트 활동 확인하기](/ko/products/wandb/weave/guides/tracking/view-agent-activity)를 참조하세요.
