메인 콘텐츠로 건너뛰기
Colab에서 열기
별도 설정 없이 Weave에서 OpenAI 모델을 사용해 실험해 보고 싶으신가요? LLM 플레이그라운드를 사용해 보세요.

트레이싱

개발 중이든 프로덕션 환경이든, LLM 애플리케이션의 트레이스를 중앙 데이터베이스에 저장하는 것은 중요합니다. 이러한 트레이스는 디버깅에 활용할 수 있고, 애플리케이션을 개선하는 과정에서 평가에 사용할 까다로운 예시 데이터셋을 구축하는 데도 도움이 됩니다. Weave는 openai python library의 트레이스를 자동으로 캡처할 수 있습니다. 원하는 프로젝트 이름으로 weave.init(<project-name>)를 호출해 캡처를 시작하세요. OpenAI는 임포트하는 시점과 관계없이 자동으로 패치됩니다. weave.init()를 호출할 때 W&B 팀을 지정하지 않으면 기본 entity가 사용됩니다. 기본 entity를 확인하거나 업데이트하려면 W&B Models 문서의 User Settings를 참고하세요. 자동 패치 Weave는 weave.init() 호출 전후와 관계없이 OpenAI를 자동으로 패치합니다.
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?"
    }
  ]
)
명시적 패치 (선택) 더 세밀하게 제어하려면 명시적으로 패치할 수도 있습니다:
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"}
  ]
)
실시간 트레이스 보기
OpenAI FunctionsOpenAI Assistants의 함수 호출 도구도 캡처합니다.

구조화된 출력

Weave는 OpenAI와 함께 구조화된 출력도 지원합니다. 이 기능은 LLM 응답이 특정 형식을 따르도록 하는 데 유용합니다.
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)

비동기 지원

Weave는 OpenAI의 비동기 함수도 지원합니다.
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()

스트리밍 지원

Weave는 OpenAI의 응답 스트리밍도 지원합니다.
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="")

함수 호출 트레이싱

도구를 사용할 때 Weave는 OpenAI가 수행한 함수 호출도 트레이스합니다.
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)

Batch API

Weave는 여러 요청을 일괄 처리할 수 있도록 OpenAI Batch API도 지원합니다.
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)

Assistants API

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

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

# 어시스턴트 생성
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?"
)

# 어시스턴트 실행
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id
)

# 어시스턴트 응답 조회
messages = client.beta.threads.messages.list(thread_id=thread.id)

비용 추적

Weave는 OpenAI API 호출 비용을 자동으로 추적합니다. 비용 내역은 Weave UI에서 확인할 수 있습니다.
비용 추적은 모든 OpenAI 모델에서 사용할 수 있으며, 최신 OpenAI 가격을 기준으로 계산됩니다.

맞춤형 함수 트레이싱

@weave.op 데코레이터를 사용하면 OpenAI를 사용하는 맞춤형 함수도 트레이스할 수 있습니다.
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?")

다음 단계

이제 OpenAI용 트레이싱을 설정했으므로 다음 작업을 할 수 있습니다.
  1. Weave UI에서 트레이스 보기: Weave 프로젝트로 이동해 OpenAI 호출의 트레이스를 확인합니다
  2. 평가 생성: 트레이스를 사용해 평가용 데이터셋을 만듭니다
  3. 성능 모니터링: 지연 시간, 비용 및 기타 메트릭을 추적합니다
  4. 문제 디버깅: 트레이스를 사용해 LLM 애플리케이션에서 어떤 일이 일어나고 있는지 파악합니다
이 주제에 대한 자세한 내용은 평가 가이드모니터링 가이드를 참조하세요.