Claude 4 Sonnet と Claude 4 Opus の始め方
Anthropic の新しい Claude 4 Sonnet と Opus を、API を使ってローカルの Python 環境でセットアップし実行するためのガイド。この記事は機械翻訳です。誤訳の可能性があればコメント欄でお知らせください。
Created on August 27|Last edited on August 27
Comment
💡
Claude 4 は Anthropicの最新世代の大規模言語モデル――とりわけ新しい Sonnet 4 と Opus 4――は、コーディング能力や推論において新たな標準を打ち立てており、 エージェント ワークフローこれらのモデルは拡張思考と統合されたツール使用をサポートしており、Claude が手順を追って推論し、電卓やデータベース、その他のサービスを呼び出しつつ、その過程の各ステップを透過的に表示できます。
このクイックスタートでは、生の Claude 4 API を実際に扱いながら W&B Weave 自分のワークフロー内で、Claude がどのように推論し、ツールを使うのかを正確に追跡・可視化し、デバッグできるようにします。
本記事の内容概要:
目次
Anthropic APIキーの取得Claude 4 Sonnet と Claude 4 Opus の料金W&B WeaveClaude 4 Sonnet と Claude 4 Opus をはじめようステップ1: Anthropic の API キーステップ2: PipでAnthropicとW&B Weaveをインストールするステップ3: 推論用スクリプトの作成Claude Opus 4 と Claude Sonnet 4 のツール使用結論関連資料
💡
Anthropic APIキーの取得
Claude 4 Sonnet と Claude 4 Opus を使い始める前に、アクセス用の API キーが必要です。まずは Anthropic のアカウントを作成し、続いて次のページへ移動しましょう。Anthropic の API コンソール 左下の「API Keys」をクリックします。

次に、「Create Key」ボタンをクリックしてキーを作成します。

キーに名前を付け、「Add」をクリックします。

準備完了です。
Claude 4 Sonnet と Claude 4 Opus の料金
本稿執筆時点(2025年5月24日)の Claude 4 Opus と Sonnet の料金は以下のとおりです(参考として Sonnet 3.7 の料金も併記します)。

W&B Weave
主な特長は @weave.op() デコレータで、追跡したい関数の上に付け加えます。Python におけるデコレータは、別の関数に機能を付与する特別な関数です。これを追加することで @weave.op() 関数定義の上にこれを付けることで、Weave にその関数の入力と出力を自動的に記録させます。これにより、関数に渡されるデータと返される結果を簡単に監視できます。
コードを実行した後は、Weave のダッシュボードでこれらのログを確認できます。関数呼び出しの詳細な可視化やトレースが提供されるため、デバッグや実験データの整理に役立ち、Claude を用いた開発プロセスをより効率的かつ洞察的なものにします。
Claude 4 Sonnet と Claude 4 Opus をはじめよう
始める前にいくつかの注意点があります。
- このチュートリアルのスクリーンショットは、Google Colab を使用している例を示しています。
- Google Colab の優れている点のひと��は、テキストセルにコメントや文脈を追記できることです。

ステップ1: Anthropic の API キー
まずは Anthropic の API キーを設定します。
そのためのコードは次のとおりです。
if "ANTHROPIC_API_KEY" not in os.environ:os.environ["ANTHROPIC_API_KEY"] = "your api key"
"your api key" を自身の Anthropic API Key に置き換えてください。
ステップ2: PipでAnthropicとW&B Weaveをインストールする
Claude 4 Sonnet と Claude 4 Opus を動かすのに必要なのは Anthropic だけです。とはいえ、W&B Weave を使って入出力を手間なくトラッキングする方法もあわせて紹介します。
ちょうど良いタイミングなので Weights & Biases に登録する今のうちに済ませておくと、チュートリアルを中断せずに進められます。
そのためのコードは次のとおりです。
!pip install anthropic weave
そのセルを実行してください。

