Forge
Skip to main content

Tutorial: Get started with Claude Opus 4.7

Getting set up and running Anthropic's new Claude Opus 4.7 on your machine in Python using the API.
Last updated: June 5, 2026
Like everyone else, I was excited to jump right in and start playing around with Claude 4.7 as soon as I heard about it in the announcement. I figured you might, too, and so I put together this quickstart.
💡
Claude Opus 4.7 is Anthropic's most capable generally available model to date. It's a direct upgrade to Opus 4.6, with particular gains in advanced software engineering, long-horizon agentic work, and vision. It keeps the 1M-token context window and 128K output tokens from 4.6, but introduces important changes under the hood: high-resolution image support (2576px / 3.75MP), a new tokenizer, and several breaking changes you need to plan for, which we'll cover below.
Because Opus 4.7 builds directly on the 4.6 architecture, all major foundational changes (such as adaptive thinking and the removal of message prefilling) apply here.
In this tutorial, you'll get hands-on with the Claude Opus 4.7 API and W&B Weave to track, visualize, and debug exactly how Claude reasons and uses tools within your own workflows.
Here's what we'll be covering:


Step 0: Prerequisites

We assume in this tutorial hat you have and Anthropic API key, which you can get in the Claude Console. 



Claude Opus 4.7 pricing

As of this writing (April 2026), the pricing for Claude Opus 4.7 and the rest of the current model family is the following:
ModelInputOutput
Claude Opus 4.7$5 / MTok$25 / MTok
Claude Opus 4.6$5 / MTok$25 / MTok
Claude Sonnet 4.6$3 / MTok$15 / MTok
Claude Haiku 4.5$1 / MTok$5 / MTok

Opus 4.7 is priced identically to Opus 4.6. The 1M context window is available at standard API pricing, and batch processing still offers a 50% discount.
However, there is a major cost nuance worth flagging: Opus 4.7 uses a new tokenizer that produces roughly 1.0x to 1.35x as many tokens as older models for the exact same input text, depending on the content type. Additionally, the model thinks more at higher effort levels. The per-token price is unchanged, but your effective cost per request will likely rise slightly. Budget accordingly if you're migrating production traffic!

W&B Weave

W&B Weave enhances our project by offering a streamlined way to track and evaluate model outputs. Before you can use Weave, you'll simply need to create a free account. The rest is magic (OK, it's only kind-of magic).
The key feature is the @weave.op() decorator, which you add above any function you want to track. This instructs Weave to automatically log the inputs and outputs of that function, making it incredibly easy to debug long-running agentic loops.

Step 1: Installation and global setup

To make Claude Opus 4.7 work, you only need the Anthropic SDK. That said, we'll be showing you how you can effortlessly track your inputs and outputs using W&B Weave.
First, install the libraries in your terminal or notebook:
!pip install -U anthropic weave pillow
Next, let's set up our global environment. We will import all the libraries we need for the entire tutorial, set our API keys, initialize the Anthropic client, and start our Weave project. Run this once at the top of your script or notebook:
import os
import ast
import base64
import anthropic
import weave

# --- 1. Set API Keys ---
if "ANTHROPIC_API_KEY" not in os.environ:
os.environ["ANTHROPIC_API_KEY"] = "your_anthropic_api_key"
if "WANDB_API_KEY" not in os.environ:
os.environ["WANDB_API_KEY"] = "your_wandb_api_key"

# --- 2. Initialize Clients ---
client = anthropic.Anthropic()
weave.init("claude_opus_4_7_project")
You'll want to replace "your_anthropic_api_key" and your_wandb_api_key with your Anthropic and W&B API keys.

Step 2: Installing Anthropic and W&B Weave via pip

To make Claude Opus 4.7 work, you only need the Anthropic SDK, but we'll also install Weave to effortlessly track our inputs and outputs:
!pip install -U anthropic weave
...and then run the cell.

Now you've installed it, we still need to import it for use.
💡 If you're new to Python, basically when we install a library we simply grab the code. When we import it, we make that library available for use.

