Forge
Skip to main content

Amazon Bedrock と W&B Weave を使い始めるには

Weave で API コールをトレースし管理して、LLM を最大限に活用する方法 これは AI 翻訳の記事です。誤訳の可能性があればコメント欄でお知らせください。
Last updated: September 4, 2025
W&B の一般公開を発表できることを大変うれしく思います WeaveLLM を活用したアプリケーションの開発と本番運用のためのツール群です。Weave では次のことができます。
  • ログとバージョン開発から本番まで、LLM とのやり取りとその周辺データ
  • 実験プロンプト技法、モデル変更、パラメータとともに
  • 評価モデルの改善状況を測定する
アクセスしてください https://wandb.me/weave にアクセスしてください 開始するには。
💡
この記事では、使い方を順を追って解説しますAmazon BedrockWeights & Biases の Weave と併せて
それでは始めましょう。



Amazon Bedrock:AWS 上の LLM のハブ

Amazon Bedrock は、AI21 Labs、Anthropic、Cohere、Meta、Mistral AI、Stability AI、Amazon の高性能な基盤モデルを単一の API で提供するフルマネージドサービスです。
安全性・プライバシー・責任ある生成 AI アプリケーションを構築するための機能を提供します。トップクラスの基盤モデルで実験し、カスタマイズできるほか、社内システムやデータソースと統合するエージェントを構築し、インフラ管理なしでサーバーレスに AI 機能をデプロイできます。なお、準備として必要になるのは、 モデルアクセスをリクエストする Bedrock の LLM を使うために。
それではコードに入っていきましょう。

Bedrock 内での LLM 呼び出し

このチュートリアルを進めるには、Weights & Biases と Bedrock の両方にアクセスできる必要があります。上記のリンクにアクセスすれば、すぐに開始できます。
まず、Weave をインストールしてください。
!pip install weave
次に、LLM とのやり取りをバージョン管理するための Weave プロジェクトを作成します。
import weave
weave.init('bedrock-weave')
では、呼び出し関数にデコレーターを付けましょう。 @weave.op() デコレーター
import json
import boto3

@weave.op() # <- just add this 😎
def generate_text(
model_id: str,
prompt: str,
max_tokens: int=400,
temperature: float=0.7,
) -> dict:
# Check your region model access page, in my case on us-east-1 region:
bedrock = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
"prompt": prompt,
"max_tokens": max_tokens,
"temperature": temperature,
})
response = bedrock.invoke_model(body=body, modelId=model_id)

response_body = json.loads(response.get('body').read())
return response_body.get('outputs')
これでモデルを呼び出し、最後に生成されたリンクをクリックできるようになりました。Amazon Bedrock API で基盤モデルを使うには、その モデルID。
レシピ生成に Mistral 7B モデルを使う例を紹介します。
model_id = 'mistral.mistral-7b-instruct-v0:2'

# this is the required prompt format for mistral instruct
prompt = """<s>[INST] Create a Vegan Carbonara Recipe[/INST] """

outputs = generate_text(model_id, prompt)

for index, output in enumerate(outputs):

print(f"Output {index + 1}\n----------")
print(f"Text:\n{output['text']}\n")
print(f"Stop reason: {output['stop_reason']}\n")

# Output 1
# ----------
# Text:
# Vegan Carbonara Recipe:

# Ingredients:
# - 12 oz (340g) spaghetti or other long pasta
# - 1/2 cup (120ml) unsweetened almond milk or cashew cream
# - 1/2 cup (100g) nutritional yeast
# - 1/3 cup (80g) cooked and mashed sweet potato or pumpkin
# - 1 tbsp olive oil
# - 1 cup (200g) steamed or roasted vegetables such as zucchini, broccoli, or asparagus
# - 1/2 cup (100g) chopped mushrooms
# - 1/2 cup (100g) chopped onion
# - 1 clove garlic, minced
# - 1/2 cup (100g) chopped walnuts or cashews, toasted
# - 1/2 cup (100g) vegetable bacon or pancetta, cooked and crumbled (optional)
# - Salt and freshly ground black pepper, to taste
# - Red pepper flakes, for serving (optional)
# - Fresh parsley or basil, for serving (optional)

# Instructions:

# 1. Cook the pasta according to package instructions in salted water until al dente. Drain and set aside, reserving 1 cup of the pasta water.

# 2. In a blender or food processor, combine the almond milk or cashew cream, nutritional yeast, mashed sweet potato or pumpkin, and olive oil. Blend until smooth and creamy. Taste and adjust seasoning with salt and pepper as needed.

# 3. In a large skillet, sauté the chopped onion, garlic, and

# Stop reason: length

Weave は何を記録しますか?

概要としては
  • コード生成AIのAPI呼び出しを囲むすべてのコードがバージョン管理され、保存されるようにする
  • データ可能であれば、あらゆるデータセットやナレッジストアなどをバージョン管理して保存する
  • トレース:生成AI呼び出しを取り巻く関数のトレースを恒久的に記録する
Weave を使えば簡単です。任意の Python 関数を包んでください @weave.op() すると、Weave が関数のコードを取得してバージョン管理し、すべての呼び出しのトレースを入力と出力を含めて記録します。
このようになります。

ご覧のとおり、停止理由は length 、そのため、増やしたい場合があります max_tokens 完全な回答を得るには param を調整します。パラメータを変更して関数を再実行すれば実現できます。
その結果、完全な出力を含む新しいトレースへのリンクが生成されます。


ネストされた呼び出しを追跡する

Python では任意の関数にデコレータを付けられます。たとえば、次のように作成できます。 run 関数を作成し、プロンプト整形と LLM 呼び出しのコールを別々に追跡します。
@weave.op()
def format_prompt(prompt: str) -> str:
return f"""<s>[INST] {prompt}[/INST] """

