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

# Anthropic

> Anthropic SDK를 통해 이루어지는 LLM Call를 Weave로 자동으로 추적하고 로깅하세요

<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를 통합하면 [Python](https://github.com/anthropics/anthropic-sdk-python)과 [TypeScript](https://github.com/anthropics/anthropic-sdk-typescript)에서 Anthropic SDK를 통해 이루어지는 LLM Call를 자동으로 추적하고 로깅합니다. Weave는 Anthropic의 `Messages.create()`를 자동으로 호출해 이를 수행합니다.

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

<div id="traces">
  ## 트레이스
</div>

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

다음 예제는 Anthropic에 대한 기본적인 call에 Weave를 통합하는 방법을 보여줍니다.

<Tabs>
  <Tab title="Python">
    ```python lines {6} theme={null}
    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={null}
    // @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가 트레이싱 정보를 자동으로 캡처하고 링크를 출력합니다. 링크를 클릭하면 Weave UI에서 트레이스를 확인할 수 있습니다.

[<img src="https://mintcdn.com/wb-21fd5541/IuXGrpyeFw4WzHgb/weave/guides/integrations/imgs/anthropic_trace.png?fit=max&auto=format&n=IuXGrpyeFw4WzHgb&q=85&s=cbe99591b6a85d0e6e73db6e34df2599" alt="anthropic_trace.png" width="3024" height="1594" data-path="weave/guides/integrations/imgs/anthropic_trace.png" />](https://wandb.ai/capecape/anthropic_project/weave/calls)

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

`weave.init()`만으로도 Anthropic SDK Call을 캡처할 수 있지만, 직접 만든 함수에 ops를 데코레이터로 적용하면 각 모델 Call을 둘러싼 애플리케이션 로직까지 포함하는 더 풍부한 트레이스를 얻을 수 있습니다.

Weave ops는 실험하면서 코드를 자동으로 버전 관리하고 입력과 출력을 캡처합니다. Python에서는 [`@weave.op()`](https://docs.wandb.ai/weave/guides/tracking/ops) 데코레이터를 사용하고, TypeScript에서는 [`weave.op()`](/ko/weave/reference/typescript-sdk/functions/op)으로 래핑해 [`Anthropic.messages.create()`](https://platform.claude.com/docs/en/build-with-claude/working-with-messages)를 호출하면 Weave가 입력과 출력을 대신 추적합니다.

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

<Tabs>
  <Tab title="Python">
    ```python lines {5,10,24} theme={null}
    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={null}
    // @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가 함수의 코드, 입력, 출력을 캡처합니다. 중첩 함수 등을 포함해 추적하려는 어떤 함수에도 ops를 사용할 수 있습니다.

[<img src="https://mintcdn.com/wb-21fd5541/IuXGrpyeFw4WzHgb/weave/guides/integrations/imgs/anthropic_ops.png?fit=max&auto=format&n=IuXGrpyeFw4WzHgb&q=85&s=27db880158748f4d5c7df9dec0545694" alt="anthropic_ops.png" width="2682" height="1282" data-path="weave/guides/integrations/imgs/anthropic_ops.png" />](https://docs.wandb.ai/weave/guides/tracking/ops)

<div id="create-a-model-for-easier-experimentation">
  ## 실험을 더 쉽게 하기 위한 `Model` 만들기
</div>

개별 Call을 추적하기 시작했다면, 다음 단계는 관련 매개변수를 함께 정리해 서로 다른 설정을 비교할 수 있도록 하는 것입니다.

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

여러 요소가 동시에 바뀌면 실험을 체계적으로 정리하기가 어렵습니다. [`Model`](/ko/weave/guides/core-types/models) 클래스를 사용하면 시스템 프롬프트나 사용 중인 모델처럼 앱 실험과 관련된 세부 정보를 캡처하고 정리할 수 있습니다. 이렇게 하면 앱의 다양한 반복 버전을 정리하고 비교하는 데 도움이 됩니다.

[`Model`](/ko/weave/guides/core-types/models)은 코드를 버전 관리하고 입력과 출력을 캡처하는 것에 더해, 애플리케이션의 동작을 제어하는 구조화된 매개변수도 캡처합니다. 이를 통해 어떤 매개변수가 가장 효과적인지 찾는 데 도움이 될 수 있습니다. 또한 Weave Models를 `serve` 및 [evaluations](/ko/weave/guides/core-types/evaluations)와 함께 사용할 수도 있습니다.

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

```python lines theme={null}
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/wb-21fd5541/IuXGrpyeFw4WzHgb/weave/guides/integrations/imgs/anthropic_model.png?fit=max&auto=format&n=IuXGrpyeFw4WzHgb&q=85&s=705c33e06250066a95cf3afdae7180d8" alt="anthropic_model.png" width="3008" height="1464" data-path="weave/guides/integrations/imgs/anthropic_model.png" />](https://wandb.ai/capecape/anthropic_project/weave/calls)

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

표준 메시지 외에도 Weave는 Anthropic의 도구 사용 인터페이스를 계측하여 에이전트 워크플로를 엔드투엔드로 트레이스할 수 있게 합니다.

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

다음의 축약된 예시는 Anthropic 도구 설정을 보여줍니다.

<Tabs>
  <Tab title="Python">
    ```python lines theme={null}
    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={null}
    // @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는 대화의 각 step에서 도구 정의, Claude의 도구 사용 요청, 도구 결과를 자동으로 캡처합니다.

[<img src="https://mintcdn.com/wb-21fd5541/IuXGrpyeFw4WzHgb/weave/guides/integrations/imgs/anthropic_tool.png?fit=max&auto=format&n=IuXGrpyeFw4WzHgb&q=85&s=1eb2d47700c4be0c9a4fe86986938250" alt="anthropic_tool.png" width="2628" height="1218" data-path="weave/guides/integrations/imgs/anthropic_tool.png" />](https://wandb.ai/capecape/anthropic_project/weave/calls)
