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

> CoreWeave Forge SDK를 사용해 Agent Lens에서 OpenAI SDK Call을 트레이스하세요.

CoreWeave Forge SDK는 Python 및 Node.js용 OpenAI SDK로 수행하는 Call을 자동으로 트레이스합니다. 트레이싱을 초기화하면 대화 안에서 수행하는 각 Call이 Agent Lens에 LLM span으로 기록됩니다. 이때 메시지, 도구 Call, 요청 설정, 그리고 캐시된 토큰과 추론 토큰을 포함한 토큰 사용량도 함께 기록됩니다. OpenAI SDK를 호출하는 방식은 바꿀 필요가 없습니다.

이 인테그레이션은 Chat Completion(스트리밍 포함), 구조화된 출력 파싱, Responses API(스트리밍 포함), 이미지 생성을 트레이스합니다.

<h2 id="prerequisites">
  사전 요구 사항
</h2>

* CoreWeave Forge 계정 및 `WANDB_API_KEY` 환경 변수로 설정한 [API 키](https://forge.coreweave.com/settings#apikeys)
* `OPENAI_API_KEY` 환경 변수로 설정한 [OpenAI API 키](https://platform.openai.com/api-keys)
* Python: Python 3.10 이상 및 `openai` 1.99.9 이상
* TypeScript: Node.js 18.19 이상(또는 20.6 이상) 및 `openai` 4.0.0 이상

<h2 id="install-packages">
  패키지 설치
</h2>

<CodeGroup>
  ```bash Python theme={"system"}
  pip install "coreweave[openai]"
  ```

  ```bash TypeScript theme={"system"}
  npm install @coreweave/forge-sdk openai
  ```
</CodeGroup>

<h2 id="trace-openai-conversations">
  OpenAI 대화 트레이싱
</h2>

Forge 팀 이름과 프로젝트 이름을 지정해 `tracing.init()`을 호출하세요. Python에서는 OpenAI SDK를 이 호출 전후 언제 임포트하든 `tracing.init()`이 OpenAI SDK를 패치합니다. TypeScript에서는 TypeScript 탭에 나온 계측 플래그를 사용해 Node를 시작하세요.

Agent Lens에는 대화 안에서 실행된 Call만 표시됩니다. 대화 밖에서 수행된 Call에는 대화 ID가 없으므로 Agent Lens에 나타나지 않습니다. 에이전트 세션마다 대화를 하나씩 생성하고, 사용자 메시지마다 턴을 시작하세요. 모든 턴이 대화의 ID를 공유하므로 Agent Lens는 이 턴들을 하나의 대화로 묶고, 각 Call은 자신이 실행된 턴의 LLM span이 됩니다.

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    from openai import OpenAI
    from coreweave.forge.agentlens import tracing

    tracing.init("[YOUR-TEAM]/[YOUR-PROJECT]")
    client = OpenAI()

    questions = [
        "What is inference latency?",
        "How does batching affect it?",
        "Summarize what we discussed in one sentence.",
    ]

    history = []
    with tracing.Conversation(agent_name="support-agent") as conversation:
        for question in questions:
            with conversation.start_turn(user_message=question):
                history.append({"role": "user", "content": question})
                response = client.responses.create(model="gpt-5-mini", input=history)
                history.append({"role": "assistant", "content": response.output_text})
                print(response.output_text)

    tracing.shutdown()
    ```
  </Tab>

  <Tab title="TypeScript">
    각 에이전트 run을 `tracing.runIsolated()`로 감싸면 해당 run의 대화와 턴이 동시에 실행되는 다른 run과 분리됩니다.

    ```typescript lines title="app.mjs" theme={"system"}
    import OpenAI from 'openai';
    import {tracing} from '@coreweave/forge-sdk/agentlens';

    await tracing.init('[YOUR-TEAM]/[YOUR-PROJECT]');
    const openai = new OpenAI();

    const questions = [
      'What is inference latency?',
      'How does batching affect it?',
      'Summarize what we discussed in one sentence.',
    ];

    await tracing.runIsolated(async () => {
      const conversation = tracing.startConversation({agentName: 'support-agent'});
      const history = [];
      try {
        for (const question of questions) {
          const turn = conversation.startTurn({userMessage: question});
          try {
            history.push({role: 'user', content: question});
            const response = await openai.responses.create({model: 'gpt-5-mini', input: history});
            history.push({role: 'assistant', content: response.output_text});
            console.log(response.output_text);
          } finally {
            turn.end();
          }
        }
      } finally {
        conversation.end();
      }
    });

    await tracing.shutdown();
    ```

    계측 플래그를 지정해 스크립트를 실행하세요. 이 플래그는 코드보다 먼저 Forge 계측을 로드하므로, 코드에서 OpenAI SDK를 임포트하는 시점에 이미 패치가 적용되어 있습니다.

    ```bash theme={"system"}
    node --import=@coreweave/forge-sdk/instrument app.mjs
    ```

    번들러가 의존성을 하나의 파일로 합치는 경우처럼 플래그를 사용할 수 없다면 클라이언트를 래핑하세요.

    ```typescript theme={"system"}
    import {integrations} from '@coreweave/forge-sdk/agentlens';

    const openai = integrations.wrapOpenAI(new OpenAI());
    ```

    플래그 없이 실행하면 `tracing.init()`이 이와 관련된 경고를 한 번 출력합니다. 클라이언트를 래핑했다면 이 경고는 무시해도 됩니다.
  </Tab>
</Tabs>

요청당 하나의 턴을 처리하는 웹 앱처럼 나중에 기존 대화에 턴을 추가하려면, 대화를 생성할 때마다 동일한 `conversation_id`(Python) 또는 `conversationId`(TypeScript)를 전달하세요.

대화, 턴 및 기타 span 유형에 대한 자세한 내용은 [에이전트 트레이싱](/ko/products/agent-lens/tracing/instrument)을 참조하세요.

<h2 id="turn-off-automatic-patching">
  자동 패치 끄기
</h2>

Python에서는 `tracing.init()`에 `autopatch_integrations=False`를 전달하세요. 그러면 `tracing.integrations.patch_openai()` 및 `tracing.integrations.unpatch_openai()`를 사용해 OpenAI SDK를 직접 패치하거나 패치를 해제할 수 있습니다.

TypeScript에서는 `--import=@coreweave/forge-sdk/instrument` 플래그 없이 실행한 다음, 트레이스할 클라이언트만 `integrations.wrapOpenAI()`로 래핑하세요.

<h2 id="view-your-traces">
  트레이스 보기
</h2>

[CoreWeave Forge](https://forge.coreweave.com)의 제품 메뉴에서 Agent Lens를 선택하고, 사이드 메뉴 상단의 프로젝트 선택기에서 해당 프로젝트를 선택한 후 **Conversations**를 선택하세요. 자세한 내용은 [에이전트 활동 보기](/ko/products/agent-lens/conversations/view-activity)를 참조하세요.
