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

> OpenAI를 Weave와 통합하여 트레이싱, 평가, 모니터링을 수행하세요

<a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_openai.ipynb" aria-label="Google Colab에서 열기">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Colab에서 열기" />
</a>

이 가이드에서는 OpenAI Python 및 TypeScript 라이브러리를 Weave와 통합하여 LLM 애플리케이션을 트레이스, 평가, 모니터링하는 방법을 설명합니다. 이미 OpenAI SDK를 사용 중이며, 개발 단계와 프로덕션 환경 모두에서 Call을 파악하고 싶은 개발자를 위한 가이드입니다.

<Note>
  [LLM Playground](/ko/products/wandb/weave/guides/tools/playground)를 사용하면 별도 설정 없이 Weave에서 OpenAI 모델을 바로 실험해 볼 수 있습니다.
</Note>

<h2 id="tracing">
  트레이싱
</h2>

LLM 애플리케이션의 트레이스를 중앙 데이터베이스에 저장해 두면 개발 단계와 프로덕션 단계 모두에서 유용합니다. 트레이스는 디버깅에 활용할 수 있고, 애플리케이션을 개선하면서 평가에 사용할 까다로운 예시를 모아 데이터셋을 구축하는 데에도 도움이 됩니다.

Weave는 [`openai` Python 라이브러리](https://developers.openai.com/api/docs/libraries)의 트레이스를 자동으로 캡처할 수 있습니다.

캡처를 시작하려면 원하는 프로젝트 이름을 지정해 `weave.init("[PROJECT_NAME]")`을 호출하세요. Weave는 OpenAI를 임포트하는 시점과 관계없이 자동으로 패치하므로, 이후의 모든 OpenAI Call이 트레이싱됩니다.

`weave.init()`을 호출할 때 CoreWeave Forge 팀을 지정하지 않으면 Weave는 기본 entity를 사용합니다. 기본 entity를 확인하거나 변경하려면 Weights & Biases Models 문서의 [User Settings](/ko/products/wandb/platform/app/settings-page/user-settings#default-team)를 참고하세요.

<h3 id="automatic-patching">
  자동 패치
</h3>

OpenAI를 `weave.init()` 이전에 임포트하든 이후에 임포트하든 Weave가 자동으로 패치합니다. 다음 예시는 Call 트레이싱을 시작하는 데 필요한 최소한의 설정을 보여 줍니다.

<CodeGroup>
  ```python Python lines {4} theme={"system"}
  from openai import OpenAI
  import weave

  weave.init('emoji-bot')  # OpenAI가 자동으로 패치됩니다!

  client = OpenAI()
  response = client.chat.completions.create(
    model="gpt-4",
    messages=[
      {
        "role": "system",
        "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
      },
      {
        "role": "user",
        "content": "How are you?"
      }
    ]
  )
  ```

  ```typescript twoslash TypeScript theme={"system"}
  // @noErrors
  import { OpenAI } from 'openai';
  import { wrapOpenAI } from '@wandb/weave';

  const openai = wrapOpenAI(new OpenAI());

  // 이제 OpenAI에 대한 모든 Call이 트레이스됩니다
  openai.chat.completions.create(
    {
      model: "gpt-4",
      messages: [
        {
          role: "system",
          content: "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
        },
        {
          role: "user",
          content: "How are you?"
        }
      ]
    }
  );
  ```
</CodeGroup>

<h3 id="optional-explicit-patching">
  선택 사항: 명시적 패치
</h3>

패치가 적용되는 시점을 세밀하게 제어하려면 자동 동작에 의존하지 말고 OpenAI를 명시적으로 패치하세요.

```python lines {3,4} theme={"system"}
import weave

weave.init('emoji-bot')
weave.integrations.patch_openai()  # OpenAI 트레이싱 활성화

from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
  model="gpt-4",
  messages=[
    {"role": "user", "content": "Make me a emoji"}
  ]
)
```

[라이브 트레이스 보기](https://forge.coreweave.com/wandb/capecape/emoji-bot/weave/calls/01928a78-6d8a-7e20-9b8c-0cbc8318a0c8)

<Tip>
  Weave는 [OpenAI Functions](https://platform.openai.com/docs/guides/function-calling)와 [OpenAI Assistants](https://platform.openai.com/docs/assistants/overview)의 함수 호출 도구도 캡처합니다.
</Tip>

<h2 id="structured-outputs">
  구조화된 출력
</h2>

Weave는 OpenAI 구조화된 출력의 트레이싱을 지원합니다. 구조화된 출력은 LLM 응답이 특정 형식을 반드시 따르도록 해야 할 때 유용합니다. 다음 예시는 사용자 메시지에서 유형이 지정된 `UserDetail` 객체를 추출하는 Call을 트레이스합니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  from pydantic import BaseModel
  import weave

  class UserDetail(BaseModel):
      name: str
      age: int

  client = OpenAI()
  weave.init('extract-user-details')

  completion = client.beta.chat.completions.parse(
      model="gpt-4o-2024-08-06",
      messages=[
          {"role": "system", "content": "Extract the user details from the message."},
          {"role": "user", "content": "My name is David and I am 30 years old."},
      ],
      response_format=UserDetail,
  )

  user_detail = completion.choices[0].message.parsed
  print(user_detail)
  ```
</CodeGroup>

<h2 id="async-support">
  비동기 지원
</h2>

Weave는 비동기 OpenAI Call의 트레이싱을 지원합니다. 따라서 `AsyncOpenAI`를 사용하는 애플리케이션에서도 동기 애플리케이션과 동일한 가시성을 확보할 수 있습니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import AsyncOpenAI
  import weave

  client = AsyncOpenAI()
  weave.init('async-emoji-bot')

  async def call_openai():
      response = await client.chat.completions.create(
          model="gpt-4",
          messages=[
              {
                  "role": "system", 
                  "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
              },
              {
                  "role": "user",
                  "content": "How are you?"
              }
          ]
      )
      return response

  # 비동기 함수 호출
  result = await call_openai()
  ```
</CodeGroup>

<h2 id="streaming-support">
  스트리밍 지원
</h2>

Weave는 OpenAI 스트리밍 응답의 트레이싱을 지원합니다. 캡처된 트레이스에는 스트리밍된 완료 결과 전체가 반영되므로, 최종 출력과 요청 매개변수를 함께 검토할 수 있습니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('streaming-emoji-bot')

  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {
              "role": "system", 
              "content": "You are AGI. You will be provided with a message, and your task is to respond using emojis only."
          },
          {
              "role": "user",
              "content": "How are you?"
          }
      ],
      stream=True
  )

  for chunk in response:
      print(chunk.choices[0].delta.content or "", end="")
  ```
</CodeGroup>

<h2 id="tracing-function-calls">
  함수 호출 트레이싱
</h2>

도구를 사용하면 Weave가 OpenAI의 함수 호출을 트레이스합니다. 이를 통해 모델이 각 도구를 어떤 방식으로, 어떤 인수와 함께 호출했는지 파악할 수 있습니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('function-calling-bot')

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get the weather in a given location",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "The location to get the weather for"
                      },
                      "unit": {
                          "type": "string",
                          "enum": ["celsius", "fahrenheit"],
                          "description": "The unit to return the temperature in"
                      }
                  },
                  "required": ["location"]
              }
          }
      }
  ]

  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {
              "role": "user",
              "content": "What's the weather like in New York?"
          }
      ],
      tools=tools
  )

  print(response.choices[0].message.tool_calls)
  ```
</CodeGroup>

<h2 id="batch-api">
  Batch API
</h2>

Weave는 OpenAI Batch API를 지원합니다. 이 API를 사용하면 여러 요청을 비동기로 처리하면서도 각 요청을 Weave 트레이스에 그대로 캡처할 수 있습니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('batch-processing')

  # 배치 파일 생성
  batch_input = [
      {
          "custom_id": "request-1",
          "method": "POST",
          "url": "/v1/chat/completions",
          "body": {
              "model": "gpt-4",
              "messages": [{"role": "user", "content": "Hello, how are you?"}]
          }
      },
      {
          "custom_id": "request-2", 
          "method": "POST",
          "url": "/v1/chat/completions",
          "body": {
              "model": "gpt-4",
              "messages": [{"role": "user", "content": "What's the weather like?"}]
          }
      }
  ]

  # 배치 제출
  batch = client.batches.create(
      input_file_id="your-file-id",
      endpoint="/v1/chat/completions",
      completion_window="24h"
  )

  # 배치 결과 조회
  completed_batch = client.batches.retrieve(batch.id)
  ```
</CodeGroup>

<h2 id="assistants-api">
  Assistants API
</h2>

Weave는 OpenAI Assistants API를 지원합니다. 따라서 assistant, 스레드, run을 중심으로 구축한 대화형 AI 애플리케이션을 트레이스할 수 있습니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('assistant-bot')

  # assistant 생성
  assistant = client.beta.assistants.create(
      name="Math Assistant",
      instructions="You are a personal math tutor. Answer questions about math.",
      model="gpt-4"
  )

  # 스레드 생성
  thread = client.beta.threads.create()

  # 스레드에 메시지 추가
  message = client.beta.threads.messages.create(
      thread_id=thread.id,
      role="user",
      content="What is 2+2?"
  )

  # assistant 실행
  run = client.beta.threads.runs.create(
      thread_id=thread.id,
      assistant_id=assistant.id
  )

  # assistant의 응답 조회
  messages = client.beta.threads.messages.list(thread_id=thread.id)
  ```
</CodeGroup>

<h2 id="cost-tracking">
  비용 추적
</h2>

Weave는 OpenAI API 호출 비용을 자동으로 추적하므로 성능과 함께 비용을 모니터링할 수 있습니다. 비용 세부 내역은 Weights & Biases UI에서 확인할 수 있습니다.

<Note>
  비용 추적은 모든 OpenAI 모델에서 사용 가능하며, Weave는 OpenAI가 공개한 가격을 기준으로 비용을 계산합니다.
</Note>

<h2 id="tracing-custom-functions">
  맞춤형 함수 트레이싱
</h2>

OpenAI Call을 자체 애플리케이션 로직 단위로 묶으려면 OpenAI를 사용하는 맞춤형 함수에 `@weave.op` 데코레이터를 적용해 트레이스하세요. 그러면 해당 함수의 상위 트레이스가 생성되고, 내부에서 실행된 OpenAI Call이 그 아래에 중첩됩니다.

<CodeGroup>
  ```python Python theme={"system"}
  from openai import OpenAI
  import weave

  client = OpenAI()
  weave.init('custom-function-bot')

  @weave.op
  def generate_response(prompt: str) -> str:
      response = client.chat.completions.create(
          model="gpt-4",
          messages=[
              {
                  "role": "user",
                  "content": prompt
              }
          ]
      )
      return response.choices[0].message.content

  # 이 함수 호출이 트레이스됩니다
  result = generate_response("Hello, how are you?")
  ```
</CodeGroup>

<h2 id="next-steps">
  다음 단계
</h2>

OpenAI 트레이싱을 설정했으므로 이제 애플리케이션의 Call을 Weave에서 확인할 수 있습니다. 여기서 다음 작업을 진행할 수 있습니다.

* **Weights & Biases UI에서 트레이스 보기**: Weave 프로젝트로 이동하여 OpenAI Call의 트레이스를 확인하세요.
* **평가 만들기**: 트레이스를 활용해 평가 데이터셋을 구축하세요.
* **성능 모니터링**: 지연 시간, 비용 및 기타 메트릭을 추적하세요.
* **문제 디버깅**: 트레이스를 사용하여 LLM 애플리케이션 내부에서 어떤 일이 일어나는지 파악하세요.

자세한 내용은 [평가 가이드](/ko/products/wandb/weave/guides/evaluation/scorers) 및 [모니터링 가이드](../tracking)를 참조하세요.


## Related topics

- [OpenAI API](/ko/products/wandb/integrations/openai-api.md)
