Skip to content

Commit 5c3e633

Browse files
feat(api): adds support for Claude Opus 4.5, Effort, Advance Tool Use Features, Autocompaction, and Computer Use v5
1 parent c47c5bd commit 5c3e633

File tree

70 files changed

+1402
-120
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+1402
-120
lines changed

.stats.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
configured_endpoints: 34
2-
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-2f35b2ff9174d526a6d35796d2703490bfa5692312af67cbdfa4500283dabe31.yml
3-
openapi_spec_hash: dc52b25c487e97d355ef645644aa13e7
4-
config_hash: d23c4d678fcf7ff829a2891b3196edb6
2+
openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/anthropic%2Fanthropic-a49e89deec4e00d1da490808099d66e2001531b12d8666a7f5d0b496f760440d.yml
3+
openapi_spec_hash: c93ef3808c58e233b01966ff154f31ce
4+
config_hash: 7e9dfe17ab5c80abee5372ce746a926e

api.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -256,6 +256,7 @@ from anthropic.types.beta import (
256256
BetaContextManagementConfig,
257257
BetaContextManagementResponse,
258258
BetaCountTokensContextManagementResponse,
259+
BetaDirectCaller,
259260
BetaDocumentBlock,
260261
BetaFileDocumentSource,
261262
BetaFileImageSource,
@@ -264,9 +265,12 @@ from anthropic.types.beta import (
264265
BetaInputTokensClearAtLeast,
265266
BetaInputTokensTrigger,
266267
BetaJSONOutputFormat,
268+
BetaMCPToolConfig,
269+
BetaMCPToolDefaultConfig,
267270
BetaMCPToolResultBlock,
268271
BetaMCPToolUseBlock,
269272
BetaMCPToolUseBlockParam,
273+
BetaMCPToolset,
270274
BetaMemoryTool20250818,
271275
BetaMemoryTool20250818Command,
272276
BetaMemoryTool20250818CreateCommand,
@@ -280,6 +284,7 @@ from anthropic.types.beta import (
280284
BetaMessageParam,
281285
BetaMessageTokensCount,
282286
BetaMetadata,
287+
BetaOutputConfig,
283288
BetaPlainTextSource,
284289
BetaRawContentBlockDelta,
285290
BetaRawContentBlockDeltaEvent,
@@ -296,6 +301,7 @@ from anthropic.types.beta import (
296301
BetaRequestMCPServerURLDefinition,
297302
BetaRequestMCPToolResultBlockParam,
298303
BetaSearchResultBlockParam,
304+
BetaServerToolCaller,
299305
BetaServerToolUsage,
300306
BetaServerToolUseBlock,
301307
BetaServerToolUseBlockParam,
@@ -335,7 +341,18 @@ from anthropic.types.beta import (
335341
BetaToolChoiceTool,
336342
BetaToolComputerUse20241022,
337343
BetaToolComputerUse20250124,
344+
BetaToolComputerUse20251124,
345+
BetaToolReferenceBlock,
346+
BetaToolReferenceBlockParam,
338347
BetaToolResultBlockParam,
348+
BetaToolSearchToolBm25_20251119,
349+
BetaToolSearchToolRegex20251119,
350+
BetaToolSearchToolResultBlock,
351+
BetaToolSearchToolResultBlockParam,
352+
BetaToolSearchToolResultError,
353+
BetaToolSearchToolResultErrorParam,
354+
BetaToolSearchToolSearchResultBlock,
355+
BetaToolSearchToolSearchResultBlockParam,
339356
BetaToolTextEditor20241022,
340357
BetaToolTextEditor20250124,
341358
BetaToolTextEditor20250429,

examples/auto_compaction.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
"""Show the full summary content after compaction"""
2+
3+
import json
4+
5+
from anthropic import Anthropic
6+
from anthropic.lib.tools import beta_tool
7+
8+
9+
@beta_tool
10+
def search(query: str) -> str:
11+
"""Search for information."""
12+
return json.dumps(
13+
{
14+
"results": [
15+
{"title": f"Result for {query}", "content": "Lorem ipsum " * 100},
16+
{"title": f"More on {query}", "content": "Detailed info " * 100},
17+
]
18+
}
19+
)
20+
21+
22+
@beta_tool
23+
def done(summary: str) -> str: # noqa: ARG001
24+
"""Call when finished."""
25+
return "Complete"
26+
27+
28+
client = Anthropic()
29+
30+
runner = client.beta.messages.tool_runner(
31+
model="claude-sonnet-4-20250514",
32+
max_tokens=4096,
33+
tools=[search, done],
34+
messages=[
35+
{
36+
"role": "user",
37+
"content": "You MUST search for EACH of these animals ONE BY ONE: dogs, cats, birds, fish, horses, elephants, lions, tigers, bears, wolves. After searching for ALL of them, call done.",
38+
}
39+
],
40+
compaction_control={
41+
"enabled": True,
42+
"context_token_threshold": 3000, # Even lower threshold
43+
},
44+
)
45+
46+
prev_msg_count = 0
47+
for i, message in enumerate(runner):
48+
curr_msg_count = len(list(runner._params["messages"]))
49+
print(f"Turn {i + 1}: {message.usage.input_tokens} input tokens, {curr_msg_count} messages")
50+
51+
if curr_msg_count < prev_msg_count:
52+
print("=" * 70)
53+
print("🔄 COMPACTION OCCURRED!")
54+
print("=" * 70)
55+
print(f"Messages went from {prev_msg_count}{curr_msg_count}")
56+
print(f"Input tokens: {message.usage.input_tokens}")
57+
print("\nNEW MESSAGES LIST:")
58+
print("-" * 70)
59+
60+
for msg in runner._params["messages"]:
61+
role = msg.get("role", "?")
62+
content = msg.get("content", "")
63+
64+
if isinstance(content, list):
65+
for block in content:
66+
if isinstance(block, dict) and block.get("type") == "text":
67+
print(f"\n[{role}] TEXT BLOCK:")
68+
print(block.get("text", ""))
69+
elif isinstance(content, str):
70+
print(f"\n[{role}]:")
71+
print(content)
72+
73+
print("-" * 70)
74+
75+
prev_msg_count = curr_msg_count
76+
77+
print("\n✅ Done!")
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import json
2+
from typing import Any, List
3+
from typing_extensions import Literal
4+
5+
import rich
6+
7+
from anthropic import Anthropic, beta_tool
8+
from anthropic.lib.tools import BetaFunctionTool, BetaFunctionToolResultType
9+
from anthropic.types.beta import BetaToolReferenceBlockParam
10+
11+
client = Anthropic()
12+
13+
14+
@beta_tool(defer_loading=True)
15+
def get_weather(location: str, units: Literal["c", "f"]) -> str:
16+
"""Lookup the weather for a given city in either celsius or fahrenheit
17+
18+
Args:
19+
location: The city and state, e.g. San Francisco, CA
20+
units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
21+
Returns:
22+
A dictionary containing the location, temperature, and weather condition.
23+
"""
24+
# Simulate a weather API call
25+
print(f"Fetching weather for {location} in {units}")
26+
27+
# Here you would typically make an API call to a weather service
28+
# For demonstration, we return a mock response
29+
if units == "c":
30+
return json.dumps(
31+
{
32+
"location": location,
33+
"temperature": "20°C",
34+
"condition": "Sunny",
35+
}
36+
)
37+
else:
38+
return json.dumps(
39+
{
40+
"location": location,
41+
"temperature": "68°F",
42+
"condition": "Sunny",
43+
}
44+
)
45+
46+
47+
def make_tool_searcher(tools: List[BetaFunctionTool[Any]]) -> BetaFunctionTool[Any]:
48+
"""Returns a tool that Claude can use to search through all available tools"""
49+
50+
@beta_tool
51+
def search_available_tools(*, keyword: str) -> BetaFunctionToolResultType:
52+
"""Search for useful tools using a query string"""
53+
54+
results: list[BetaToolReferenceBlockParam] = []
55+
for tool in tools:
56+
if keyword in json.dumps(tool.to_dict()):
57+
results.append({"type": "tool_reference", "tool_name": tool.name})
58+
59+
return results
60+
61+
return search_available_tools
62+
63+
64+
def main() -> None:
65+
tools: list[BetaFunctionTool[Any]] = [
66+
get_weather,
67+
# ... many more tools
68+
]
69+
runner = client.beta.messages.tool_runner(
70+
max_tokens=1024,
71+
model="claude-sonnet-4-5-20250929",
72+
tools=[*tools, make_tool_searcher(tools)],
73+
messages=[{"role": "user", "content": "What is the weather in SF?"}],
74+
betas=["tool-search-tool-2025-10-19"],
75+
)
76+
for message in runner:
77+
rich.print(message)
78+
79+
80+
main()

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ show_error_codes = true
160160
#
161161
# We also exclude our `tests` as mypy doesn't always infer
162162
# types correctly and Pyright will still catch any type errors.
163-
exclude = ['src/anthropic/_files.py', '_dev/.*.py', 'tests/.*', 'examples/mcp_server_weather.py', 'examples/tools_with_mcp.py', 'examples/memory/basic.py', 'src/anthropic/lib/_parse/_transform.py']
163+
exclude = ['src/anthropic/_files.py', '_dev/.*.py', 'tests/.*', 'examples/mcp_server_weather.py', 'examples/tools_with_mcp.py', 'examples/memory/basic.py', 'src/anthropic/lib/_parse/_transform.py', 'src/anthropic/lib/tools/_beta_functions.py']
164164

165165
strict_equality = true
166166
implicit_reexport = true

src/anthropic/lib/streaming/_beta_messages.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -468,7 +468,7 @@ def accumulate_event(
468468
current_snapshot.content.append(
469469
cast(
470470
Any, # Pydantic does not support generic unions at runtime
471-
construct_type(type_=ParsedBetaContentBlock, value=event.content_block.model_dump()),
471+
construct_type(type_=ParsedBetaContentBlock, value=event.content_block.to_dict()),
472472
),
473473
)
474474
elif event.type == "content_block_delta":
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
from typing import TypedDict
2+
from typing_extensions import Required
3+
4+
DEFAULT_SUMMARY_PROMPT = """You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
5+
1. Task Overview
6+
The user's core request and success criteria
7+
Any clarifications or constraints they specified
8+
2. Current State
9+
What has been completed so far
10+
Files created, modified, or analyzed (with paths if relevant)
11+
Key outputs or artifacts produced
12+
3. Important Discoveries
13+
Technical constraints or requirements uncovered
14+
Decisions made and their rationale
15+
Errors encountered and how they were resolved
16+
What approaches were tried that didn't work (and why)
17+
4. Next Steps
18+
Specific actions needed to complete the task
19+
Any blockers or open questions to resolve
20+
Priority order if multiple steps remain
21+
5. Context to Preserve
22+
User preferences or style requirements
23+
Domain-specific details that aren't obvious
24+
Any promises made to the user
25+
Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
26+
Wrap your summary in <summary></summary> tags."""
27+
28+
DEFAULT_THRESHOLD = 100_000
29+
30+
31+
class CompactionControl(TypedDict, total=False):
32+
context_token_threshold: int
33+
"""The context token threshold at which to trigger compaction.
34+
35+
When the cumulative token count (input + output) across all messages exceeds this threshold,
36+
the message history will be automatically summarized and compressed. Defaults to 150,000 tokens.
37+
"""
38+
39+
model: str
40+
"""
41+
The model to use for generating the compaction summary.
42+
If not specified, defaults to the same model used for the tool runner.
43+
"""
44+
45+
summary_prompt: str
46+
"""The prompt used to instruct the model on how to generate the summary."""
47+
48+
enabled: Required[bool]

0 commit comments

Comments
 (0)