@weave.op()
def run(prompt: str) -> None:
prompt = format_prompt(prompt)

outputs = generate_text(model_id, prompt, max_tokens=1000)
for index, output in enumerate(outputs):

print(f"Output {index + 1}\n----------")
print(f"Text:\n{output['text']}\n")
print(f"Stop reason: {output['stop_reason']}\n")
run("What clothes do I need to pack in winter for a trip to Chamonix?")


異なるモデルを試す

Bedrock の非常に強力な点は、次の項目を変更するだけでモデルをすばやく切り替えられることです モデルIDたとえば、 Mixtral-8x7B そして実験を再実行します。
model_id = 'mistral.mixtral-8x7b-instruct-v0:1'

prompt = """<s>[INST] Create a Vegan Carbonara Recipe[/INST] """

outputs = generate_text(model_id, prompt, max_tokens=1000)

for index, output in enumerate(outputs):

print(f"Output {index + 1}\n----------")
print(f"Text:\n{output['text']}\n")
print(f"Stop reason: {output['stop_reason']}\n")
💡
モデルを切り替えると、プロンプトの書式を変える必要が生じる場合がある点に注意してください。今回のケースでは両方のモデルが同じプロンプト構造を共有しているため、更新は不要です。
💡

Anthropic の Claude モデルが Bedrock で利用可能

Bedrock の主要な特長のひとつは、 Anthropic の強力な Claude モデル群これらのモデルはサイズや性能がさまざまですが、それらを活用するためにコードを大きく変更する必要はありません。
@weave.op() # <- just add this 😎
def anthropic_call(
model_id: str,
messages: str,
max_tokens: int=400,
system_prompt: str=None,
) -> dict:
bedrock = boto3.client(service_name='bedrock-runtime')


body = json.dumps({
"system": system_prompt,
"messages": messages,
"max_tokens": max_tokens,
"anthropic_version": "bedrock-2023-05-31"
})
response = bedrock.invoke_model(
body=body,
modelId=model_id
)

response_body = json.loads(response.get('body').read())

outputs = response_body.get('content')
return outputs

モデルアクセス

Amazon Bedrock の利用者は、使用可能にするために各モデルへのアクセス権を申請する必要があります。追加のモデルへのアクセスを申請するには、Amazon Bedrock コンソールのナビゲーションペインで「モデルアクセス」を選択してください。詳しくは「モデルアクセス」を参照してください。
💡
Bedrock のランディングページ左下にあるリンクを探してください

より高度なユースケース:ドキュメント翻訳

Anthropic のモデルは非常に強力で、複雑なタスクの解決が可能です。ここでは例として、Claude を使って翻訳を行います。 W&B のドキュメントサイト
まず、このモデルは特定の形式のメッセージリストを想定しているため、プロンプトを少し異なる方法で整形する必要があります。 role そして content。システムプロンプトは追加の引数として渡されます kwargs ペイロードに対して:
from pathlib import Path
from dataclasses import dataclass

system_prompt = """
# Instructions

You are a documentation translation assistant from English to {output_language}. We are translating valid docusaurus flavored markdown. Some rules to remember:

- Do not add extra blank lines.
- The results must be valid docusaurus markdown
- It is important to maintain the accuracy of the contents but we don't want the output to read like it's been translated. So instead of translating word by word, prioritize naturalness and ease of communication.
- In code blocks, just translate the comments and leave the code as is.

## Formatting Rules

Do not translate target markdown links. Never translate the part of the link inside (). For instance here [https://wandb.ai/site](https://wandb.ai/site) do not translate anything, but on this, you should translate the [] part:
[track metrics](./guides/track), [create logs](./guides/artifacts).
"""

human_prompt = """
Here is a chunk of documentation in docusaurus Markdown format to translate. Return the translation only, without adding anything else.
<Markdown start>
{md_chunk}
<End of Markdown>
"""

@dataclass
class PromptTemplate:
system_prompt: str
human_prompt: str
language: str
@weave.op() # <- just add this 😎
def format_claude(self, md_chunk):
"A formatting function for Mistral Instruct models"
system_prompt = self.system_prompt.format(output_language=self.language)
human_prompt = self.human_prompt.format(md_chunk=md_chunk)
messages = [{"role":"user", "content":human_prompt}]
return system_prompt, messages
次に、PromptTemplate とモデル呼び出しを内部でリファクタリングできます weave.Model このようにしてコードを整理するためのオブジェクトです。
from weave import Model

class ClaudeDocTranslator(Model):
model_id: str='anthropic.claude-3-sonnet-20240229-v1:0'
max_tokens: int=2048
prompt_template: PromptTemplate
@weave.op()
def format_doc(self, path: Path) -> str:
"Read and format the document"
doc = Path(path).read_text()
system_prompt, messages = prompt_template.format_claude(doc)
return system_prompt, messages
@weave.op()
def translate(self, path: Path) -> dict:
system_prompt, messages = self.format_doc(path)
output = anthropic_call(
self.model_id,
messages=messages,
system_prompt=system_prompt,
max_tokens=self.max_tokens)
return output[0]['text']
では、ドキュメントを1つ翻訳してみましょう。
model = ClaudeDocTranslator(prompt_template=prompt_template)
out = model.translate(Path("./docs/quickstart.md"))

結論

この短いチュートリアルで、W&B と Bedrock の統合が理解できていれば幸いです。開始するには、いくつかの認証情報が必要です。次のことを行ってください。
モデリングをお楽しみください!

この記事は機械翻訳です。誤訳の可能性があればコメント欄でお知らせください。元のレポートはこちらをご覧ください。 元のレポートを見る