Claude Cookbook

Extended thinking with tool use

Combine extended thinking with tools for transparent reasoning during multi-step workflows.

Alex Albert
Alex Albert
@alexalbertt
Published on February 24, 2025
Was this page helpful?

Extended Thinking with Tool Use

Table of contents

This notebook demonstrates how to use Claude's extended thinking feature with tools on Claude Sonnet 5.5. The extended thinking feature allows you to see Claude's step-by-step thinking before it provides a final answer, providing transparency into how it decides which tools to use and how it interprets tool results.

On Claude Sonnet 5.5 thinking is adaptive (thinking={"type": "adaptive"}, with output_config={"effort": ...} controlling how hard it thinks), and the model may think before its first tool request and again between tool calls after it reads tool results (interleaved thinking). No beta header is needed for this. Thinking blocks carry a signature and are bound to the conversation so far, so earlier assistant content, including thinking and redacted_thinking blocks, must be passed back unchanged on each follow-up request. For more information on extended thinking, see our documentation.

Setup

First, let's install the necessary packages and set up our environment.

%pip install anthropic
import json
import anthropic
# Global variables for model, output limit, and thinking effort
MODEL_NAME = "claude-sonnet-5-5"
MAX_TOKENS = 16000 # thinking tokens count toward max_tokens, so leave headroom
EFFORT = "xhigh" # how hard Claude thinks: low | medium | high (default) | xhigh | max.
# Adaptive thinking may skip thinking entirely on easy requests at lower effort; "xhigh"
# makes these small examples reliably produce thinking blocks you can inspect.
# Every request below passes thinking={"type": "adaptive", "display": "summarized"}.
# "display" defaults to "omitted" on this model, which returns thinking blocks with
# empty text; "summarized" returns a summary of the reasoning so we can print it.
# Set your API key as an environment variable or directly
# os.environ["ANTHROPIC_API_KEY"] = "your_api_key_here"
# Initialize the client
client = anthropic.Anthropic()
# Helper functions
def print_thinking_response(response):
"""Pretty print a message response with thinking blocks."""
print("\n==== FULL RESPONSE ====")
for block in response.content:
if block.type == "thinking":
print("\n🧠 THINKING BLOCK:")
# Show truncated thinking for readability
print(block.thinking[:500] + "..." if len(block.thinking) > 500 else block.thinking)
print(f"\n[Signature available: {bool(getattr(block, 'signature', None))}]")
if hasattr(block, "signature") and block.signature:
print(f"[Signature (first 50 chars): {block.signature[:50]}...]")
elif block.type == "redacted_thinking":
print("\n🔒 REDACTED THINKING BLOCK:")
print(f"[Data length: {len(block.data) if hasattr(block, 'data') else 'N/A'}]")
elif block.type == "text":
print("\n✓ FINAL ANSWER:")
print(block.text)
print("\n==== END RESPONSE ====")
def count_tokens(messages, tools=None):
"""Count tokens for a given message list with optional tools."""
if tools:
response = client.messages.count_tokens(model=MODEL_NAME, messages=messages, tools=tools)
else:
response = client.messages.count_tokens(model=MODEL_NAME, messages=messages)
return response.input_tokens

Single tool calls with thinking

This example demonstrates how to combine thinking and make a single tool call, with a mock weather tool.

