> ## 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

> 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 をコードに統合すると、[Python](https://github.com/anthropics/anthropic-sdk-python) と [TypeScript](https://github.com/anthropics/anthropic-sdk-typescript) の両方で、Anthropic SDK を使用した LLM Call が自動的にトラッキングされ、ログされます。Weave は、Anthropic の `Messages.create()` メソッドを自動的に呼び出すことでこれを実現します。

このガイドでは、トレースを取得する方法、独自の関数を op としてラップする方法、実験向けに再利用可能な `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](/ja/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">
  ## 独自の op でラップする
</div>

`weave.init()` だけでも Anthropic SDK の Call は取得できますが、独自の関数を op でデコレートすると、各 model call の前後にあるアプリケーション ロジックを含む、より豊富なトレースを取得できます。

Weave の op は、実験を進める中でコードを自動的にバージョン管理し、入力と出力を取得します。[`Anthropic.messages.create()`](https://platform.claude.com/docs/en/build-with-claude/working-with-messages) を呼び出す関数を、Python では [`@weave.op()`](https://docs.wandb.ai/weave/guides/tracking/ops) でデコレートし、TypeScript では [`weave.op()`](/ja/weave/reference/typescript-sdk/functions/op) でラップすると、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 はその関数のコード、入力、出力を取得します。op を使用すれば、ネストされた関数を含め、トラッキングしたい任意の関数をトラッキングできます。

[<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`](/ja/weave/guides/core-types/models) クラスを使用すると、system prompt や使用しているモデルなど、アプリの実験に関する詳細を取得して整理できます。これにより、アプリの異なるイテレーションを整理して比較しやすくなります。

コードのバージョン管理や入力と出力の取得に加えて、モデルはアプリケーションの動作を制御する構造化されたパラメーターも取得します。これにより、どのパラメーターが最も効果的かを検索しやすくなります。Weave モデルは、`serve` や [評価](/ja/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` の新しいバージョンを作成してトラッキングします。これにより、Trace Data をコードの変更に関連付けることができ、どの設定がユースケースに最も適しているかを判断するのに役立ちます。

[<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)