インストールが完了したので、使用するためにインポートする必要があります
Pythonが初めての場合は基本的には、ライブラリをインストールするとそのコードを取得することになり、インポートするとそのライブラリを実際に使えるようにします。
💡
ステップ3: 推論用スクリプトの作成
では、Anthropic の Python SDK を使って Claude Sonnet 4 または Claude Opus 4 のどちらでも推論を実行できるスクリプトを書きましょう。出力のストリーミング有無を選べるオプションに加えて、Claude の拡張思考(回答の前に内部推論をストリーミング表示)を有効化する設定も用意します。
以下に、堅牢な Python スクリプト(および @weave.op (入出力の追跡付き)で、そのままコピーして用途に合わせて調整できます。
import os# Optional: default API key fallback for demo (replace/remove for production!)if "ANTHROPIC_API_KEY" not in os.environ:os.environ["ANTHROPIC_API_KEY"] = "your_claude_api_key"if "WANDB_API_KEY" not in os.environ:os.environ["WANDB_API_KEY"] = "your_wandb_api_key"import anthropicimport osimport weave; weave.init("claude_4")# === CONFIGURABLE ARGS ===streaming = True # Set to True for streaming, False for classic responseenable_thinking = True # Set to True to enable extended thinking# ==== MODEL SELECTION ====# Claude Opus 4 (highest reasoning, highest cost)model = "claude-opus-4-20250514"# Claude Sonnet 4 (fast, less expensive)# model = "claude-sonnet-4-20250514"client = anthropic.Anthropic()@weave.opdef claude_inference(prompt, model, streaming=True, enable_thinking=True):"""Run inference on given prompt with specified Claude model,printing thinking and response as they arrive,and returning the full final response text.Returns: text response as a string, or None on failure"""kwargs = dict(model=model,max_tokens=2048 if enable_thinking else 512,messages=[{"role": "user", "content": prompt}],)if enable_thinking:kwargs["thinking"] = {"type": "enabled", "budget_tokens": 1024}response_text = ""if streaming:with client.messages.stream(**kwargs) as stream:for event in stream:if event.type == "content_block_start":block_type = event.content_block.typeif block_type == "thinking":print("\n[THINKING]: ", end="", flush=True)elif block_type == "text":print("\n[RESPONSE]: ", end="", flush=True)elif event.type == "content_block_delta":d = event.deltaif getattr(d, "type", None) == "thinking_delta":print(d.thinking, end="", flush=True)elif getattr(d, "type", None) == "text_delta":print(d.text, end="", flush=True)response_text += d.textelif event.type == "content_block_stop":print() # Finish this blockelse:response = client.messages.create(**kwargs)for block in response.content:if block.type == "thinking" and block.thinking.strip():print("\n[THINKING]:", block.thinking.strip(), flush=True)elif block.type == "text" and block.text.strip():print("\n[RESPONSE]:", block.text.strip(), flush=True)response_text += block.text.strip()# return response_text if response_text else Nonereturn str(response_text)# === USAGE EXAMPLE ===prompt = ("If a train travels 60 miles per hour for 2.5 hours, how far does it go? ""Show your reasoning step by step.")final_answer = claude_inference(prompt,model=model,streaming=streaming,enable_thinking=enable_thinking)print("\n\n=== FINAL RETURNED RESPONSE ===\n", final_answer)
モデルを切り替えるには、model 変数を変更するだけです。Opus 4 を使う場合は、次のように設定します。 model = "claude-opus-4-20250514"Sonnet 4 を使う場合は、次のように設定します。 model = "claude-sonnet-4-20250514"・トグル streaming および enable_thinking スクリプトの先頭で設定し、推論過程(思考)やストリーム出力を生成と同時に表示できるようにします。
スクリプトを実行すると、Weave 上でモデルの出力を可視化できるリンクが表示されます。

リンクをクリックすると、モデルの入力と出力を確認できます。

Claude には「通常モード(非思考)」と「拡張思考」の2つの応答モードがあります。非思考モードでは、一般的なチャットボットと同様に最終的な答えだけが返され、答えに至る過程は表示されません。
まずClaudeは内部の推論過程を段階的に(「シンキングブロック」)表示し、その後に最終的な回答を返します。これにより、Claude���どのように結論に至ったかを可視化でき、透明性の確保、デバッグ、詳細なロジックが求められるタスクに役立ちます。
コード内では、次の設定で思考モードを有効化しました。 enable_thinking = True さらに、API呼び出しを構成する際に次のブロックを追加します。
if enable_thinking:kwargs["thinking"] = {"type": "enabled", "budget_tokens": 1024}
これはClaudeに拡張思考を使うよう指示し、さらに「思考バジェット」を設定します。ここでの最小値は budget_tokens は1024トークンです。この数値は、Claudeが内部の推論処理に使える出力トークンの上限を示します。あなたの合計 max_tokens リクエストでは、より大きい値を指定する必要があります budget_tokens「思考」用トークンに加えて最終回答用のトークンも確保する必要があるためです。例えば、思考バジェットが1024の場合は、 max_tokens たとえば2048にして、思考と最終回答の両方に十分な余裕を確保します。
Claude Opus 4 と Claude Sonnet 4 のツール使用
Claude 4 Sonnet と Claude 4 Opus の大きな特長のひとつが「ツール使用」です。これは、推論の過程で計算機やデータベースのようなカスタム関数を呼び出せる機能を指します。これにより、Claude は一般的な知識だけに頼らず、実データや独自ロジック、サービスを用いて複雑なプロンプトに回答できるようになります。
例として、ビジネスアナリティクスの場面を考えてみましょう。たとえば「1個あたり$50で150個売れた場合の総売上はいくらか。さらに、それは平均月次売上と比べてどうか」を知りたいとします。Claude 4 のツール使用を使えば、モデルに掛け算を実行させると同時に、実データまたはサンプルの売上データを参照させることができます。ビジネスロジックを自分でコーディングしなくても、1ターンで両方を完了できます。
この機能を使うには、Claude の API 呼び出し時に計算機やデータ取得ツールなどをツールとして登録します。たとえば Claude がタスクを進める中で――「150個を$50で販売した場合の総売上はいくらで、月次平均と比べてどうなりますか?」――モデルは関数を呼び出して数値を計算し、データを参照し、その結果について推論するところまでを、1回のターンでまとめて実行できます。
インターリーブ思考を有効にすると、Claude はツール呼び出しの合間に一時停止します中間解析を共有し、直近の結果を振り返って、次に何をすべきかを賢く判断します。こうした段階的な推論により、どのツールを使うべきかをより深く考えられるようになり、最初からすべてのツール選択を一度に予測させる必要がなくなります。
始め方はシンプルです。関数を定義し、その入出力を記述して、tools パラメータで Claude に渡します。より高い可視性と高度な推論が必要な場合は、提供されているベータ用ヘッダーでインターリーブ思考を有効にします。すると Claude は、シンキングブロック、ツール呼び出し、結果を交互に提示し、各ステップで明確さを保ちながら解法を積み上げていきます。
インターリーブ思考の動作を示すために、通常モードと併用した例を紹介します。両方の応答が Weave 内でどのように表示されるかを確認できます。
import anthropicimport astimport osimport weave; weave.init("claude_4")REVENUE_PER_MONTH = [5000, 6000, 4800, 5300, 5500, 5100, 4950, 5400, 5200, 5100, 5300, 5000]def handle_db_command(command):cmd = command.lower().strip()if cmd == "get average monthly revenue":avg = sum(REVENUE_PER_MONTH) / len(REVENUE_PER_MONTH)return f"{avg:.2f}"elif cmd == "get total yearly revenue":return str(sum(REVENUE_PER_MONTH))elif cmd == "get best month":month = REVENUE_PER_MONTH.index(max(REVENUE_PER_MONTH)) + 1val = max(REVENUE_PER_MONTH)return f"Month {month}, revenue: {val}"else:return "Error: unknown database command"def safe_eval(expr):try:node = ast.parse(expr, mode='eval')for sub in ast.walk(node):if not isinstance(sub, (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Num, ast.Load, ast.operator, ast.unaryop, ast.Constant)):raise ValueError("Unsafe")return eval(expr, {"__builtins__": {}})except Exception as e:return f"Error: {e}"calculator_tool = {"name": "calculator","description": "Safely evaluates arithmetic expressions (e.g. '150 * 50')","input_schema": {"type": "object","properties": {"expression": {"type": "string", "description": "Math expression"}},"required": ["expression"]}}database_tool = {"name": "database","description": ("A company revenue database. Supported commands (use as the `command` field):\n""- 'get average monthly revenue' (Returns yearly average)\n""- 'get total yearly revenue'\n""- 'get best month' (Returns best month and its value)\n""Do NOT use SQL. Only use one of the 3 supported commands."),"input_schema": {"type": "object","properties": {"command": {"type": "string", "description": "Plain database command"}},"required": ["command"]}}PROMPT = ("What's the total revenue if we sold 150 units of product A at $50 each?\n""Also, compare this to our average monthly revenue in our database.\n\n""Instructions for the database tool:\n""- Only use one of these commands for the 'command' field:\n"" * get average monthly revenue\n"" * get total yearly revenue\n"" * get best month\n""Do not use SQL. Only use one of these simple command phrases.")client = anthropic.Anthropic()def execute_tools(blocks):"""Find all tool calls in blocks.Return tool_result dicts to send as messages back to Claude."""tool_results = []for b in blocks:if b.type == "tool_use":if b.name == "calculator":val = safe_eval(b.input['expression'])out = str(val)elif b.name == "database":out = handle_db_command(b.input['command'])else:out = "Error: unknown tool"tool_results.append({"type": "tool_result", "tool_use_id": b.id, "content": out})return tool_results# === ONE MODEL CALL (one assistant reply, may be tool call or final text) ===@weave.op()def claude_message_op(msg_history, interleaved=False):"""Runs a single Anthropic API call (one assistant step).Returns list of blocks (tool calls or text/thinking blocks)."""extra_headers = ({"anthropic-beta": "interleaved-thinking-2025-05-14"} if interleaved else None)response = client.messages.create(model="claude-sonnet-4-20250514",max_tokens=2512,tools=[calculator_tool, database_tool],thinking={"type": "enabled", "budget_tokens": 2000},extra_headers=extra_headers,messages=msg_history,)return response.content# === MAIN CHAIN ===@weave.op()def run_claude_tools_full_chain(prompt_text=PROMPT, interleaved=False, max_loops=5):"""Main loop: calls single-step Claude; if tool call, executes it and calls Claude again etc.Each step is a tracked @weave.op for graph lineage.Returns the full set of blocks and tool call/results for inspection in Weave."""all_steps = []msg_history = [{"role": "user", "content": prompt_text}]for loop in range(max_loops):assistant_blocks = claude_message_op(msg_history, interleaved=interleaved)all_steps.append({"assistant_blocks": assistant_blocks, "msg_history": list(msg_history)})tool_results = execute_tools(assistant_blocks)if not tool_results:breakmsg_history.append({"role": "assistant", "content": assistant_blocks})msg_history.append({"role": "user", "content": tool_results})all_steps[-1]["tool_results"] = tool_resultsreturn all_stepsdef print_blocks(blocks):for block in blocks:if block.type == "thinking":print(f"[THINKING BLOCK]: {block.thinking}\n{'-'*60}")elif block.type == "tool_use":print(f"[TOOL USE BLOCK]: {block.name} with input {block.input} (id={block.id}) {'-'*40}")elif block.type == "text":print(f"[RESPONSE BLOCK]:\n{block.text}\n{'-'*60}")# interleaved = Truesteps = run_claude_tools_full_chain(prompt_text=PROMPT,interleaved=True,max_loops=5)print("\n====== Full Conversation Step Trace ======")for i, step in enumerate(steps):print(f"\n----- Assistant Step {i+1} -----")print_blocks(step["assistant_blocks"])if "tool_results" in step:print(f"\nTOOL RESULTS: {step['tool_results']}")# Optionally, the "final" response blocks (which is the last 'assistant_blocks' returned)final_blocks = steps[-1]["assistant_blocks"]print("\n--- Final Assistant Response ---\n")print_blocks(final_blocks)# interleaved = Falsesteps = run_claude_tools_full_chain(prompt_text=PROMPT,interleaved=False,max_loops=5)print("\n====== Full Conversation Step Trace ======")for i, step in enumerate(steps):print(f"\n----- Assistant Step {i+1} -----")print_blocks(step["assistant_blocks"])if "tool_results" in step:print(f"\nTOOL RESULTS: {step['tool_results']}")# Optionally, the "final" response blocks (which is the last 'assistant_blocks' returned)final_blocks = steps[-1]["assistant_blocks"]print("\n--- Final Assistant Response ---\n")print_blocks(final_blocks)
〜で実行する場合は interleaved=True、Claude は内部推論、ツール呼び出し、ツールの実行結果、最終的なテキスト応答を交互に行います。すべてのツール呼び出しを単一の応答内であらかじめ計画するのではなく、プロセス全体を段階的に解いていきます。この手法は透明性を高めるだけでなく、推論を進めながらツール呼び出しの結果を振り返って取り入れられるため、答えがどのように組み上がっていくかを明確なステップごとに示すことができます。
このオーケストレーションは、まずカスタムツールを2種類登録することで管理します。ひとつは電卓で、実装方法は safe_eval(), そして、擬似的なデータベース問い合わせインターフェースで、担当は handle_db_command(). 各ツールは、その機能だけでなく明示的な入力スキーマでも記述され、関数呼び出し時にどのような引数を渡せるかをClaudeが把握できるようになっています。
スクリプトを実行すると、結果が Weave 内に表示されます。

Weave 内では、上位レベルの呼び出しと run_claude_tools_full_chain—プロンプト、ツール使用、アシスタントの判断—に加えて、Claude が生成する各「思考」単位(シンキング)、ツール呼び出し、テキスト応答ブロックまで、すべてを記録します。これにより、完全なセマンティックトレースが得られ、あらゆる段階で会話のデバッグ、比較、監査が可能になります。
結論
わずかな手順で、Anthropic の Python SDK を使って Claude 4 をセットアップし、W&B Weave と統合して、モデルの推論やツール使用のあらゆる側面を完全に可視化できるようにしました。このワークフローにより、各インタラクション、ツール呼び出し、中間ステップまで追跡できるため、デバッグや最適化が容易になり、Claude がどのように答えに到達したのかを正確に理解できます。
この基盤があれば、ツールを活用する大規模言語モデルを用いた複雑なAIワークフローを、確実に構築・テスト・監視できます。プロジェクトの進展に合わせて、パイプラインを継続的に開発・分析・改良していきましょう。さらに詳しいヒントや高度な使い方については、以下の資料をご覧ください。
関連資料
Attribute-Value Extraction With GPT-3 and Weights & Biases
In this article, we learn how to fine-tune OpenAI's GPT-3 for attribute-value extraction from products, looking at the challenges and how to overcome them.
Automating Change Log Tweets with Few-Shot Learning and GPT-3
A text summarization recipe using OpenAI GPT-3's few-shot learning and Weights & Biases
o1 model Python quickstart using the OpenAI API
Getting set up and running the new o1 models in Python using the OpenAI API. We'll be working with o1-preview.
Add a comment