def tool_use_with_thinking():
# Define a weather tool
tools = [
{
"name": "weather",
"description": "Get current weather information for a location.",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to get weather for.",
}
},
"required": ["location"],
},
}
]
def weather(location):
# Mock weather data, keyed by bare city name (the model may pass "Paris, FR")
location = location.split(",")[0].strip()
weather_data = {
"New York": {"temperature": 72, "condition": "Sunny"},
"London": {"temperature": 62, "condition": "Cloudy"},
"Tokyo": {"temperature": 80, "condition": "Partly cloudy"},
"Paris": {"temperature": 65, "condition": "Rainy"},
"Sydney": {"temperature": 85, "condition": "Clear"},
"Berlin": {"temperature": 60, "condition": "Foggy"},
}
return weather_data.get(location, {"error": f"No weather data available for {location}"})
# A bare "what's the weather in Paris?" usually goes straight to the tool call with no
# thinking. Giving Claude a small decision that depends on the result makes it reason first.
user_message = {
"role": "user",
"content": "I'm hosting an outdoor dinner in Paris this evening and deciding whether to move it indoors. Work out what you need to check, use the tool, then give me a recommendation with your reasoning.",
}
# Initial request with tool use and thinking
response = client.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": EFFORT},
tools=tools,
messages=[user_message],
)
# Detailed diagnostic output of initial response
print("\n=== INITIAL RESPONSE ===")
print(f"Response ID: {response.id}")
print(f"Stop reason: {response.stop_reason}")
print(f"Model: {response.model}")
print(f"Content blocks: {len(response.content)} blocks")
for i, block in enumerate(response.content):
print(f"\nBlock {i + 1}: Type = {block.type}")
if block.type == "thinking":
print(f"Thinking content: {block.thinking[:150]}...")
print(f"Signature available: {bool(getattr(block, 'signature', None))}")
elif block.type == "text":
print(f"Text content: {block.text}")
elif block.type == "tool_use":
print(f"Tool: {block.name}")
print(f"Tool input: {block.input}")
print(f"Tool ID: {block.id}")
print("=== END INITIAL RESPONSE ===\n")
# Handle tool use until Claude gives its final answer
full_conversation = [user_message]
while response.stop_reason == "tool_use":
# Keep the whole assistant turn (thinking, redacted_thinking, text and tool_use blocks,
# in order) for the conversation history. Thinking blocks are signed and bound to the
# conversation prefix, so pass the turn back exactly as received.
full_conversation.append({"role": "assistant", "content": response.content})
# Execute every tool_use block in this turn and answer each one
tool_results = []
for tool_use_block in (b for b in response.content if b.type == "tool_use"):
print("\n=== EXECUTING TOOL ===")
print(f"Tool name: {tool_use_block.name}")
print(f"Location to check: {tool_use_block.input['location']}")
tool_result = weather(tool_use_block.input["location"])
print(f"Result: {tool_result}")
print("=== TOOL EXECUTION COMPLETE ===\n")
tool_results.append(
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": json.dumps(tool_result),
}
)
# Add the tool results to the conversation in a single user turn
full_conversation.append({"role": "user", "content": tool_results})
# Continue the conversation with the same thinking configuration
print("\n=== SENDING FOLLOW-UP REQUEST WITH TOOL RESULT ===")
response = client.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": EFFORT},
tools=tools,
messages=full_conversation,
)
print(f"Follow-up response received. Stop reason: {response.stop_reason}")
print_thinking_response(response)
# Run the example
tool_use_with_thinking()
=== INITIAL RESPONSE ===
Response ID: msg_011Cfdj5KspNpopEXyAhbhct
Stop reason: tool_use
Model: claude-sonnet-5-5
Content blocks: 3 blocks

Block 1: Type = thinking
Thinking content: I need to check the weather in Paris, so I'll call the weather tool for that.

...
Signature available: True

Block 2: Type = text
Text content: I need to check Paris's current conditions and anything that affects this evening, such as rain, temperature, wind, and how the weather is trending. I'll pull the weather now.

Block 3: Type = tool_use
Tool: weather
Tool input: {'location': 'Paris, France'}
Tool ID: toolu_014FismJG9gGgQfUSw9WVjGs
=== END INITIAL RESPONSE ===


=== EXECUTING TOOL ===
Tool name: weather
Location to check: Paris, France
Result: {'temperature': 65, 'condition': 'Rainy'}
=== TOOL EXECUTION COMPLETE ===


=== SENDING FOLLOW-UP REQUEST WITH TOOL RESULT ===
Follow-up response received. Stop reason: end_turn

==== FULL RESPONSE ====

