> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Anthropic

> Weave를 사용하여 Anthropic SDK로 수행한 LLM Call을 자동으로 추적하고 로깅하세요

<a target="_blank" href="https://colab.research.google.com/github/wandb/examples/blob/master/weave/docs/quickstart_anthropic.ipynb" aria-label="Google Colab에서 열기">
  <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Colab에서 열기" />
</a>

코드에 Weave를 통합하면 Weave가 [Python](https://github.com/anthropics/anthropic-sdk-python)과 [TypeScript](https://github.com/anthropics/anthropic-sdk-typescript)용 Anthropic SDK로 수행한 LLM Call을 모두 자동으로 추적하고 로깅합니다. 이를 위해 Weave는 Anthropic의 `Messages.create()` 메서드를 자동으로 호출합니다.

이 가이드에서는 Anthropic SDK로 작업할 때 트레이스를 캡처하고, 직접 작성한 함수를 Op으로 래핑하고, 실험에 재사용할 수 있는 `Model`을 구축하고, 도구 사용을 추적하는 방법을 설명합니다. 이러한 패턴을 활용하면 맞춤형 로깅 코드를 따로 작성하지 않고도 Claude 기반 애플리케이션을 디버그하고, 비교하고, 반복적으로 개선할 수 있습니다.

<h2 id="traces">
  트레이스
</h2>

코드에 `weave.init("your-team-name/your-project-name")`를 추가하면 Weave가 Anthropic SDK의 트레이스를 자동으로 캡처합니다. `weave.init()`에 팀 이름을 인수로 지정하지 않으면 Weave는 [기본 W\&B entity](/ko/products/wandb/platform/app/settings-page/user-settings#default-team)에 출력을 로깅합니다. 프로젝트 이름을 지정하지 않으면 Weave 초기화가 실패합니다.

다음 예시는 기본적인 Anthropic Call에 Weave를 통합하는 방법을 보여줍니다.

<Tabs>
  <Tab title="Python">
    ```python lines {6} theme={"system"}
    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": "Tell me a joke about a dog",
            }
        ],
        model="claude-3-opus-20240229",
    )
    print(message.content)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash theme={"system"}
    // @noErrors
    import Anthropic from '@anthropic-ai/sdk';
    import * as weave from 'weave';
    import { wrapAnthropic } from 'weave';

    await weave.init('anthropic_project');

    // 트레이싱을 활성화하려면 Anthropic 클라이언트를 래핑합니다
    const client = wrapAnthropic(new Anthropic());

    const message = await client.messages.create({
        max_tokens: 1024,
        messages: [
            {
                role: 'user',
                content: 'Tell me a joke about a dog',
            }
        ],
        model: 'claude-3-opus-20240229',
    });

    console.log(message.content);
    ```
  </Tab>
</Tabs>

코드에 `weave.init()`를 포함하면 Weave가 트레이싱 정보를 자동으로 캡처하고 링크를 출력합니다. 이 링크를 클릭하면 Weights & Biases UI에서 트레이스를 확인할 수 있습니다.

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/anthropic_trace.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=65de4a109defabbb0e1b0da9524a9729" alt="anthropic_trace.png" width="2908" height="1594" data-path="products/wandb/weave/_media/anthropic_trace.png" />](https://forge.coreweave.com/wandb/capecape/anthropic_project/weave/calls)

<h2 id="wrap-with-your-own-ops">
  직접 만든 Op로 래핑하기
</h2>

`weave.init()`만으로도 Anthropic SDK Call이 캡처되지만, 직접 작성한 함수를 Op로 데코레이트하면 각 모델 Call을 둘러싼 애플리케이션 로직까지 담긴 더 풍부한 트레이스를 얻을 수 있습니다.

Weave Op는 실험을 진행하는 동안 코드 버전을 자동으로 관리하고 입력과 출력을 캡처합니다. [`Anthropic.messages.create()`](https://platform.claude.com/docs/en/build-with-claude/working-with-messages)를 호출하는 함수를 Python에서는 [`@weave.op()`](/ko/products/wandb/weave/guides/tracking/ops)로 데코레이트하고, TypeScript에서는 [`weave.op()`](/ko/products/wandb/weave/reference/typescript-sdk/functions/op)로 래핑하세요. 그러면 Weave가 입력과 출력을 자동으로 추적합니다.

다음 예시는 함수를 추적하는 방법을 보여줍니다.

<Tabs>
  <Tab title="Python">
    ```python lines {5,10,24} theme={"system"}
    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"))
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash theme={"system"}
    // @noErrors
    import Anthropic from '@anthropic-ai/sdk';
    import * as weave from 'weave';
    import { wrapAnthropic } from 'weave';

    await weave.init('anthropic_project');
    const client = wrapAnthropic(new Anthropic());

    const callAnthropic = weave.op(async function callAnthropic(
        userInput: string,
        model: string
    ): Promise<string> {
        const message = await client.messages.create({
            max_tokens: 1024,
            messages: [
                {
                    role: 'user',
                    content: userInput,
                }
            ],
            model: model,
        });
        const content = message.content[0];
        return content.type === 'text' ? content.text : '';
    });

    const generateJoke = weave.op(async function generateJoke(
        topic: string
    ): Promise<string> {
        return callAnthropic(`Tell me a joke about ${topic}`, 'claude-3-haiku-20240307');
    });

    console.log(await generateJoke('chickens'));
    console.log(await generateJoke('cars'));
    ```
  </Tab>
</Tabs>

함수를 `weave.op()`로 데코레이트하면 Weave가 해당 함수의 코드, 입력, 출력을 캡처합니다. Op를 사용하면 중첩 함수를 포함해 원하는 어떤 함수든 추적할 수 있습니다.

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/anthropic_ops.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=f113e2cae615ba622c85b095fd506c73" alt="anthropic_ops.png" width="2566" height="1278" data-path="products/wandb/weave/_media/anthropic_ops.png" />](/ko/products/wandb/weave/guides/tracking/ops)

<h2 id="create-a-model-for-easier-experimentation">
  더 쉽게 실험할 수 있도록 `Model` 만들기
</h2>

개별 Call을 트레이싱하고 있다면, 다음 단계는 관련 매개변수를 한데 묶어 여러 설정을 비교할 수 있도록 하는 것입니다.

<Note>
  `weave.Model` 클래스는 Weave Python SDK에서만 사용할 수 있습니다. TypeScript에서는 `weave.op()` 래퍼를 사용하여 구조화된 매개변수가 있는 함수를 추적하세요.
</Note>

바뀌는 요소가 많으면 실험을 체계적으로 관리하기 어렵습니다. [`Model`](/ko/products/wandb/weave/guides/core-types/models) 클래스를 사용하면 system 프롬프트나 사용 중인 모델 등 앱의 실험 세부 정보를 캡처하고 정리할 수 있으므로, 앱의 여러 반복 버전을 체계적으로 관리하고 비교할 수 있습니다.

모델은 코드 버전 관리와 입력 및 출력 캡처 외에도 애플리케이션의 동작을 제어하는 구조화된 매개변수를 캡처합니다. 이를 통해 어떤 매개변수가 가장 효과적인지 알아낼 수 있습니다. Weave 모델은 `serve` 및 [평가](/ko/products/wandb/weave/guides/core-types/evaluations)와 함께 사용할 수도 있습니다.

다음 예시에서는 `model`과 `temperature`를 바꿔 가며 실험할 수 있습니다.

```python lines theme={"system"}
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`의 새 버전을 생성하고 추적합니다. 이를 통해 트레이스 데이터를 코드 변경 사항과 연결할 수 있으며, 사용 사례에 가장 적합한 설정이 무엇인지 확인하는 데에도 도움이 됩니다.

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/anthropic_model.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=68d81f117bb003f5aaaf46d5f731b79c" alt="anthropic_model.png" width="2892" height="1464" data-path="products/wandb/weave/_media/anthropic_model.png" />](https://forge.coreweave.com/wandb/capecape/anthropic_project/weave/calls)

<h2 id="tools-function-calling">
  도구 (함수 호출)
</h2>

Weave는 일반 메시지뿐 아니라 Anthropic의 도구 사용 인터페이스도 계측하므로, 에이전트형 워크플로를 엔드투엔드로 트레이스할 수 있습니다.

Anthropic은 Claude가 함수 호출을 요청할 수 있도록 [도구](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview) 인터페이스를 제공합니다. Weave는 대화 전반에서 도구 정의, 도구 사용 요청, 도구 결과를 자동으로 추적합니다.

다음은 Anthropic 도구 설정을 보여 주는 축약된 예시입니다.

<Tabs>
  <Tab title="Python">
    ```python lines theme={"system"}
    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)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript twoslash theme={"system"}
    // @noErrors
    const message = await 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: 'claude-3-opus-20240229',
    });

    console.log(message);
    ```
  </Tab>
</Tabs>

Weave는 대화의 각 단계에서 도구 정의, Claude의 도구 사용 요청, 도구 결과를 자동으로 캡처합니다.

[<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/anthropic_tool.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=7afe7a26d7b84964a5aa948c8e7a4a31" alt="anthropic_tool.png" width="2512" height="1218" data-path="products/wandb/weave/_media/anthropic_tool.png" />](https://forge.coreweave.com/wandb/capecape/anthropic_project/weave/calls)
