> ## Documentation Index
> Fetch the complete documentation index at: https://wb-21fd5541-feature-automate-reference-docs-generation.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Openai

# OpenAI

<a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_openai.ipynb">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" />
</a>

<Note>
  설정 없이 Weave에서 OpenAI 모델을 실험해 보고 싶으신가요? [LLM 플레이그라운드](../tools/playground.mdx)를 시도해 보세요.
</Note>

## 추적

개발 중이나 프로덕션 환경에서 LLM 애플리케이션의 추적을 중앙 데이터베이스에 저장하는 것이 중요합니다. 이러한 추적은 디버깅에 사용되며 애플리케이션을 개선하는 동안 평가할 수 있는 까다로운 예제 데이터셋을 구축하는 데 도움이 됩니다.

Weave는 [openai python 라이브러리](https://platform.openai.com/docs/libraries/python-library)에 대한 추적을 자동으로 캡처할 수 있습니다.

원하는 프로젝트 이름으로 `weave.init(<project-name>)` 를 호출하여 캡처를 시작하세요.

<CodeGroup>
  ```python Python
  from openai import OpenAI
  import weave
  client = OpenAI()
  # highlight-next-line
  weave.init('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?"
      }
    ]
  )
  ```

  ```typescript TypeScript
  import { OpenAI } from 'openai';
  import { wrapOpenAI } from '@wandb/weave';

  const openai = wrapOpenAI(new OpenAI());

  // This will now trace all calls to OpenAI
  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>

[실시간 추적 보기](https://wandb.ai/capecape/emoji-bot/weave/calls/01928a78-6d8a-7e20-9b8c-0cbc8318a0c8)

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

## 구조화된 출력

Weave는 OpenAI와 함께 구조화된 출력도 지원합니다. 이는 LLM 응답이 특정 형식을 따르도록 보장하는 데 유용합니다.

<CodeGroup>
  ```python Python
  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>

## 비동기 지원

Weave는 OpenAI에 대한 비동기 함수도 지원합니다.

<CodeGroup>
  ```python Python
  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

  # Call the async function
  result = await call_openai()
  ```
</CodeGroup>

## 스트리밍 지원

Weave는 OpenAI의 스트리밍 응답도 지원합니다.

<CodeGroup>
  ```python Python
  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>

## 함수 호출 추적

Weave는 도구를 사용할 때 OpenAI에서 수행하는 함수 호출도 추적합니다.

<CodeGroup>
  ```python Python
  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>

## 추가 데이터 로깅

추적에 추가 데이터를 로깅하려면 `weave.log` 함수를 사용할 수 있습니다.

<CodeGroup>
  ```python Python
  from openai import OpenAI
  import weave

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

  # Log additional data
  weave.log({"user_id": "123", "session_id": "abc"})

  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {
              "role": "user",
              "content": "Hello, how are you?"
          }
      ]
  )
  ```
</CodeGroup>

## 배치 API

Weave는 여러 요청을 처리하기 위한 OpenAI 배치 API도 지원합니다.

<CodeGroup>
  ```python Python
  from openai import OpenAI
  import weave

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

  # Create a batch file
  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?"}]
          }
      }
  ]

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

  # Retrieve the batch results
  completed_batch = client.batches.retrieve(batch.id)
  ```
</CodeGroup>

## Assistants API

Weave는 대화형 AI 애플리케이션을 구축하기 위한 OpenAI Assistants API도 지원합니다.

<CodeGroup>
  ```python Python
  from openai import OpenAI
  import weave

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

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

  # Create a thread
  thread = client.beta.threads.create()

  # Add a message to the thread
  message = client.beta.threads.messages.create(
      thread_id=thread.id,
      role="user",
      content="What is 2+2?"
  )

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

  # Get the assistant's response
  messages = client.beta.threads.messages.list(thread_id=thread.id)
  ```
</CodeGroup>

## 비용 추적

Weave는 OpenAI API 호출 비용을 자동으로 추적합니다. Weave UI에서 비용 내역을 볼 수 있습니다.

<Note>
  비용 추적은 모든 OpenAI 모델에 사용 가능하며 최신 OpenAI 가격을 기준으로 계산됩니다.
</Note>

## 사용자 정의 함수 추적

OpenAI를 사용하는 커스텀 함수도 다음을 사용하여 추적할 수 있습니다 `@weave.op` 데코레이터.

<CodeGroup>
  ```python Python
  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

  # This function call will be traced
  result = generate_response("Hello, how are you?")
  ```
</CodeGroup>

## 다음 단계

이제 OpenAI에 대한 추적을 설정했으니 다음을 수행할 수 있습니다:

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

이러한 주제에 대한 자세한 정보는 [평가 가이드](../evaluation/index.mdx)와 [모니터링 가이드](../tracking/index.mdx)를 확인하세요.