🧠 THINKING BLOCK:
The data I got back is pretty sparse—just 65°F and rainy, no forecast details or timing. I'll be upfront about those limits while still giving a practical recommendation, like suggesting a covered or indoor option as a safe bet given the current rain.



[Signature available: True]
[Signature (first 50 chars): CAQSzAgKEAgSGAI4AUIIdGhpbmtpbmcSDClkCAxutjspaB5bxx...]

✓ FINAL ANSWER:
**Recommendation: move the dinner indoors.** If you can't, only keep it outside if you have solid covered space.

**What the tool showed**
- The condition in Paris is **rainy**.
- The temperature is **65°F (about 18°C)**. The tool gave no unit, but only Fahrenheit makes sense for 65 in Paris.

**Why I'd move it**
- **Rain is the main problem.** It's raining now, and the tool gave no sign that it will stop by this evening. Wet seating, soggy food, and guests dashing for cover are hard to fix once dinner has started.
- **The temperature won't help.** 65°F is mild now, but it will probably drop after sunset. Rain with a cooler evening feels colder than the number suggests, especially for people sitting still for a couple of hours.
- **Moving late costs more.** Moving indoors now is easy. Moving mid-meal means carrying food, plates, and candles through the rain.

**What I couldn't check**
The tool only gave current conditions. I have no hourly forecast, rain chances, wind, or timing for this evening. If the rain is a passing shower and your dinner is several hours away, the evening could clear up. Look at a radar or hourly forecast, such as Météo-France, to see.

**If you want to stay outside**
Only do it if both of these are true:
1. You have real cover, like a covered terrace, a sturdy awning, or a tent with sides. An umbrella isn't enough.
2. You have an indoor backup you can switch to within about 15 minutes.

You could also decide at a set time, such as 2 hours before guests arrive. Go indoors if it's still raining then.

==== END RESPONSE ====

Multiple tool calls with thinking

This example demonstrates how to handle multiple tool calls, such as a mock news and weather service, while observing the thinking process.

