이 가이드에서는 OpenAI Python 및 TypeScript 라이브러리를 Weave와 통합하여 LLM 애플리케이션을 트레이스, 평가, 모니터링하는 방법을 보여드립니다. OpenAI SDK를 이미 사용하고 있으며 개발 단계와 프로덕션 환경에서 Call에 대한 가시성을 확보하려는 개발자를 위한 가이드입니다.
별도 설정 없이 Weave에서 OpenAI 모델을 사용해 실험해 보세요. LLM 플레이그라운드를 사용하시면 됩니다.
개발 중이든 프로덕션 환경이든, LLM 애플리케이션의 트레이스를 중앙 데이터베이스에 저장하는 것은 유용합니다. 이러한 트레이스는 디버깅에 활용할 수 있고, 애플리케이션을 개선하는 과정에서 평가에 사용할 까다로운 예시 데이터셋을 구축하는 데도 도움이 됩니다.Weave는 openai Python library의 트레이스를 자동으로 캡처할 수 있습니다.원하는 프로젝트 이름으로 weave.init("[PROJECT_NAME]")를 호출해 캡처를 시작하세요. Weave는 임포트하는 시점과 관계없이 OpenAI를 자동으로 패치하므로, 이후의 모든 OpenAI Call이 트레이싱됩니다.weave.init()를 호출할 때 W&B 팀을 지정하지 않으면 기본 entity가 사용됩니다. 기본 entity를 확인하거나 업데이트하려면 W&B Models 문서의 User Settings를 참고하세요.
Weave는 OpenAI를 weave.init() 전에 임포트하든 후에 임포트하든 자동으로 패치합니다. 다음 예시는 Call 트레이싱을 시작하는 데 필요한 최소 설정을 보여줍니다:
from openai import OpenAIimport weaveweave.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 { OpenAI } from 'openai';import { wrapOpenAI } from '@wandb/weave';constopenai =wrapOpenAI(newOpenAI());// 이제 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?" } ] });
Weave는 OpenAI 구조화된 출력의 트레이싱도 지원하며, 이는 LLM 응답이 특정 형식을 따르도록 해야 할 때 유용합니다. 다음 예시는 사용자 메시지에서 유형 지정된 UserDetail 객체를 추출하는 call을 트레이스합니다:
from openai import OpenAIfrom pydantic import BaseModelimport weaveclass UserDetail(BaseModel): name: str age: intclient = 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.parsedprint(user_detail)
Weave는 비동기 OpenAI Call의 트레이싱도 지원하므로 AsyncOpenAI를 사용하는 애플리케이션도 동기 애플리케이션과 동일한 수준의 가시성을 제공합니다.
from openai import AsyncOpenAIimport weaveclient = 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의 스트리밍 응답에 대한 트레이싱을 지원합니다. 캡처된 트레이스에는 전체 스트리밍 completion이 반영되므로, 요청 parameters와 함께 최종 출력을 검토할 수 있습니다.
from openai import OpenAIimport weaveclient = 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 OpenAIimport weaveclient = 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)