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

# Bedrock

> Weave で Amazon Bedrock の LLM Call をトラッキングして監視し、基盤モデルとのやり取りと converse API の使用状況を取得します。

Weave は、Amazon Bedrock を通じて行われる LLM Call を自動的にトラッキングしてログします。Amazon Bedrock は、複数の AI プロバイダーの基盤モデルを統一された API で提供する AWS のマネージドサービスです。このインテグレーションを使用して、Bedrock の基盤モデルとのやり取りと `converse` API の使用状況を取得し、Bedrock ベースのアプリケーションをデバッグ、評価、監視できます。

Amazon Bedrock から Weave に LLM Call をログする方法は複数あります。`weave.op` を使用すると、Bedrock モデルへのあらゆる Call をトラッキングするための再利用可能なオペレーションを作成できます。また、Anthropic モデルを使用している場合は、Weave の組み込み Anthropic インテグレーションを使用できます。

<Tip>
  最新のチュートリアルについては、[W\&B on Amazon Web Services](https://wandb.ai/site/partners/aws/) をご覧ください。
</Tip>

<h2 id="traces">
  トレース
</h2>

クライアントにパッチを適用すると、Weave は Bedrock API の呼び出しのトレースを自動的に取得します。Weave を初期化し、クライアントにパッチを適用した後は、通常どおり Bedrock クライアントを使用します。

```python lines theme={"system"}
import weave
import boto3
import json
from weave.integrations.bedrock.bedrock_sdk import patch_client

weave.init("my_bedrock_app")

# Bedrock クライアントを作成し、パッチを適用します
client = boto3.client("bedrock-runtime")
patch_client(client)

# 通常どおりクライアントを使用します
response = client.invoke_model(
    modelId="anthropic.claude-3-5-sonnet-20240620-v1:0",
    body=json.dumps({
        "anthropic_version": "bedrock-2023-05-31",
        "max_tokens": 100,
        "messages": [
            {"role": "user", "content": "What is the capital of France?"}
        ]
    }),
    contentType='application/json',
    accept='application/json'
)
response_dict = json.loads(response.get('body').read())
print(response_dict["content"][0]["text"])
```

同じパッチ適用済みクライアントは、`converse` API を使用する際にもトレースを取得します。

```python lines theme={"system"}
messages = [{"role": "user", "content": [{"text": "What is the capital of France?"}]}]

response = client.converse(
    modelId="anthropic.claude-3-5-sonnet-20240620-v1:0",
    system=[{"text": "You are a helpful AI assistant."}],
    messages=messages,
    inferenceConfig={"maxTokens": 100},
)
print(response["output"]["message"]["content"][0]["text"])

```

<h2 id="wrap-calls-with-your-own-ops">
  独自の op で Call をラップする
</h2>

Bedrock の Call を独自の op でラップすると、関連するロジックをまとめ、カスタム入力を取得し、追跡対象の同じ関数をアプリケーション全体で再利用できます。`@weave.op()` デコレーターを使用して、再利用可能なオペレーションを作成します。次の例では、`invoke_model` と `converse` の両方の API を示します。

```python lines theme={"system"}
@weave.op
def call_model_invoke(
    model_id: str,
    prompt: str,
    max_tokens: int = 100,
    temperature: float = 0.7
) -> dict:
    body = json.dumps({
        "anthropic_version": "bedrock-2023-05-31",
        "max_tokens": max_tokens,
        "temperature": temperature,
        "messages": [
            {"role": "user", "content": prompt}
        ]
    })

    response = client.invoke_model(
        modelId=model_id,
        body=body,
        contentType='application/json',
        accept='application/json'
    )
    return json.loads(response.get('body').read())

@weave.op
def call_model_converse(
    model_id: str,
    messages: str,
    system_message: str,
    max_tokens: int = 100,
) -> dict:
    response = client.converse(
        modelId=model_id,
        system=[{"text": system_message}],
        messages=messages,
        inferenceConfig={"maxTokens": max_tokens},
    )
    return response
```

<Frame>
  <img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/bedrock_converse.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=cb9b6bf7ec97dfd5c7e8e914927ee681" alt="Weave での Bedrock Converse インテグレーションと呼び出しのトレースおよび応答データ" width="3394" height="1520" data-path="products/wandb/weave/_media/bedrock_converse.png" />
</Frame>

<h2 id="create-a-model-for-easier-experimentation">
  実験を容易にするために `Model` を作成する
</h2>

Weave `Model` は設定と予測ロジックをひとまとめにすることで、パラメーターを繰り返し調整し、run を並べて比較できるようにします。Weave `Model` を作成して、実験をより適切に整理し、パラメーターを取得します。次の例では、`converse` API を使用します。

```python lines theme={"system"}
class BedrockLLM(weave.Model):
    model_id: str
    max_tokens: int = 100
    system_message: str = "You are a helpful AI assistant."

    @weave.op
    def predict(self, prompt: str) -> str:
        "Generate a response using Bedrock's converse API"
        
        messages = [{
            "role": "user",
            "content": [{"text": prompt}]
        }]

        response = client.converse(
            modelId=self.model_id,
            system=[{"text": self.system_message}],
            messages=messages,
            inferenceConfig={"maxTokens": self.max_tokens},
        )
        return response["output"]["message"]["content"][0]["text"]

# モデルを作成して使用します
model = BedrockLLM(
    model_id="anthropic.claude-3-5-sonnet-20240620-v1:0",
    max_tokens=100,
    system_message="You are an expert software engineer that knows a lot of programming. You prefer short answers."
)
result = model.predict("What is the best way to handle errors in Python?")
print(result)
```

この方法では、実験をバージョン管理し、Bedrock ベースのアプリケーションのさまざまな設定をトラッキングできます。

<h2 id="learn-more">
  詳細情報
</h2>

以下の資料では、Weave で Amazon Bedrock を探索・評価するためのその他の方法を紹介します。

<h3 id="try-bedrock-in-the-weave-playground">
  Weave プレイグラウンドで Bedrock を試す
</h3>

セットアップなしで Weights & Biases UI で Amazon Bedrock のモデルを試すには、[LLM プレイグラウンド](/ja/products/wandb/weave/guides/tools/playground)をご利用ください。

<h3 id="report-compare-llms-on-bedrock-for-text-summarization-with-weave">
  Report: Weave でテキスト要約用の Bedrock 上の LLM を比較する
</h3>

[Amazon Bedrock 上の LLM の評価](https://forge.coreweave.com/wandb/byyoung3/ML_NEWS3/reports/Compare-LLMs-on-Amazon-Bedrock-for-text-summarization-with-W-B-Weave--VmlldzoxMDI1MTIzNw) の report では、Bedrock と Weave を組み合わせて、要約タスク用の LLM を評価・比較する使い方を説明しています。この report にはコードサンプルが含まれています。


## Related topics

- [Bedrock Agents](/ja/products/wandb/weave/guides/integrations/bedrock_agents.md)