def multiple_tool_calls_with_thinking():
# Define tools
tools = [
{
"name": "weather",
"description": "Get current weather information for a location.",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to get weather for.",
}
},
"required": ["location"],
},
},
{
"name": "news",
"description": "Get latest news headlines for a topic.",
"input_schema": {
"type": "object",
"properties": {
"topic": {"type": "string", "description": "The topic to get news about."}
},
"required": ["topic"],
},
},
]
def weather(location):
# Mock weather data, keyed by bare city name (the model may pass "Paris, FR")
location = location.split(",")[0].strip()
weather_data = {
"New York": {"temperature": 72, "condition": "Sunny"},
"London": {"temperature": 62, "condition": "Cloudy"},
"Tokyo": {"temperature": 80, "condition": "Partly cloudy"},
"Paris": {"temperature": 65, "condition": "Rainy"},
"Sydney": {"temperature": 85, "condition": "Clear"},
"Berlin": {"temperature": 60, "condition": "Foggy"},
}
return weather_data.get(location, {"error": f"No weather data available for {location}"})
def news(topic):
# Mock news data
news_data = {
"technology": [
"New AI breakthrough announced by research lab",
"Tech company releases latest smartphone model",
"Quantum computing reaches milestone achievement",
],
"sports": [
"Local team wins championship game",
"Star player signs record-breaking contract",
"Olympic committee announces host city for 2036",
],
"weather": [
"Storm system developing in the Atlantic",
"Record temperatures recorded across Europe",
"Climate scientists release new research findings",
],
}
# Loose matching so "London tech" or "technology news" resolve to a category
topic = topic.lower()
for key, headlines in news_data.items():
if key in topic or (key == "technology" and "tech" in topic):
return {"headlines": headlines}
return {"headlines": ["No news available for this topic"]}
# Initial request
response = client.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": EFFORT},
tools=tools,
messages=[
{
"role": "user",
"content": "I run an outdoor tech meetup in London tomorrow evening and I'm deciding whether to move it indoors and what to open the talk with. Work out which of your tools you need and in what order, use them, then give me a recommendation with your reasoning.",
}
],
)
# Print detailed information about initial response
print("\n=== INITIAL RESPONSE ===")
print(f"Response ID: {response.id}")
print(f"Stop reason: {response.stop_reason}")
print(f"Model: {response.model}")
print(f"Content blocks: {len(response.content)} blocks")
# Print each content block
for i, block in enumerate(response.content):
print(f"\nBlock {i + 1}: Type = {block.type}")
if block.type == "thinking":
print(f"Thinking content: {block.thinking[:150]}...")
print(f"Signature available: {bool(getattr(block, 'signature', None))}")
elif block.type == "text":
print(f"Text content: {block.text}")
elif block.type == "tool_use":
print(f"Tool: {block.name}")
print(f"Tool input: {block.input}")
print(f"Tool ID: {block.id}")
print("=== END INITIAL RESPONSE ===\n")
# Handle potentially multiple tool calls
full_conversation = [
{
"role": "user",
"content": "I run an outdoor tech meetup in London tomorrow evening and I'm deciding whether to move it indoors and what to open the talk with. Work out which of your tools you need and in what order, use them, then give me a recommendation with your reasoning.",
}
]
# Track iteration count for multi-turn tool use
iteration = 0
while response.stop_reason == "tool_use":
iteration += 1
print(f"\n=== TOOL USE ITERATION {iteration} ===")
# Keep the whole assistant turn (thinking, text and tool_use blocks, in order)
# for the conversation history; pass it back exactly as received
assistant_blocks = response.content
# Add assistant response with thinking blocks and tool use
full_conversation.append({"role": "assistant", "content": assistant_blocks})
# Run every tool_use block in this turn (Claude may call several tools in parallel)
tool_use_blocks = [block for block in response.content if block.type == "tool_use"]
if tool_use_blocks:
tool_results = []
for tool_use_block in tool_use_blocks:
print("\n=== EXECUTING TOOL ===")
print(f"Tool name: {tool_use_block.name}")
# Execute the appropriate tool
if tool_use_block.name == "weather":
print(f"Location to check: {tool_use_block.input['location']}")
tool_result = weather(tool_use_block.input["location"])
elif tool_use_block.name == "news":
print(f"Topic to check: {tool_use_block.input['topic']}")
tool_result = news(tool_use_block.input["topic"])
else:
tool_result = {"error": "Unknown tool"}
print(f"Result: {tool_result}")
print("=== TOOL EXECUTION COMPLETE ===\n")
tool_results.append(
{
"type": "tool_result",
"tool_use_id": tool_use_block.id,
"content": json.dumps(tool_result),
}
)
# Add all tool results to the conversation in a single user turn
full_conversation.append({"role": "user", "content": tool_results})
# Continue the conversation
print("\n=== SENDING FOLLOW-UP REQUEST WITH TOOL RESULT ===")
response = client.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": EFFORT},
tools=tools,
messages=full_conversation,
)
# Print follow-up response details
print(f"\n=== FOLLOW-UP RESPONSE (ITERATION {iteration}) ===")
print(f"Response ID: {response.id}")
print(f"Stop reason: {response.stop_reason}")
print(f"Content blocks: {len(response.content)} blocks")
for i, block in enumerate(response.content):
print(f"\nBlock {i + 1}: Type = {block.type}")
if block.type == "thinking":
print(f"Thinking content preview: {block.thinking[:100]}...")
elif block.type == "text":
print(f"Text content preview: {block.text[:100]}...")
elif block.type == "tool_use":
print(f"Tool: {block.name}")
print(f"Tool input preview: {str(block.input)[:100]}")
print(f"=== END FOLLOW-UP RESPONSE (ITERATION {iteration}) ===\n")
if response.stop_reason != "tool_use":
print("\n=== FINAL RESPONSE ===")
print_thinking_response(response)
print("=== END FINAL RESPONSE ===")
else:
print("No tool_use block found in response.")
break
# Run the example
multiple_tool_calls_with_thinking()
=== INITIAL RESPONSE ===
Response ID: msg_011Cfdj62iENiRCj8mRZbo5x
Stop reason: tool_use
Model: claude-sonnet-5-5
Content blocks: 4 blocks