Step 3: Writing the inference script

Now let's write a script to run inference with Claude Opus 4.7 using Anthropic's Python SDK. We'll enable Adaptive Thinking, the recommended approach that lets Claude dynamically decide when and how deeply to reason before answering.
Below is a robust Python script (using @weave.op to track inputs and outputs) that you can copy and adapt.
# === CONFIGURABLE ARGS ===
streaming = True
enable_thinking = True

@weave.op
def claude_inference(prompt, streaming=True, enable_thinking=True):
"""
Run inference on given prompt with specified Claude model,
printing thinking and response as they arrive.
"""
kwargs = dict(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{"role": "user", "content": prompt}],
)

if enable_thinking:
kwargs["thinking"] = {"type": "adaptive"}

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.type
if 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.delta
if 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.text
elif event.type == "content_block_stop":
print() # Finish this block
else:
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 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,
streaming=streaming,
enable_thinking=enable_thinking
)

print("\n\n=== FINAL RETURNED RESPONSE ===\n", final_answer)
Toggle streaming and enable_thinking at the top of the script to see reasoning and/or stream content as it becomes available.
After running our script, we will see a link to visualize our model's output in Weave!


After clicking the link, we can view the inputs and outputs for our model:



What's new in Opus 4.7: xhigh Effort, Literal Instructions, and more

Before we look at vision and tool use, you need to be aware of how Claude Opus 4.7 introduces several behavioral shifts that will impact how you engineer your prompts and workflows:

1. Literal instruction following

Opus 4.7 is substantially better at following instructions, which means it takes them literally. Where previous models interpreted instructions loosely or "filled in the blanks" for you, Opus 4.7 executes exactly what you wrote. If your prompts relied on Claude making assumptions, you will need to re-tune them.

2. The new xhigh effort level

To control how deeply Claude thinks before speaking, you use the effort parameter. Opus 4.7 introduces a brand new xhigh tier:
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
thinking={"type": "adaptive"},
output_config={"effort": "xhigh"},
messages=[{"role": "user", "content": prompt}],
)
  • low: Fast, token-efficient responses.
  • medium: Balanced approach.
  • high: High capability for complex analysis.
  • xhigh: (NEW) Extra high capability. This gives finer control between high and max, and is the new default for coding agents like Claude Code.
  • max: Absolute highest capability, but uses substantially more tokens.

3. Adaptive thinking replaces budget_tokens

If you are migrating from early Claude 4 models, the old {"type": "enabled", "budget_tokens": 1024} syntax is deprecated. The new standard is {"type": "adaptive"}.

Other key changes in Opus 4.7

  • New tokenizer: Opus 4.7 uses a new tokenizer that improves downstream task performance. The tradeoff is that the same text input can map to roughly 1x to 1.35x the tokens it would have on 4.6.
  • Improved capabilities: Better knowledge work (document editing, slide layouts), improved memory for file-system-based agents, and more literal instruction following.

Step 3: Using Opus 4.7's high-resolution vision

Now that we understand how Opus 4.7 thinks, let's look at how it sees.
One of the standout upgrades in Opus 4.7 is its support for high-resolution images (up to 2576px on the long edge, or ~3.75 Megapixels). Older models downscaled large images, but 4.7 can read dense UI screenshots, intricate circuit diagrams, and tiny text with pixel-perfect accuracy.
Since we already set up our global clients, passing a high-resolution image to Opus 4.7 alongside text is very straightforward:
def encode_image_to_base64(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read()).decode("utf-8")

@weave.op
def analyze_high_res_image(image_path, prompt):
base64_image = encode_image_to_base64(image_path)
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=4000,
messages=[
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": base64_image,
},
},
{
"type": "text",
"text": prompt
}
],
}
],
)
return response.content[0].text
Next, let's interactively test this out! Run the cell below. It will prompt you to type in the path of a local image and ask a question about it:
# 1. Interactively ask for the image path
my_image_path = input("Please enter the file path to your image (e.g., screenshot.jpg): ")

