메인 콘텐츠로 건너뛰기
Colab에서 열기 코드에 Weave를 통합하면 PythonTypeScript용 Anthropic SDK로 수행되는 LLM 호출을 Weave가 자동으로 추적하고 로깅합니다. Weave는 Anthropic의 Messages.create 메서드를 자동으로 호출해 이를 처리합니다.

트레이스

코드에 weave.init("your-team-name/your-project-name")를 추가하면 Weave가 Anthropic SDK 호출에 대한 트레이스를 자동으로 캡처합니다. weave.init()의 인자로 팀 이름을 지정하지 않으면, Weave는 출력 내용을 기본 W&B entity에 기록합니다. 프로젝트 이름을 지정하지 않으면 Weave 초기화에 실패합니다. 다음 예시는 Anthropic에 대한 기본 호출에 Weave를 연동하는 방법을 보여줍니다:
import weave    
# anthropic 라이브러리를 평소처럼 사용합니다
import os
from anthropic import Anthropic

weave.init("anthropic_project")

client = Anthropic(
    api_key=os.environ.get("ANTHROPIC_API_KEY"),
)

message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "개에 대한 농담을 하나 말해줘",
        }
    ],
    model="claude-3-opus-20240229",
)
print(message.content)
코드에 weave.init()을 포함하면 Weave가 트레이싱 정보를 자동으로 캡처하고 링크를 출력합니다. 링크를 클릭하면 Weave UI에서 트레이스를 확인할 수 있습니다. anthropic_trace.png

사용자 정의 ops로 래핑하기

Weave ops는 실험하는 동안 코드를 자동으로 버전 관리하고, 그 입력과 출력을 캡처합니다. @weave.op() (Python)으로 데코레이트하거나 weave.op() (TypeScript)로 래핑한 뒤 Anthropic.messages.create를 호출하면, Weave가 입력과 출력을 자동으로 추적합니다. 다음 예시는 함수를 추적하는 방법을 보여줍니다:
import weave
import os
from anthropic import Anthropic

weave.init("anthropic_project")
client = Anthropic(
    api_key=os.environ.get("ANTHROPIC_API_KEY"),
)

@weave.op()
def call_anthropic(user_input:str, model:str) -> str:
    message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": user_input,
        }
        ],
        model=model,
    )
    return message.content[0].text

@weave.op()
def generate_joke(topic: str) -> str:
    return call_anthropic(f"Tell me a joke about {topic}", model="claude-3-haiku-20240307")

print(generate_joke("chickens"))
print(generate_joke("cars"))
함수를 weave.op()으로 데코레이트하거나 래핑하면, Weave가 함수의 코드와 입력, 출력을 캡처합니다. ops는 중첩 함수를 포함해 원하는 어떤 함수에도 사용할 수 있습니다. anthropic_ops.png

실험을 더 쉽게 하기 위해 Model 생성하기

weave.Model 클래스는 Weave Python SDK에서만 사용할 수 있습니다. TypeScript에서는 weave.op() 래퍼를 사용해 구조화된 파라미터를 가진 함수를 추적하세요.
여러 요소가 복잡하게 얽혀 있을 때에는 실험을 체계적으로 정리하기가 어렵습니다. Model 클래스를 사용하면 시스템 프롬프트나 사용 중인 모델과 같이 앱의 실험 세부 정보를 기록하고 구성할 수 있습니다. 이를 통해 앱의 다양한 이터레이션을 정리하고 비교하는 데 도움이 됩니다. 코드 버전 관리와 입력/출력 기록뿐 아니라, Model은 애플리케이션 동작을 제어하는 구조화된 파라미터도 함께 캡처합니다. 이를 통해 어떤 파라미터가 가장 잘 동작하는지 찾을 수 있습니다. 또한 Weave Models를 serveEvaluation과 함께 사용할 수도 있습니다. 다음 예시에서는 modeltemperature를 바꿔 가며 실험해 볼 수 있습니다:
import weave    
# anthropic 라이브러리를 평소처럼 사용합니다
import os
from anthropic import Anthropic
weave.init('joker-anthropic')

class JokerModel(weave.Model): # `weave.Model`로 변경
  model: str
  temperature: float
  
  @weave.op()
  def predict(self, topic): # `predict`로 변경
    client = Anthropic()
    message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": f"Tell me a joke about {topic}",
        }
        ],
        model=self.model,
        temperature=self.temperature
    )
    return message.content[0].text


joker = JokerModel(
    model="claude-3-haiku-20240307",
    temperature = 0.1)
result = joker.predict("Chickens and Robots")
print(result)
이 값들 가운데 하나라도 변경할 때마다 Weave는 JokerModel의 새 버전을 생성하고 추적합니다. 이를 통해 트레이스 데이터를 코드 변경 사항과 연결할 수 있으며, 어떤 설정이 사용 사례에 가장 잘 맞는지 판단하는 데 도움이 됩니다. anthropic_model.png

Tools (함수 호출)

Anthropic은 Claude가 함수 호출을 요청할 수 있는 tools 인터페이스를 제공합니다. Weave는 대화 전체에 걸쳐 도구 정의, 도구 사용 요청, 도구 결과를 자동으로 추적합니다. 다음은 Anthropic 도구 설정의 일부 예시입니다:
message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "What's the weather like in San Francisco?",
        }
    ],
    tools=[
        {
            "name": "get_weather",
            "description": "Get the current weather in a given location",
            "input_schema": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    }
                },
                "required": ["location"],
            },
        },
    ],
    model=model,
)

print(message)
Weave는 각 대화 단계마다 도구 정의, Claude의 도구 사용 요청, 도구 결과를 자동으로 수집합니다. anthropic_tool.png