Block 1: Type = thinking
Thinking content: London weather and outdoor tech news are unrelated requests, so I can fetch both at once.

...
Signature available: True

Block 2: Type = text
Text content: I'll check two things: the London weather, which decides indoors or outdoors, and current outdoor tech news, which could give you an opening for the talk. Neither depends on the other, so I'll run both now.

Block 3: Type = tool_use
Tool: weather
Tool input: {'location': 'London'}
Tool ID: toolu_016w2JwNyoLzMzEVbLpH62xJ

Block 4: Type = tool_use
Tool: news
Tool input: {'topic': 'outdoor tech'}
Tool ID: toolu_01VbrLTn6hoqbSCzFdsJSTYm
=== END INITIAL RESPONSE ===


=== TOOL USE ITERATION 1 ===

=== EXECUTING TOOL ===
Tool name: weather
Location to check: London
Result: {'temperature': 62, 'condition': 'Cloudy'}
=== TOOL EXECUTION COMPLETE ===


=== EXECUTING TOOL ===
Tool name: news
Topic to check: outdoor tech
Result: {'headlines': ['New AI breakthrough announced by research lab', 'Tech company releases latest smartphone model', 'Quantum computing reaches milestone achievement']}
=== TOOL EXECUTION COMPLETE ===


=== SENDING FOLLOW-UP REQUEST WITH TOOL RESULT ===

=== FOLLOW-UP RESPONSE (ITERATION 1) ===
Response ID: msg_011Cfdj6FH2q2v5mcsXVFXim
Stop reason: end_turn
Content blocks: 2 blocks

Block 1: Type = thinking
Thinking content preview: This weather data I have is current conditions, 62°F and cloudy, not actually a forecast for tomorro...