# 2. Verify the file actually exists
if os.path.exists(my_image_path):
my_prompt = input("What would you like to ask Claude about this image? ")
print("\n[Sending image to Claude Opus 4.7... please wait]")
# --- THIS IS THE FIX: Load the image using PIL ---
pil_img = Image.open(my_image_path)
# 3. Execute the Weave-tracked function with the PIL object instead of the string
vision_result = analyze_high_res_image(pil_img, my_prompt)
# 4. Print the result
print("\n=== VISION RESPONSE ===\n", vision_result)
else:
print(f"\n❌ Error: Could not find an image at '{my_image_path}'. Please check the path and try again.")
In Weave you'll have logged the image, prompt as well as the output:



Using Claude Opus 4.7 with tool use

Finally, one of the most exciting features is tool use: Claude's ability to call custom functions, such as a calculator or a database, during its reasoning process.
To illustrate, consider a business analytics scenario. Suppose you want to know, "What's the total revenue if we sold 150 units at $50 each? Also, how does that compare to our average monthly revenue?" When you use tool use with Claude Opus 4.7, you can let the model both perform the multiplication and look up your real or sample revenue data—all in one turn.
When you enable adaptive thinking, Interleaved Thinking is activated automatically. Claude will pause between tool calls to share its intermediate analysis, reflect on the latest results, and make an informed decision about what to do next.
Here is our complete, end-to-end tool use loop:
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)) + 1
val = 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."
)

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

@weave.op()
def claude_message_op(msg_history):
"""
Runs a single Anthropic API call (one assistant step).
Adaptive thinking automatically enables interleaved thinking.
"""
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
tools=[calculator_tool, database_tool],
thinking={"type": "adaptive"},
output_config={"effort": "xhigh"},
messages=msg_history,
)
return response.content

@weave.op()
def run_claude_tools_full_chain(prompt_text=PROMPT, max_loops=5):
"""
Main loop: calls Claude; if tool call, executes it and calls Claude again.
Each step is tracked in Weave for graph lineage.
"""
all_steps = []
msg_history = [{"role": "user", "content": prompt_text}]

for loop in range(max_loops):
assistant_blocks = claude_message_op(msg_history)
all_steps.append({
"assistant_blocks": assistant_blocks,
"msg_history": list(msg_history)
})

tool_results = execute_tools(assistant_blocks)
if not tool_results:
break

msg_history.append({"role": "assistant", "content": assistant_blocks})
msg_history.append({"role": "user", "content": tool_results})
all_steps[-1]["tool_results"] = tool_results

return all_steps

def 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} "
f"(id={block.id}) {'-'*40}")
elif block.type == "text":
print(f"[RESPONSE BLOCK]:\n{block.text}\n{'-'*60}")

# === RUN THE CHAIN ===
steps = run_claude_tools_full_chain(
prompt_text=PROMPT,
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']}")

final_blocks = steps[-1]["assistant_blocks"]
print("\n--- Final Assistant Response ---\n")
print_blocks(final_blocks)
Inside Weave, you can now visualize both the high-level call to run_claude_tools_full_chain, as well as every individual reasoning, tool call, and textual response block generated by Claude. This gives you a complete semantic trace and lets you debug, compare, and audit conversations at every step.

Inside Weave, you can visualize both the high-level call to run_claude_tools_full_chain, including prompt, tool usage, and assistant decisions, as well as every individual reasoning ("thinking"), tool call, and textual response block generated by Claude. This gives you a complete semantic trace and lets you debug, compare, and audit conversations at every step.

Conclusion

In just a few steps, you've set up Claude Opus 4.7 with the Anthropic Python SDK and integrated it with W&B Weave for full visibility into every aspect of your model's reasoning, vision, and tool use.
The key upgrades in this version—literal instruction following, the new xhigh effort parameter, 3.75MP high-res vision, and robust autonomous coding capabilities—make Claude Opus 4.7 an incredible engine for your applications. This workflow lets you trace every interaction and intermediate step, making it easy to optimize exactly how Claude arrives at its answers.