> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wandb.ai/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>
  별도 설정 없이 Weave에서 OpenAI 모델을 사용해 실험해 보세요. [LLM 플레이그라운드](../tools/playground)를 사용하시면 됩니다.
</Note>

<div id="tracing">
  ## 트레이싱
</div>

개발 중이든 프로덕션 환경이든, LLM 애플리케이션의 트레이스를 중앙 데이터베이스에 저장하는 것은 유용합니다. 이러한 트레이스는 디버깅에 활용할 수 있고, 애플리케이션을 개선하는 과정에서 평가에 사용할 까다로운 예시 데이터셋을 구축하는 데도 도움이 됩니다.

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

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

`weave.init()`를 호출할 때 W\&B 팀을 지정하지 않으면 기본 entity가 사용됩니다. 기본 entity를 확인하거나 업데이트하려면 W\&B Models 문서의 [User Settings](https://docs.wandb.ai/platform/app/settings-page/user-settings/#default-team)를 참고하세요.

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

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

<CodeGroup>
  ```python Python lines {4} theme={null}
  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={null}
  // @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>

<div id="optional-explicit-patching">
  ### 선택: 명시적 패치
</div>

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

```python lines {3,4} theme={null}
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://wandb.ai/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>

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

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

<CodeGroup>
  ```python Python theme={null}
  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>

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

Weave는 비동기 OpenAI Call의 트레이싱도 지원하므로 `AsyncOpenAI`를 사용하는 애플리케이션도 동기 애플리케이션과 동일한 수준의 가시성을 제공합니다.

<CodeGroup>
  ```python Python theme={null}
  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>

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

Weave는 OpenAI의 스트리밍 응답에 대한 트레이싱을 지원합니다. 캡처된 트레이스에는 전체 스트리밍 completion이 반영되므로, 요청 parameters와 함께 최종 출력을 검토할 수 있습니다.

<CodeGroup>
  ```python Python theme={null}
  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>

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

도구를 사용할 때 Weave는 OpenAI가 수행한 함수 호출도 트레이스하며, 이를 통해 모델이 각 도구를 어떻게 호출했는지와 어떤 인수를 사용했는지 이해하는 데 도움이 됩니다.

<CodeGroup>
  ```python Python theme={null}
  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>

<div id="batch-api">
  ## Batch API
</div>

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

<CodeGroup>
  ```python Python theme={null}
  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>

<div id="assistants-api">
  ## Assistants API
</div>

Weave는 OpenAI Assistants API를 지원하므로 assistant, thread, run을 기반으로 구축된 대화형 AI 애플리케이션을 트레이스할 수 있습니다.

<CodeGroup>
  ```python Python theme={null}
  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 생성
  thread = client.beta.threads.create()

  # thread에 메시지 추가
  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>

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

지출을 성능과 함께 모니터링할 수 있도록 Weave는 OpenAI API Call 비용을 자동으로 추적합니다. 비용 내역은 Weave UI에서 확인할 수 있습니다.

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

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

OpenAI Call을 자체 애플리케이션 로직 아래로 그룹화하려면, `@weave.op` 데코레이터를 적용해 OpenAI를 사용하는 맞춤형 함수를 트레이스하세요. 이렇게 하면 해당 함수에 대한 상위 트레이스가 생성되고, 그 내부에 기본 OpenAI Call이 중첩됩니다.

<CodeGroup>
  ```python Python theme={null}
  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>

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

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

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

이 주제에 대한 자세한 내용은 [평가 가이드](../evaluation/scorers) 및 [모니터링 가이드](../tracking)를 참조하세요.