Block 2: Type = text
Text content preview: ## What the tools returned
- **Weather (London):** 62°F (about 17°C) and cloudy.
- **News ("outdoor ...
=== END FOLLOW-UP RESPONSE (ITERATION 1) ===


=== FINAL RESPONSE ===

==== FULL RESPONSE ====

🧠 THINKING BLOCK:
This weather data I have is current conditions, 62°F and cloudy, not actually a forecast for tomorrow evening, so I should be upfront about that limitation rather than pretend it's predictive. I'll give my recommendation but flag that the info is approximate.



[Signature available: True]
[Signature (first 50 chars): CAQSpgcKEAgSGAI4AUIIdGhpbmtpbmcSDGBMkNBxX+VByEIp0x...]

✓ FINAL ANSWER:
## What the tools returned
- **Weather (London):** 62°F (about 17°C) and cloudy.
- **News ("outdoor tech"):** The headlines were about a new AI breakthrough, a new smartphone release, and a quantum computing milestone. None of them is specific to outdoor tech.

## Limits of this data
- **The weather is a current reading, not a forecast for tomorrow evening.** It doesn't show rain chances, wind, or how much the temperature drops after sunset. That matters because London evenings are usually several degrees cooler than the daytime reading.
- **The news results are general tech headlines.** They don't connect to an outdoor theme.

## Recommendation on moving indoors
**Keep it outdoors, but only if you have a cover or a fallback, and check an hourly forecast tomorrow morning.**
- 62°F and cloudy is comfortable. Cloud also helps if people are looking at laptops or phone screens, because there's no glare.
- The evening will be cooler, so tell attendees to bring a layer.
- I can't see rain risk. Check the Met Office or BBC Weather hourly forecast tomorrow morning. If rain is likely during your event window, or if you have no cover for equipment, move indoors or have a booked backup space.
- Because it's a tech meetup, think about power, Wi-Fi, and keeping the AV kit dry. Those are good reasons to go indoors even in marginal weather.

## Recommendation on the opening
Of the three headlines, **quantum computing reaching a milestone** or **the new AI breakthrough** would grab attention most easily. I only have the headlines, with no details, so I'd check the full stories before citing specifics.

Here are two ways to tie it to an outdoor setting:
1. **Use the weather itself as the hook.** For example: "We're sitting under a cloudy London sky, and forecasting this exact sky is one of the hardest computing problems around." You can then lead into AI or quantum computing as the tools that might improve weather prediction. That fits the venue and the headlines.
2. **Open with a question to the audience.** For example: "What's one piece of tech you'd trust to work outdoors in British weather?" It gets people talking and suits an outdoor crowd, and it doesn't depend on weak news material.

I'd go with option 1 if you're outside, because it uses the setting. If you move indoors, option 2 works just as well.

==== END RESPONSE ====
=== END FINAL RESPONSE ===

Preserving thinking blocks

When working with extended thinking and tools, make sure to:

  1. Pass thinking blocks back unchanged, with their signatures. Each thinking block carries a cryptographic signature over the full (unsummarized) reasoning. When you send tool results, include the previous assistant turn exactly as you received it: thinking / redacted_thinking / text / tool_use blocks, in order. A block whose signature doesn't verify is rejected with a 400.

  2. Don't edit earlier turns. On Claude Sonnet 5.5 a thinking block is also bound to the conversation prefix that produced it (the system prompt, the tools array, and every earlier message). If you replay a thinking block after changing any of that, the block no longer matches its conversation. Accounts created on or after August 31, 2026 get a 400 for this by default; older accounts can opt in with the thinking-binding-controls-2026-08-01 beta header and thinking.block_binding.prefix_mismatch_behavior set to "error" (reject the request) or "drop_block" (drop the stale block and report it in input_transformations). The example below uses the beta header so the behavior is the same on any account.

  3. Don't silently drop them either. Leaving the thinking blocks out of the replayed turn is accepted by the API, but Claude then continues the task without the reasoning it did before the tool call. Keep them.

  4. Handle both thinking and redacted_thinking blocks. Both must be preserved in the conversation history, even though the content of redacted blocks is not human readable.

For more details on extended thinking without tools, see the main "Extended Thinking" notebook.

def thinking_block_preservation_example():
# Define a simple weather tool
tools = [
{
"name": "weather",
"description": "Get current weather information for a location.",
"input_schema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to get weather for.",
}
},
"required": ["location"],
},
}
]
def weather(location):
# Mock weather data, keyed by bare city name (the model may pass "Paris, FR")
location = location.split(",")[0].strip()
weather_data = {
"New York": {"temperature": 72, "condition": "Sunny"},
"London": {"temperature": 62, "condition": "Cloudy"},
"Tokyo": {"temperature": 80, "condition": "Partly cloudy"},
"Paris": {"temperature": 65, "condition": "Rainy"},
"Sydney": {"temperature": 85, "condition": "Clear"},
"Berlin": {"temperature": 60, "condition": "Foggy"},
}
return weather_data.get(location, {"error": f"No weather data available for {location}"})
question = "I'm about to cycle across Berlin to a meeting I can't be late for. Work out what you need to check, use the tool, then tell me whether to leave extra time and why."
# Opt in to strict prefix binding so this demo behaves the same on every account
# (accounts created on or after 2026-08-31 get this behavior by default).
betas = ["thinking-binding-controls-2026-08-01"]
strict_thinking = {
"type": "adaptive",
"display": "summarized",
"block_binding": {"prefix_mismatch_behavior": "error"},
}
# Initial request with tool use and thinking. Adaptive thinking occasionally skips
# thinking even here, so retry a couple of times until we have a thinking block to work with.
for _ in range(3):
response = client.beta.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking=strict_thinking,
output_config={"effort": EFFORT},
tools=tools,
betas=betas,
messages=[{"role": "user", "content": question}],
)
thinking_blocks = [b for b in response.content if b.type == "thinking"]
tool_use_blocks = [b for b in response.content if b.type == "tool_use"]
if thinking_blocks and tool_use_blocks:
break
print("\n=== INITIAL RESPONSE ===")
print("Response contains:")
print(f"- {len(thinking_blocks)} thinking blocks")
print(f"- {len(tool_use_blocks)} tool use blocks")
if not (thinking_blocks and tool_use_blocks):
print("\nClaude answered without a thinking block or without calling the tool this time;")
print("re-run the cell to see the preservation checks below.")
return
tool_block = tool_use_blocks[0]
print(f"\nTool called: {tool_block.name}")
print(f"Location to check: {tool_block.input['location']}")
# Execute the tool
tool_result = weather(tool_block.input["location"])
print(f"Tool result: {tool_result}")
tool_result_turn = {
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_block.id,
"content": json.dumps(tool_result),
}
],
}
def follow_up(label, messages, thinking=strict_thinking):
try:
result = client.beta.messages.create(
model=MODEL_NAME,
max_tokens=MAX_TOKENS,
thinking=thinking,
output_config={"effort": EFFORT},
tools=tools,
betas=betas,
messages=messages,
)
print(f"SUCCESS ({label}): stop_reason={result.stop_reason}")
return result
except anthropic.BadRequestError as e:
print(f"ERROR ({label}): {e}")
return None
# TEST 1: tamper with the thinking block's signature -> rejected
print("\n=== TEST 1: modified signature ===")
tampered_turn = []
for block in response.content:
block_dict = block.model_dump()
if block_dict["type"] == "thinking":
block_dict["signature"] = block_dict["signature"][:-4] + "AAAA"
tampered_turn.append(block_dict)
follow_up(
"tampered signature",
[
{"role": "user", "content": question},
{"role": "assistant", "content": tampered_turn},
tool_result_turn,
],
)
print("Thinking blocks must be passed back byte-for-byte, signature included.")
# TEST 2: replay the thinking block unchanged but edit the earlier user message.
# The block is bound to the original prefix, so with prefix_mismatch_behavior="error"
# the request is rejected...
print("\n=== TEST 2: edited earlier turn, prefix_mismatch_behavior='error' ===")
edited_history = [
{"role": "user", "content": question + " Thanks!"}, # <- not what Claude saw
{"role": "assistant", "content": response.content},
tool_result_turn,
]
follow_up("edited prefix", edited_history)
# ...and with "drop_block" the API drops the stale thinking block, tells you it did so
# in input_transformations, and Claude continues without that reasoning.
print("\n=== TEST 3: edited earlier turn, prefix_mismatch_behavior='drop_block' ===")
lenient = {**strict_thinking, "block_binding": {"prefix_mismatch_behavior": "drop_block"}}
dropped = follow_up("edited prefix, drop_block", edited_history, thinking=lenient)
if dropped is not None:
print(f"input_transformations: {dropped.to_dict().get('input_transformations')}")
# TEST 4: the correct approach - every block from the first response, in order, unchanged,
# on top of an unchanged prefix.
print("\n=== TEST 4: WITH thinking block, unchanged history (correct approach) ===")
complete_response = follow_up(
"full replay",
[
{"role": "user", "content": question},
{"role": "assistant", "content": response.content},
tool_result_turn,
],
)
if complete_response is not None:
second_thinking = [b for b in complete_response.content if b.type == "thinking"]
second_text = [b for b in complete_response.content if b.type == "text"]
print("\nSecond response contains:")
print(f"- {len(second_thinking)} thinking blocks")
print(f"- {len(second_text)} text blocks")
if second_text:
print(f"\nFinal answer: {second_text[0].text}")
print(
"\nNote: with adaptive thinking Claude may or may not think again after a tool result,"
)
print(
"so the second response can contain thinking blocks. Either way, pass every earlier block back unchanged."
)
# Run the example
thinking_block_preservation_example()
=== INITIAL RESPONSE ===
Response contains:
- 1 thinking blocks
- 1 tool use blocks

Tool called: weather
Location to check: Berlin
Tool result: {'temperature': 60, 'condition': 'Foggy'}

=== TEST 1: modified signature ===
ERROR (tampered signature): Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages.1.content.0: Invalid `signature` in `thinking` block'}, 'request_id': 'req_011Cfdj789gkiDGRiGuVqr8n'}
Thinking blocks must be passed back byte-for-byte, signature included.

=== TEST 2: edited earlier turn, prefix_mismatch_behavior='error' ===
ERROR (edited prefix): Error code: 400 - {'type': 'error', 'error': {'type': 'invalid_request_error', 'message': 'messages.1.content.0: Invalid `signature` in `thinking` block. The block is bound to a different conversation. Remove the block, or set `thinking.block_binding.prefix_mismatch_behavior` to "drop_block". Content before this block differs from when it was created, first at `messages.0.content.0`.'}, 'request_id': 'req_011Cfdj78tLJjd4YRHAKCFck'}

=== TEST 3: edited earlier turn, prefix_mismatch_behavior='drop_block' ===
SUCCESS (edited prefix, drop_block): stop_reason=end_turn
input_transformations: [{'type': 'thinking_dropped', 'path': 'messages.1.content.0', 'reason': 'prefix_binding_mismatch'}]

=== TEST 4: WITH thinking block, unchanged history (correct approach) ===
SUCCESS (full replay): stop_reason=end_turn

Second response contains:
- 1 thinking blocks
- 1 text blocks

Final answer: **Yes, leave extra time. I'd add about 10–15 minutes, or more if your route is long or goes through busy areas.**

The tool reports Berlin as **foggy at 60 degrees**. It gave no unit, but 60 is only a plausible temperature in °F, which is about 16°C. That's mild, so cold isn't the problem.

**Why the fog matters**
- **Visibility:** You'll see junctions, tram tracks, turning vehicles and pedestrians later, and drivers will see you later too. You'll probably ride more slowly and cautiously, especially on shared roads and at crossings.
- **Damp surfaces:** Fog often leaves roads, cobbles, tram rails and painted road markings slick. Berlin has plenty of all of these, so braking and cornering need more care.
- **Delays at junctions:** Slower traffic and more cautious road users tend to add stops and waiting time across a whole cross-city ride.

**What I couldn't check**
- The report had no wind, rain or forecast data, so I can't say whether conditions will improve or get worse during your ride.
- I only have a city-wide reading. Fog can be thicker near the Spree, parks or open areas like Tempelhofer Feld.

**Before you go**
- Switch on front and rear lights, even if it's daytime.
- Wear something light-coloured or reflective.
- Brake earlier than usual, and take extra care on tram tracks and cobbles.
- Check the BVG or S-Bahn status now. If the ride looks too tight, you'll know your fallback.

If the meeting is critical, aim to arrive 10 minutes early. That leaves room for a slow ride or a wrong turn.

Note: with adaptive thinking Claude may or may not think again after a tool result,
so the second response can contain thinking blocks. Either way, pass every earlier block back unchanged.

Conclusion

This notebook shows how to combine Claude's extended thinking feature with tool use. Key benefits include:

  1. Transparency into Claude's thinking process when using tools
  2. Visibility into how Claude decides when to use tools versus internal knowledge
  3. Better understanding of multi-step tasks that involve multiple tool calls
  4. Insight into how Claude interprets tool results and incorporates them into responses

When using extended thinking with tools, keep in mind:

  • Pick an effort level that fits the task ("high" is the default; "low" and "medium" trade depth for speed and cost, "xhigh" and "max" are for the hardest problems). There is no token budget on current models
  • Set "display": "summarized" if you want to read the thinking; the default ("omitted") returns empty thinking text
  • Always preserve thinking blocks and their signatures when passing tool results
  • Include both normal and redacted thinking blocks in the conversation history
  • Ensure that system prompts, tools, and thinking configurations match between calls
  • Claude may think again between tool calls (interleaved thinking), so handle thinking blocks in any assistant turn and pass them all back unchanged
  • Tool use and thinking together can increase token usage and response time
Was this page helpful?