Debian Codegraph @

tests/lib/tools/test_runners.py

raw
1 import os
2 import json
3 import logging
4 from copy import copy
5 from typing import Any, Dict, List, Type, Union, cast
6 from collections.abc import Callable
7 from typing_extensions import Literal, get_args
8
9 import httpx2
10 import pytest
11 import pydantic
12 from respx import MockRouter
13 from inline_snapshot import external, snapshot
14
15 from anthropic import Anthropic, AsyncAnthropic, InternalServerError, beta_tool, beta_async_tool
16 from anthropic._types import Omit, omit
17 from anthropic._utils import assert_signatures_in_sync
18 from anthropic._compat import PYDANTIC_V1
19 from anthropic.lib.tools import BetaFunctionTool, BetaAsyncFunctionTool, BetaFunctionToolResultType
20 from anthropic.lib.tools._beta_runner import (
21 _STOP_REASON_STEPS,
22 BetaToolRunner,
23 BetaAsyncToolRunner,
24 _determine_next_step_from_stop_reason,
25 )
26 from anthropic.types.anthropic_beta_param import AnthropicBetaParam
27 from anthropic.types.beta.beta_tool_param import BetaToolParam
28 from anthropic.types.beta.beta_stop_reason import BetaStopReason
29 from anthropic.types.beta.beta_message_param import BetaMessageParam
30 from anthropic.types.beta.beta_fallback_param import BetaFallbackParam
31 from anthropic.types.beta.beta_tool_choice_param import BetaToolChoiceParam
32 from anthropic.types.beta.beta_content_block_param import BetaContentBlockParam
33 from anthropic.types.beta.beta_output_config_param import BetaOutputConfigParam
34 from anthropic.types.beta.beta_tool_result_block_param import BetaToolResultBlockParam
35 from anthropic.types.beta.beta_json_output_format_param import BetaJSONOutputFormatParam
36 from anthropic.types.beta.beta_web_search_tool_20250305_param import BetaWebSearchTool20250305Param
37 from anthropic.types.beta.beta_context_management_config_param import BetaContextManagementConfigParam
38 from anthropic.types.beta.beta_tool_change_tool_reference_param import BetaToolChangeToolReferenceParam
39
40 from ..utils import print_obj
41
42 base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010")
43
44 # all the snapshots in this file are auto-generated from the live API
45 #
46 # you can update them with
47 #
48 # `ANTHROPIC_LIVE=1 ./scripts/test --inline-snapshot=fix -n0`
49
50 snapshots = {
51 "basic": {
52 "responses": snapshot(
53 [
54 '{"model": "claude-haiku-4-5-20251001", "id": "msg_0133AjAuLSKXatUZqNkpALPx", "type": "message", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01DGiQScbZKPwUBYN79rFUb8", "name": "get_weather", "input": {"location": "San Francisco, CA", "units": "f"}}], "stop_reason": "tool_use", "stop_sequence": null, "usage": {"input_tokens": 656, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 74, "service_tier": "standard"}}',
55 '{"model": "claude-haiku-4-5-20251001", "id": "msg_014x2Sxq2p6sewFyUbJp8Mg3", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "The weather in San Francisco, CA is currently **68\\u00b0F** and **Sunny**. It\'s a nice day! \\u2600\\ufe0f"}], "stop_reason": "end_turn", "stop_sequence": null, "usage": {"input_tokens": 770, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 33, "service_tier": "standard"}}',
56 ]
57 ),
58 "result": snapshot(
59 """\
60 ParsedBetaMessage(
61 container=None,
62 content=[
63 ParsedBetaTextBlock(
64 citations=None,
65 parsed_output=None,
66 text='The weather in San Francisco, CA is currently **Sunny** with a temperature of **68°F**.',
67 type='text'
68 )
69 ],
70 context_management=None,
71 diagnostics=None,
72 id='msg_01BZsMQjer9AFLgmdRKJ8NcA',
73 input_transformations=None,
74 model='claude-haiku-4-5-20251001',
75 role='assistant',
76 stop_details=None,
77 stop_reason='end_turn',
78 stop_sequence=None,
79 type='message',
80 usage=BetaUsage(
81 cache_creation=BetaCacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0),
82 cache_creation_input_tokens=0,
83 cache_read_input_tokens=0,
84 fallback_credit=None,
85 inference_geo='not_available',
86 input_tokens=770,
87 iterations=None,
88 output_tokens=25,
89 output_tokens_details=None,
90 server_tool_use=None,
91 service_tier='standard',
92 speed=None
93 )
94 )
95 """
96 ),
97 },
98 "custom": {
99 "responses": snapshot(
100 [
101 '{"model": "claude-haiku-4-5-20251001", "id": "msg_01FKEKbzbqHmJv5ozwH7tz99", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "Let me check the weather for San Francisco for you in Celsius."}, {"type": "tool_use", "id": "toolu_01MxFFv4azdWzubHT3dXurMY", "name": "get_weather", "input": {"location": "San Francisco, CA", "units": "c"}}], "stop_reason": "tool_use", "stop_sequence": null, "usage": {"input_tokens": 659, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 88, "service_tier": "standard"}}',
102 '{"model": "claude-haiku-4-5-20251001", "id": "msg_01DSPL7PHKQYTe9VAFkHzsA3", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "The weather in San Francisco, CA is currently **20\\u00b0C** and **Sunny**. Nice weather!"}], "stop_reason": "end_turn", "stop_sequence": null, "usage": {"input_tokens": 787, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 26, "service_tier": "standard"}}',
103 ]
104 ),
105 "result": snapshot(
106 "ParsedBetaMessage(container=None, content=[ParsedBetaTextBlock(citations=None, parsed_output=None, text='The weather in San Francisco, CA is currently **20°C** and **Sunny**. Nice weather!', type='text')], context_management=None, id='msg_01DSPL7PHKQYTe9VAFkHzsA3', model='claude-haiku-4-5-20251001', role='assistant', stop_details=None, stop_reason='end_turn', stop_sequence=None, type='message', usage=BetaUsage(cache_creation=BetaCacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0), cache_creation_input_tokens=0, cache_read_input_tokens=0, inference_geo=None, input_tokens=787, iterations=None, output_tokens=26, server_tool_use=None, service_tier='standard', speed=None))\n"
107 ),
108 },
109 "streaming": {
110 "result": snapshot(
111 """\
112 ParsedBetaMessage(
113 container=None,
114 content=[
115 ParsedBetaTextBlock(
116 citations=None,
117 parsed_output=None,
118 text="The weather in San Francisco, CA is currently **68°F and Sunny**. It's a nice day!",
119 type='text'
120 )
121 ],
122 context_management=None,
123 diagnostics=None,
124 id='msg_0158JyopQTFaomteeJoDpS5q',
125 input_transformations=None,
126 model='claude-haiku-4-5-20251001',
127 role='assistant',
128 stop_details=None,
129 stop_reason='end_turn',
130 stop_sequence=None,
131 type='message',
132 usage=BetaUsage(
133 cache_creation=BetaCacheCreation(ephemeral_1h_input_tokens=0, ephemeral_5m_input_tokens=0),
134 cache_creation_input_tokens=0,
135 cache_read_input_tokens=0,
136 fallback_credit=None,
137 inference_geo='not_available',
138 input_tokens=770,
139 iterations=None,
140 output_tokens=27,
141 output_tokens_details=None,
142 server_tool_use=None,
143 service_tier='standard',
144 speed=None
145 )
146 )
147 """
148 )
149 },
150 "tool_call": {
151 "responses": snapshot(
152 [
153 '{"model": "claude-haiku-4-5-20251001", "id": "msg_01NzLkujbJ7VQgzNHFx76Ab4", "type": "message", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01SPe52JjANtJDVJ5yUZj4jz", "name": "get_weather", "input": {"location": "SF", "units": "c"}}], "stop_reason": "tool_use", "stop_sequence": null, "usage": {"input_tokens": 597, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 71, "service_tier": "standard"}}',
154 '{"model": "claude-haiku-4-5-20251001", "id": "msg_016bjf5SAczxp28ES4yX7Z7U", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "The weather in SF (San Francisco) is currently **20\\u00b0C** and **sunny**!"}], "stop_reason": "end_turn", "stop_sequence": null, "usage": {"input_tokens": 705, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 23, "service_tier": "standard"}}',
155 ]
156 ),
157 },
158 "tool_call_error": {
159 "responses": snapshot(
160 [
161 '{"model": "claude-haiku-4-5-20251001", "id": "msg_01QhmJFoA3mxD2mxPFnjLHrT", "type": "message", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01Do4cDVNxt51EuosKoxdmii", "name": "get_weather", "input": {"location": "San Francisco, CA", "units": "f"}}], "stop_reason": "tool_use", "stop_sequence": null, "usage": {"input_tokens": 656, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 74, "service_tier": "standard"}}',
162 '{"model": "claude-haiku-4-5-20251001", "id": "msg_0137FupJYD4A3Mc6jUUxKpU6", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "I apologize, but I encountered an error when trying to fetch the weather for San Francisco. This appears to be a temporary issue with the weather service. Could you please try again in a moment, or let me know if you\'d like me to attempt the lookup again?"}], "stop_reason": "end_turn", "stop_sequence": null, "usage": {"input_tokens": 760, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 0}, "output_tokens": 58, "service_tier": "standard"}}',
163 ]
164 )
165 },
166 }
167
168
169 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
170 class TestSyncRunTools:
171 @pytest.mark.parametrize(
172 "http_snapshot",
173 [
174 cast(Any, external("uuid:b38bbf6c-9a76-40ca-b09d-7a3911776e0f.json")),
175 ],
176 )
177 def test_basic_call_sync(self, snapshot_client: Anthropic) -> None:
178 @beta_tool
179 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
180 """Lookup the weather for a given city in either celsius or fahrenheit
181
182 Args:
183 location: The city and state, e.g. San Francisco, CA
184 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
185 Returns:
186 A dictionary containing the location, temperature, and weather condition.
187 """
188 return json.dumps(_get_weather(location, units))
189
190 message = snapshot_client.beta.messages.tool_runner(
191 max_tokens=1024,
192 model="claude-haiku-4-5",
193 tools=[get_weather],
194 messages=[{"role": "user", "content": "What is the weather in SF?"}],
195 ).until_done()
196
197 assert print_obj(message) == snapshots["basic"]["result"]
198
199 @pytest.mark.parametrize(
200 "http_snapshot",
201 [
202 cast(Any, external("uuid:10e53c1d-51be-4c64-b5bf-99adb3fa4719.json")),
203 ],
204 )
205 def test_tool_call_error(
206 self,
207 snapshot_client: Anthropic,
208 caplog: pytest.LogCaptureFixture,
209 ) -> None:
210 called = None
211
212 @beta_tool
213 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
214 """Lookup the weather for a given city in either celsius or fahrenheit
215
216 Args:
217 location: The city and state, e.g. San Francisco, CA
218 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
219 Returns:
220 A dictionary containing the location, temperature, and weather condition.
221 """
222 nonlocal called
223
224 if called is None:
225 called = True
226 raise RuntimeError("Unexpected error, try again")
227 return json.dumps(_get_weather(location, units))
228
229 runner = snapshot_client.beta.messages.tool_runner(
230 max_tokens=1024,
231 model="claude-haiku-4-5",
232 tools=[get_weather],
233 messages=[{"role": "user", "content": "What is the weather in SF?"}],
234 )
235
236 actual_responses: List[Union[BetaMessageParam, None]] = []
237 with caplog.at_level(logging.ERROR):
238 for _ in runner:
239 tool_call_response = runner.generate_tool_call_response()
240 if tool_call_response is not None:
241 actual_responses.append(tool_call_response)
242
243 message = actual_responses
244
245 assert caplog.record_tuples == [
246 (
247 "anthropic.lib.tools._beta_runner",
248 logging.ERROR,
249 "Error occurred while calling tool: get_weather",
250 ),
251 ]
252 assert print_obj(message) == snapshot(
253 """\
254 [
255 {
256 'role': 'user',
257 'content': [
258 {
259 'type': 'tool_result',
260 'tool_use_id': 'toolu_01A9HHF5Ezy3oBrKmSgfASm9',
261 'content': "RuntimeError('Unexpected error, try again')",
262 'is_error': True
263 }
264 ]
265 }
266 ]
267 """
268 )
269
270 @pytest.mark.parametrize(
271 "http_snapshot",
272 [
273 cast(Any, external("uuid:f59a9391-643b-422c-96dc-1f28bc7ea4d7.json")),
274 ],
275 )
276 # TODO: fix the append_messages method
277 @pytest.mark.xfail(reason="bug in append messages")
278 def test_custom_message_handling(self, snapshot_client: Anthropic) -> None:
279 @beta_tool
280 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
281 """Lookup the weather for a given city in either celsius or fahrenheit
282
283 Args:
284 location: The city and state, e.g. San Francisco, CA
285 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
286 Returns:
287 A dictionary containing the location, temperature, and weather condition.
288 """
289 return json.dumps(_get_weather(location, units))
290
291 runner = snapshot_client.beta.messages.tool_runner(
292 model="claude-haiku-4-5",
293 messages=[{"role": "user", "content": "What's the weather in SF in Celsius?"}],
294 tools=[get_weather],
295 max_tokens=1024,
296 )
297
298 for message_iter in runner:
299 if message_iter.content[0].type == "tool_use":
300 runner.append_messages(
301 BetaMessageParam(
302 role="user",
303 content=[
304 BetaToolResultBlockParam(
305 tool_use_id=message_iter.content[0].id,
306 content="The weather in San Francisco, CA is currently sunny with a temperature of 20°C.",
307 type="tool_result",
308 )
309 ],
310 ),
311 )
312
313 message = runner.until_done()
314
315 assert print_obj(message) == snapshots["custom"]["result"]
316
317 @pytest.mark.parametrize(
318 "http_snapshot",
319 [
320 cast(Any, external("uuid:a8ac789b-f856-48cd-9ff3-d5f36799e432.json")),
321 ],
322 )
323 def test_tool_call_caching(self, snapshot_client: Anthropic) -> None:
324 called = None
325
326 @beta_tool
327 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
328 nonlocal called
329 """Lookup the weather for a given city in either celsius or fahrenheit
330
331 Args:
332 location: The city and state, e.g. San Francisco, CA
333 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
334 Returns:
335 A dictionary containing the location, temperature, and weather condition.
336 """
337 if called is None:
338 called = True
339 return json.dumps(_get_weather(location, units))
340 raise RuntimeError("This tool should not be called again")
341
342 runner = snapshot_client.beta.messages.tool_runner(
343 model="claude-haiku-4-5",
344 messages=[{"role": "user", "content": "What's the weather in SF in Celsius?"}],
345 tools=[get_weather],
346 max_tokens=1024,
347 )
348
349 for _ in runner:
350 response1 = runner.generate_tool_call_response()
351 response2 = runner.generate_tool_call_response()
352
353 if response1 is not None:
354 assert response1 is response2
355
356 @pytest.mark.parametrize(
357 "http_snapshot",
358 [
359 cast(Any, external("uuid:771c64ff-a0af-4cd9-8080-a5a539da7cb9.json")),
360 ],
361 )
362 def test_streaming_call_sync(self, snapshot_client: Anthropic) -> None:
363 @beta_tool
364 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
365 """Lookup the weather for a given city in either celsius or fahrenheit
366
367 Args:
368 location: The city and state, e.g. San Francisco, CA
369 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
370 Returns:
371 A dictionary containing the location, temperature, and weather condition.
372 """
373 return json.dumps(_get_weather(location, units))
374
375 last_response_messsage = snapshot_client.beta.messages.tool_runner(
376 max_tokens=1024,
377 model="claude-haiku-4-5",
378 tools=[get_weather],
379 messages=[{"role": "user", "content": "What is the weather in SF?"}],
380 stream=True,
381 ).until_done()
382
383 assert print_obj(last_response_messsage) == snapshots["streaming"]["result"]
384
385 @pytest.mark.parametrize(
386 "http_snapshot",
387 [
388 cast(Any, external("uuid:e075a6c2-de4d-4125-9709-f0e178058190.json")),
389 ],
390 )
391 def test_max_iterations(self, snapshot_client: Anthropic) -> None:
392 @beta_tool
393 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
394 """Lookup the weather for a given city in either celsius or fahrenheit
395
396 Args:
397 location: The city and state, e.g. San Francisco, CA
398 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
399 Returns:
400 A dictionary containing the location, temperature, and weather condition.
401 """
402 return json.dumps(_get_weather(location, units))
403
404 runner = snapshot_client.beta.messages.tool_runner(
405 max_tokens=1024,
406 model="claude-haiku-4-5",
407 tools=[get_weather],
408 messages=[
409 {
410 "role": "user",
411 "content": (
412 "What's the weather in San Francisco, New York, London, Tokyo and Paris?"
413 "If you need to use tools, call only one tool at a time. Wait for the tool's"
414 "response before making another call. Never call multiple tools at once."
415 ),
416 }
417 ],
418 max_iterations=2,
419 )
420
421 answers: List[Union[BetaMessageParam, None]] = []
422
423 for _ in runner:
424 answers.append(runner.generate_tool_call_response())
425
426 assert print_obj(answers) == snapshot(
427 """\
428 [
429 {
430 'role': 'user',
431 'content': [
432 {
433 'type': 'tool_result',
434 'tool_use_id': 'toolu_01LRanfq6DmHn1yDTB4d1SAh',
435 'content': '{"location": "San Francisco, CA", "temperature": "68\\\\u00b0F", "condition": "Sunny"}'
436 }
437 ]
438 },
439 {
440 'role': 'user',
441 'content': [
442 {
443 'type': 'tool_result',
444 'tool_use_id': 'toolu_01RWdcDdE8NAFDgZ8F9Xk2K7',
445 'content': '{"location": "New York, NY", "temperature": "68\\\\u00b0F", "condition": "Sunny"}'
446 }
447 ]
448 }
449 ]
450 """
451 )
452
453 @pytest.mark.parametrize(
454 "http_snapshot",
455 [
456 cast(Any, external("uuid:555fb399-a54c-455b-9ac5-2c9673f18e12.json")),
457 ],
458 )
459 def test_streaming_call_sync_events(self, snapshot_client: Anthropic) -> None:
460 @beta_tool
461 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
462 """Lookup the weather for a given city in either celsius or fahrenheit
463
464 Args:
465 location: The city and state, e.g. San Francisco, CA
466 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
467 Returns:
468 A dictionary containing the location, temperature, and weather condition.
469 """
470 return json.dumps(_get_weather(location, units))
471
472 events: list[str] = []
473 runner = snapshot_client.beta.messages.tool_runner(
474 max_tokens=1024,
475 model="claude-haiku-4-5",
476 tools=[get_weather],
477 messages=[{"role": "user", "content": "What is the weather in SF?"}],
478 stream=True,
479 )
480
481 for stream in runner:
482 for event in stream:
483 events.append(event.type)
484
485 assert set(events) == snapshot(
486 {
487 "content_block_delta",
488 "content_block_start",
489 "content_block_stop",
490 "input_json",
491 "message_delta",
492 "message_start",
493 "message_stop",
494 "text",
495 }
496 )
497
498 @pytest.mark.parametrize("snapshot_client", [False], indirect=True)
499 @pytest.mark.parametrize(
500 "http_snapshot",
501 [
502 cast(Any, external("uuid:32da0815-2270-4d29-87be-3b5b63ab42e2.json")),
503 ],
504 )
505 def test_server_side_tool(
506 self,
507 snapshot_client: Anthropic,
508 ) -> None:
509 runner = snapshot_client.beta.messages.tool_runner(
510 model="claude-haiku-4-5",
511 messages=[{"role": "user", "content": "What is the weather in SF?"}],
512 tools=[
513 {
514 "type": "web_search_20250305",
515 "name": "web_search",
516 }
517 ],
518 max_tokens=1024,
519 )
520
521 message = next(runner)
522
523 content_types = [content.type for content in message.content]
524
525 assert "server_tool_use" in content_types
526 assert "web_search_tool_result" in content_types
527
528 @pytest.mark.parametrize(
529 "http_snapshot",
530 [
531 cast(Any, external("uuid:092be1de-d3f8-4c22-a4ea-a7ad54689836.json")),
532 ],
533 )
534 def test_programmatic_tool_call(self, snapshot_client: Anthropic) -> None:
535 @beta_tool(allowed_callers=["code_execution_20260120"])
536 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
537 """Lookup the weather for a given city in either celsius or fahrenheit
538
539 Args:
540 location: The city and state, e.g. San Francisco, CA
541 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
542 Returns:
543 A dictionary containing the location, temperature, and weather condition.
544 """
545 return json.dumps(_get_weather(location, units))
546
547 runner = snapshot_client.beta.messages.tool_runner(
548 max_tokens=1024,
549 model="claude-opus-4-5",
550 tools=[get_weather],
551 messages=[{"role": "user", "content": "What is the weather in SF, NY, and London in Celsius?"}],
552 )
553
554 first_response = next(runner)
555
556 # one more iteration so runner can process the tool call response and update its params with the container info
557 next(runner)
558
559 assert first_response.container is not None
560 container_id = first_response.container.id
561 assert "container" in runner._params
562 assert runner._params["container"] is not None
563 assert container_id == runner._params["container"]
564
565
566 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
567 @pytest.mark.parametrize(
568 "http_snapshot",
569 [
570 cast(Any, external("uuid:64fe7974-681a-4023-9848-b32ba39c8664.json")),
571 ],
572 )
573 async def test_basic_call_async(async_snapshot_client: AsyncAnthropic) -> None:
574 @beta_async_tool
575 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
576 """Lookup the weather for a given city in either celsius or fahrenheit
577
578 Args:
579 location: The city and state, e.g. San Francisco, CA
580 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
581 Returns:
582 A dictionary containing the location, temperature, and weather condition.
583 """
584 return json.dumps(_get_weather(location, units))
585
586 await async_snapshot_client.beta.messages.tool_runner(
587 max_tokens=1024,
588 model="claude-haiku-4-5",
589 tools=[get_weather],
590 messages=[{"role": "user", "content": "What is the weather in SF?"}],
591 ).until_done()
592
593
594 def _refusal_with_tool_use() -> httpx2.Response:
595 return httpx2.Response(
596 200,
597 json={
598 "id": "msg_refusal",
599 "type": "message",
600 "role": "assistant",
601 "model": "claude-haiku-4-5",
602 "content": [
603 {
604 "type": "tool_use",
605 "id": "toolu_refusal",
606 "name": "get_weather",
607 "input": {"location": "San Francisco, CA", "units": "f"},
608 }
609 ],
610 "stop_reason": "refusal",
611 "stop_sequence": None,
612 "usage": {"input_tokens": 1, "output_tokens": 1},
613 },
614 )
615
616
617 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
618 @pytest.mark.respx(base_url=base_url)
619 def test_refusal_ends_runner_without_executing_tools_sync(respx_mock: MockRouter) -> None:
620 respx_mock.post("/v1/messages").mock(side_effect=[_refusal_with_tool_use()])
621
622 called = False
623
624 @beta_tool
625 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
626 """Lookup the weather for a given city in either celsius or fahrenheit
627
628 Args:
629 location: The city and state, e.g. San Francisco, CA
630 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
631 Returns:
632 A dictionary containing the location, temperature, and weather condition.
633 """
634 nonlocal called
635 called = True
636 return json.dumps(_get_weather(location, units))
637
638 with Anthropic(
639 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
640 ) as client:
641 runner = client.beta.messages.tool_runner(
642 max_tokens=1024,
643 model="claude-haiku-4-5",
644 tools=[get_weather],
645 messages=[{"role": "user", "content": "What is the weather in SF?"}],
646 )
647 message = runner.until_done()
648
649 assert message.stop_reason == "refusal"
650 assert called is False
651 assert len(respx_mock.calls) == 1
652
653
654 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
655 @pytest.mark.respx(base_url=base_url)
656 async def test_refusal_ends_runner_without_executing_tools_async(respx_mock: MockRouter) -> None:
657 respx_mock.post("/v1/messages").mock(side_effect=[_refusal_with_tool_use()])
658
659 called = False
660
661 @beta_async_tool
662 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
663 """Lookup the weather for a given city in either celsius or fahrenheit
664
665 Args:
666 location: The city and state, e.g. San Francisco, CA
667 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
668 Returns:
669 A dictionary containing the location, temperature, and weather condition.
670 """
671 nonlocal called
672 called = True
673 return json.dumps(_get_weather(location, units))
674
675 async with AsyncAnthropic(
676 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
677 ) as client:
678 runner = client.beta.messages.tool_runner(
679 max_tokens=1024,
680 model="claude-haiku-4-5",
681 tools=[get_weather],
682 messages=[{"role": "user", "content": "What is the weather in SF?"}],
683 )
684 message = await runner.until_done()
685
686 assert message.stop_reason == "refusal"
687 assert called is False
688 assert len(respx_mock.calls) == 1
689
690
691 def _paused_server_tool_use() -> httpx2.Response:
692 return httpx2.Response(
693 200,
694 json={
695 "id": "msg_paused",
696 "type": "message",
697 "role": "assistant",
698 "model": "claude-haiku-4-5",
699 "content": [
700 {
701 "type": "server_tool_use",
702 "id": "srvtoolu_paused",
703 "name": "web_search",
704 "input": {"query": "weather in SF"},
705 }
706 ],
707 "stop_reason": "pause_turn",
708 "stop_sequence": None,
709 "usage": {"input_tokens": 1, "output_tokens": 1},
710 },
711 )
712
713
714 _PAUSED_ASSISTANT_TURN = {
715 "role": "assistant",
716 "content": [
717 {"type": "server_tool_use", "id": "srvtoolu_paused", "name": "web_search", "input": {"query": "weather in SF"}}
718 ],
719 }
720
721
722 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
723 @pytest.mark.respx(base_url=base_url)
724 def test_pause_turn_resumes_runner_sync(respx_mock: MockRouter) -> None:
725 respx_mock.post("/v1/messages").mock(side_effect=[_paused_server_tool_use(), _end_turn_response()])
726
727 @beta_tool
728 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
729 """Lookup the weather for a given city.
730
731 Args:
732 location: The city and state, e.g. San Francisco, CA
733 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
734 """
735 return json.dumps(_get_weather(location, units))
736
737 with Anthropic(
738 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
739 ) as client:
740 message = client.beta.messages.tool_runner(
741 max_tokens=1024,
742 model="claude-haiku-4-5",
743 tools=[get_weather, {"type": "web_search_20250305", "name": "web_search"}],
744 messages=[{"role": "user", "content": "What is the weather in SF?"}],
745 ).until_done()
746
747 assert message.stop_reason == "end_turn"
748 assert len(respx_mock.calls) == 2
749 assert json.loads(respx_mock.calls.last.request.content)["messages"][-1] == _PAUSED_ASSISTANT_TURN
750
751
752 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
753 @pytest.mark.respx(base_url=base_url)
754 async def test_pause_turn_resumes_runner_async(respx_mock: MockRouter) -> None:
755 respx_mock.post("/v1/messages").mock(side_effect=[_paused_server_tool_use(), _end_turn_response()])
756
757 @beta_async_tool
758 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
759 """Lookup the weather for a given city.
760
761 Args:
762 location: The city and state, e.g. San Francisco, CA
763 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
764 """
765 return json.dumps(_get_weather(location, units))
766
767 async with AsyncAnthropic(
768 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
769 ) as client:
770 message = await client.beta.messages.tool_runner(
771 max_tokens=1024,
772 model="claude-haiku-4-5",
773 tools=[get_weather, {"type": "web_search_20250305", "name": "web_search"}],
774 messages=[{"role": "user", "content": "What is the weather in SF?"}],
775 ).until_done()
776
777 assert message.stop_reason == "end_turn"
778 assert len(respx_mock.calls) == 2
779 assert json.loads(respx_mock.calls.last.request.content)["messages"][-1] == _PAUSED_ASSISTANT_TURN
780
781
782 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
783 @pytest.mark.respx(base_url=base_url)
784 def test_pause_turn_respects_max_iterations_sync(respx_mock: MockRouter) -> None:
785 respx_mock.post("/v1/messages").mock(side_effect=[_paused_server_tool_use() for _ in range(5)])
786
787 with Anthropic(
788 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
789 ) as client:
790 message = client.beta.messages.tool_runner(
791 max_tokens=1024,
792 model="claude-haiku-4-5",
793 tools=[{"type": "web_search_20250305", "name": "web_search"}],
794 messages=[{"role": "user", "content": "What is the weather in SF?"}],
795 max_iterations=3,
796 ).until_done()
797
798 assert message.stop_reason == "pause_turn"
799 assert len(respx_mock.calls) == 3
800
801
802 def test_every_stop_reason_is_classified() -> None:
803 # A newly generated stop reason must be mapped to a step before this passes.
804 assert set(get_args(BetaStopReason)) == set(_STOP_REASON_STEPS)
805
806 expected: Dict[BetaStopReason, str] = {
807 "tool_use": "run_tools",
808 "pause_turn": "resume",
809 "compaction": "resume",
810 "end_turn": "stop",
811 "stop_sequence": "stop",
812 "max_tokens": "stop",
813 "model_context_window_exceeded": "stop",
814 "refusal": "stop",
815 }
816 assert {
817 stop_reason: _determine_next_step_from_stop_reason(stop_reason) for stop_reason in get_args(BetaStopReason)
818 } == expected
819 assert _determine_next_step_from_stop_reason(None) == "stop"
820 assert _determine_next_step_from_stop_reason(cast(Any, "some_future_reason")) == "stop"
821
822
823 def _compaction_response() -> httpx2.Response:
824 return httpx2.Response(
825 200,
826 json={
827 "id": "msg_compaction",
828 "type": "message",
829 "role": "assistant",
830 "model": "claude-haiku-4-5",
831 "content": [{"type": "compaction", "content": "Summary of the conversation so far."}],
832 "stop_reason": "compaction",
833 "stop_sequence": None,
834 "usage": {"input_tokens": 1, "output_tokens": 1},
835 },
836 )
837
838
839 _COMPACTION_ASSISTANT_TURN = {
840 "role": "assistant",
841 "content": [{"type": "compaction", "content": "Summary of the conversation so far."}],
842 }
843
844
845 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
846 @pytest.mark.respx(base_url=base_url)
847 def test_compaction_resumes_runner_sync(respx_mock: MockRouter) -> None:
848 respx_mock.post("/v1/messages").mock(side_effect=[_compaction_response(), _end_turn_response()])
849
850 @beta_tool
851 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
852 """Lookup the weather for a given city.
853
854 Args:
855 location: The city and state, e.g. San Francisco, CA
856 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
857 """
858 return json.dumps(_get_weather(location, units))
859
860 with Anthropic(
861 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
862 ) as client:
863 message = client.beta.messages.tool_runner(
864 max_tokens=1024,
865 model="claude-haiku-4-5",
866 tools=[get_weather],
867 messages=[{"role": "user", "content": "What is the weather in SF?"}],
868 ).until_done()
869
870 assert message.stop_reason == "end_turn"
871 assert len(respx_mock.calls) == 2
872 assert json.loads(respx_mock.calls.last.request.content)["messages"][-1] == _COMPACTION_ASSISTANT_TURN
873
874
875 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
876 @pytest.mark.respx(base_url=base_url)
877 async def test_compaction_resumes_runner_async(respx_mock: MockRouter) -> None:
878 respx_mock.post("/v1/messages").mock(side_effect=[_compaction_response(), _end_turn_response()])
879
880 @beta_async_tool
881 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
882 """Lookup the weather for a given city.
883
884 Args:
885 location: The city and state, e.g. San Francisco, CA
886 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
887 """
888 return json.dumps(_get_weather(location, units))
889
890 async with AsyncAnthropic(
891 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
892 ) as client:
893 message = await client.beta.messages.tool_runner(
894 max_tokens=1024,
895 model="claude-haiku-4-5",
896 tools=[get_weather],
897 messages=[{"role": "user", "content": "What is the weather in SF?"}],
898 ).until_done()
899
900 assert message.stop_reason == "end_turn"
901 assert len(respx_mock.calls) == 2
902 assert json.loads(respx_mock.calls.last.request.content)["messages"][-1] == _COMPACTION_ASSISTANT_TURN
903
904
905 def _max_tokens_with_tool_use() -> httpx2.Response:
906 return httpx2.Response(
907 200,
908 json={
909 "id": "msg_max_tokens",
910 "type": "message",
911 "role": "assistant",
912 "model": "claude-haiku-4-5",
913 "content": [
914 {
915 "type": "tool_use",
916 "id": "toolu_max_tokens",
917 "name": "get_weather",
918 "input": {"location": "San Francisco, CA", "units": "f"},
919 }
920 ],
921 "stop_reason": "max_tokens",
922 "stop_sequence": None,
923 "usage": {"input_tokens": 1, "output_tokens": 1},
924 },
925 )
926
927
928 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
929 @pytest.mark.respx(base_url=base_url)
930 def test_max_tokens_ends_runner_without_executing_tools_sync(respx_mock: MockRouter) -> None:
931 respx_mock.post("/v1/messages").mock(side_effect=[_max_tokens_with_tool_use()])
932
933 called = False
934
935 @beta_tool
936 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
937 """Lookup the weather for a given city.
938
939 Args:
940 location: The city and state, e.g. San Francisco, CA
941 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
942 """
943 nonlocal called
944 called = True
945 return json.dumps(_get_weather(location, units))
946
947 with Anthropic(
948 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
949 ) as client:
950 message = client.beta.messages.tool_runner(
951 max_tokens=1024,
952 model="claude-haiku-4-5",
953 tools=[get_weather],
954 messages=[{"role": "user", "content": "What is the weather in SF?"}],
955 ).until_done()
956
957 assert message.stop_reason == "max_tokens"
958 assert called is False
959 assert len(respx_mock.calls) == 1
960
961
962 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
963 @pytest.mark.respx(base_url=base_url)
964 async def test_max_tokens_ends_runner_without_executing_tools_async(respx_mock: MockRouter) -> None:
965 respx_mock.post("/v1/messages").mock(side_effect=[_max_tokens_with_tool_use()])
966
967 called = False
968
969 @beta_async_tool
970 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
971 """Lookup the weather for a given city.
972
973 Args:
974 location: The city and state, e.g. San Francisco, CA
975 units: Unit for the output, either 'c' for celsius or 'f' for fahrenheit
976 """
977 nonlocal called
978 called = True
979 return json.dumps(_get_weather(location, units))
980
981 async with AsyncAnthropic(
982 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
983 ) as client:
984 message = await client.beta.messages.tool_runner(
985 max_tokens=1024,
986 model="claude-haiku-4-5",
987 tools=[get_weather],
988 messages=[{"role": "user", "content": "What is the weather in SF?"}],
989 ).until_done()
990
991 assert message.stop_reason == "max_tokens"
992 assert called is False
993 assert len(respx_mock.calls) == 1
994
995
996 def _tool_use_response(tool_name: str, tool_use_id: str, input: Union[Dict[str, Any], None] = None) -> httpx2.Response:
997 return httpx2.Response(
998 200,
999 json={
1000 "id": f"msg_{tool_use_id}",
1001 "type": "message",
1002 "role": "assistant",
1003 "model": "claude-haiku-4-5",
1004 "content": [
1005 {
1006 "type": "tool_use",
1007 "id": tool_use_id,
1008 "name": tool_name,
1009 "input": input if input is not None else {"location": "San Francisco, CA", "units": "f"},
1010 }
1011 ],
1012 "stop_reason": "tool_use",
1013 "stop_sequence": None,
1014 "usage": {"input_tokens": 1, "output_tokens": 1},
1015 },
1016 )
1017
1018
1019 def _end_turn_response() -> httpx2.Response:
1020 return httpx2.Response(
1021 200,
1022 json={
1023 "id": "msg_end_turn",
1024 "type": "message",
1025 "role": "assistant",
1026 "model": "claude-haiku-4-5",
1027 "content": [{"type": "text", "text": "Done."}],
1028 "stop_reason": "end_turn",
1029 "stop_sequence": None,
1030 "usage": {"input_tokens": 1, "output_tokens": 1},
1031 },
1032 )
1033
1034
1035 def _tool_reference_block(kind: Literal["tool_removal", "tool_addition"], name: str) -> BetaContentBlockParam:
1036 tool: BetaToolChangeToolReferenceParam = {"type": "tool_reference", "name": name}
1037 if kind == "tool_removal":
1038 return {"type": "tool_removal", "tool": tool}
1039 return {"type": "tool_addition", "tool": tool}
1040
1041
1042 def _run_sync_tool_use(
1043 client: Anthropic,
1044 *,
1045 tools: List[Any],
1046 messages: List[BetaMessageParam],
1047 ) -> List[BetaMessageParam]:
1048 """Drive a tool runner over `messages` and collect the tool_result
1049 messages it generated."""
1050 runner = client.beta.messages.tool_runner(
1051 max_tokens=1024,
1052 model="claude-haiku-4-5",
1053 tools=tools,
1054 messages=messages,
1055 )
1056 responses: List[BetaMessageParam] = []
1057 for _ in runner:
1058 response = runner.generate_tool_call_response()
1059 if response is not None:
1060 responses.append(response)
1061 return responses
1062
1063
1064 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1065 @pytest.mark.respx(base_url=base_url)
1066 def test_tool_removal_routes_call_down_unknown_tool_path_sync(respx_mock: MockRouter) -> None:
1067 # First runner: `get_weather` is registered but withdrawn mid-conversation via `tool_removal`.
1068 # Second runner: `get_weather` was never declared at all. The model calls it in both;
1069 # the resulting tool_result must be identical.
1070 respx_mock.post("/v1/messages").mock(
1071 side_effect=[
1072 _tool_use_response("get_weather", "toolu_change"),
1073 _end_turn_response(),
1074 _tool_use_response("get_weather", "toolu_change"),
1075 _end_turn_response(),
1076 ]
1077 )
1078
1079 weather_called = False
1080
1081 @beta_tool
1082 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1083 """Lookup the weather for a given city."""
1084 nonlocal weather_called
1085 weather_called = True
1086 return json.dumps(_get_weather(location, units))
1087
1088 @beta_tool
1089 def get_time(timezone: str) -> BetaFunctionToolResultType:
1090 """Lookup the current time in a timezone."""
1091 return timezone
1092
1093 with Anthropic(
1094 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1095 ) as client:
1096 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1097 removed_results = _run_sync_tool_use(
1098 client,
1099 tools=[get_weather],
1100 messages=[
1101 {"role": "user", "content": "What is the weather in SF?"},
1102 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1103 ],
1104 )
1105 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1106 never_defined_results = _run_sync_tool_use(
1107 client,
1108 tools=[get_time],
1109 messages=[{"role": "user", "content": "What is the weather in SF?"}],
1110 )
1111
1112 assert weather_called is False
1113 assert (
1114 removed_results
1115 == never_defined_results
1116 == [
1117 {
1118 "role": "user",
1119 "content": [
1120 {
1121 "type": "tool_result",
1122 "tool_use_id": "toolu_change",
1123 "content": "Error: Tool 'get_weather' not found",
1124 "is_error": True,
1125 }
1126 ],
1127 }
1128 ]
1129 )
1130
1131
1132 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1133 @pytest.mark.respx(base_url=base_url)
1134 def test_tool_addition_re_enables_removed_tool_sync(respx_mock: MockRouter) -> None:
1135 respx_mock.post("/v1/messages").mock(
1136 side_effect=[
1137 _tool_use_response("get_weather", "toolu_change"),
1138 _end_turn_response(),
1139 ]
1140 )
1141
1142 weather_called = False
1143
1144 @beta_tool
1145 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1146 """Lookup the weather for a given city."""
1147 nonlocal weather_called
1148 weather_called = True
1149 return json.dumps(_get_weather(location, units))
1150
1151 with Anthropic(
1152 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1153 ) as client:
1154 results = _run_sync_tool_use(
1155 client,
1156 tools=[get_weather],
1157 messages=[
1158 {"role": "user", "content": "What is the weather in SF?"},
1159 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1160 {"role": "system", "content": [_tool_reference_block("tool_addition", "get_weather")]},
1161 ],
1162 )
1163
1164 assert weather_called is True
1165 assert results == [
1166 {
1167 "role": "user",
1168 "content": [
1169 {
1170 "type": "tool_result",
1171 "tool_use_id": "toolu_change",
1172 "content": json.dumps(_get_weather("San Francisco, CA", "f")),
1173 }
1174 ],
1175 }
1176 ]
1177
1178
1179 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1180 @pytest.mark.respx(base_url=base_url)
1181 def test_tool_addition_by_value_re_enables_removed_tool_sync(respx_mock: MockRouter) -> None:
1182 respx_mock.post("/v1/messages").mock(
1183 side_effect=[
1184 _tool_use_response("get_weather", "toolu_change"),
1185 _end_turn_response(),
1186 ]
1187 )
1188
1189 weather_called = False
1190
1191 @beta_tool
1192 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1193 """Lookup the weather for a given city."""
1194 nonlocal weather_called
1195 weather_called = True
1196 return json.dumps(_get_weather(location, units))
1197
1198 with Anthropic(
1199 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1200 ) as client:
1201 results = _run_sync_tool_use(
1202 client,
1203 tools=[get_weather],
1204 messages=[
1205 {"role": "user", "content": "What is the weather in SF?"},
1206 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1207 {
1208 "role": "system",
1209 "content": [
1210 {
1211 "type": "tool_addition",
1212 "tool": {"type": "tool_definition", "definition": get_weather.to_dict()},
1213 }
1214 ],
1215 },
1216 ],
1217 )
1218
1219 assert weather_called is True
1220 assert results == [
1221 {
1222 "role": "user",
1223 "content": [
1224 {
1225 "type": "tool_result",
1226 "tool_use_id": "toolu_change",
1227 "content": json.dumps(_get_weather("San Francisco, CA", "f")),
1228 }
1229 ],
1230 }
1231 ]
1232
1233
1234 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1235 @pytest.mark.respx(base_url=base_url)
1236 async def test_tool_removal_routes_call_down_unknown_tool_path_async(respx_mock: MockRouter) -> None:
1237 respx_mock.post("/v1/messages").mock(
1238 side_effect=[
1239 _tool_use_response("get_weather", "toolu_change"),
1240 _end_turn_response(),
1241 ]
1242 )
1243
1244 weather_called = False
1245
1246 @beta_async_tool
1247 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1248 """Lookup the weather for a given city."""
1249 nonlocal weather_called
1250 weather_called = True
1251 return json.dumps(_get_weather(location, units))
1252
1253 async with AsyncAnthropic(
1254 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1255 ) as client:
1256 runner = client.beta.messages.tool_runner(
1257 max_tokens=1024,
1258 model="claude-haiku-4-5",
1259 tools=[get_weather],
1260 messages=[
1261 {"role": "user", "content": "What is the weather in SF?"},
1262 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1263 ],
1264 )
1265 results: List[BetaMessageParam] = []
1266 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1267 async for _ in runner:
1268 response = await runner.generate_tool_call_response()
1269 if response is not None:
1270 results.append(response)
1271
1272 assert weather_called is False
1273 assert results == [
1274 {
1275 "role": "user",
1276 "content": [
1277 {
1278 "type": "tool_result",
1279 "tool_use_id": "toolu_change",
1280 "content": "Error: Tool 'get_weather' not found",
1281 "is_error": True,
1282 }
1283 ],
1284 }
1285 ]
1286
1287
1288 def _not_found_result(tool_use_id: str) -> BetaMessageParam:
1289 return {
1290 "role": "user",
1291 "content": [
1292 {
1293 "type": "tool_result",
1294 "tool_use_id": tool_use_id,
1295 "content": "Error: Tool 'get_weather' not found",
1296 "is_error": True,
1297 }
1298 ],
1299 }
1300
1301
1302 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1303 @pytest.mark.respx(base_url=base_url)
1304 def test_tool_removal_via_append_messages_between_turns_sync(respx_mock: MockRouter) -> None:
1305 # The removal is not in the initial params: it is appended while iterating, on the
1306 # turn *before* the model calls the withdrawn tool.
1307 respx_mock.post("/v1/messages").mock(
1308 side_effect=[
1309 _tool_use_response("get_time", "toolu_time", input={"timezone": "UTC"}),
1310 _tool_use_response("get_weather", "toolu_weather"),
1311 _end_turn_response(),
1312 ]
1313 )
1314
1315 weather_called = False
1316
1317 @beta_tool
1318 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1319 """Lookup the weather for a given city."""
1320 nonlocal weather_called
1321 weather_called = True
1322 return json.dumps(_get_weather(location, units))
1323
1324 @beta_tool
1325 def get_time(timezone: str) -> BetaFunctionToolResultType:
1326 """Lookup the current time in a timezone."""
1327 return f"12:00 {timezone}"
1328
1329 with Anthropic(
1330 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1331 ) as client:
1332 runner = client.beta.messages.tool_runner(
1333 max_tokens=1024,
1334 model="claude-haiku-4-5",
1335 tools=[get_weather, get_time],
1336 messages=[{"role": "user", "content": "What time is it, and what is the weather in SF?"}],
1337 )
1338 results: List[BetaMessageParam] = []
1339 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1340 for message in runner:
1341 if any(block.type == "tool_use" and block.name == "get_time" for block in message.content):
1342 # Withdraw get_weather during turn 1; the model calls it on turn 2.
1343 runner.append_messages(
1344 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]}
1345 )
1346 response = runner.generate_tool_call_response()
1347 if response is not None:
1348 results.append(response)
1349
1350 assert weather_called is False
1351 assert results == [
1352 {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_time", "content": "12:00 UTC"}]},
1353 _not_found_result("toolu_weather"),
1354 ]
1355
1356
1357 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1358 @pytest.mark.respx(base_url=base_url)
1359 def test_tool_removal_via_append_messages_same_turn_sync(respx_mock: MockRouter) -> None:
1360 respx_mock.post("/v1/messages").mock(
1361 side_effect=[
1362 _tool_use_response("get_weather", "toolu_weather"),
1363 _end_turn_response(),
1364 ]
1365 )
1366
1367 weather_called = False
1368
1369 @beta_tool
1370 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1371 """Lookup the weather for a given city."""
1372 nonlocal weather_called
1373 weather_called = True
1374 return json.dumps(_get_weather(location, units))
1375
1376 with Anthropic(
1377 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1378 ) as client:
1379 runner = client.beta.messages.tool_runner(
1380 max_tokens=1024,
1381 model="claude-haiku-4-5",
1382 tools=[get_weather],
1383 messages=[{"role": "user", "content": "What is the weather in SF?"}],
1384 )
1385 results: List[BetaMessageParam] = []
1386 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1387 for message in runner:
1388 if any(block.type == "tool_use" for block in message.content):
1389 # The tool_use is already in `message`, but the runner has not dispatched it yet:
1390 # the loop body runs before dispatch, so a removal appended here still applies.
1391 runner.append_messages(
1392 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]}
1393 )
1394 response = runner.generate_tool_call_response()
1395 if response is not None:
1396 results.append(response)
1397
1398 assert weather_called is False
1399 assert results == [_not_found_result("toolu_weather")]
1400
1401
1402 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1403 @pytest.mark.respx(base_url=base_url)
1404 def test_tool_removal_via_set_messages_params_sync(respx_mock: MockRouter) -> None:
1405 respx_mock.post("/v1/messages").mock(
1406 side_effect=[
1407 _tool_use_response("get_time", "toolu_time", input={"timezone": "UTC"}),
1408 _tool_use_response("get_weather", "toolu_weather"),
1409 _end_turn_response(),
1410 ]
1411 )
1412
1413 weather_called = False
1414
1415 @beta_tool
1416 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1417 """Lookup the weather for a given city."""
1418 nonlocal weather_called
1419 weather_called = True
1420 return json.dumps(_get_weather(location, units))
1421
1422 @beta_tool
1423 def get_time(timezone: str) -> BetaFunctionToolResultType:
1424 """Lookup the current time in a timezone."""
1425 return f"12:00 {timezone}"
1426
1427 replacement_history: List[BetaMessageParam] = [
1428 {"role": "user", "content": "What time is it, and what is the weather in SF?"},
1429 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1430 ]
1431
1432 with Anthropic(
1433 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1434 ) as client:
1435 runner = client.beta.messages.tool_runner(
1436 max_tokens=1024,
1437 model="claude-haiku-4-5",
1438 tools=[get_weather, get_time],
1439 messages=[{"role": "user", "content": "What time is it, and what is the weather in SF?"}],
1440 )
1441 results: List[BetaMessageParam] = []
1442 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1443 for message in runner:
1444 if any(block.type == "tool_use" and block.name == "get_time" for block in message.content):
1445 # Replace the history wholesale with one carrying the removal.
1446 runner.set_messages_params(lambda params: {**params, "messages": list(replacement_history)})
1447 response = runner.generate_tool_call_response()
1448 if response is not None:
1449 results.append(response)
1450
1451 assert weather_called is False
1452 assert results == [
1453 {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "toolu_time", "content": "12:00 UTC"}]},
1454 _not_found_result("toolu_weather"),
1455 ]
1456
1457
1458 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1459 @pytest.mark.respx(base_url=base_url)
1460 def test_tool_addition_via_append_messages_re_enables_removed_tool_sync(respx_mock: MockRouter) -> None:
1461 respx_mock.post("/v1/messages").mock(
1462 side_effect=[
1463 _tool_use_response("get_weather", "toolu_weather"),
1464 _end_turn_response(),
1465 ]
1466 )
1467
1468 weather_called = False
1469
1470 @beta_tool
1471 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1472 """Lookup the weather for a given city."""
1473 nonlocal weather_called
1474 weather_called = True
1475 return json.dumps(_get_weather(location, units))
1476
1477 with Anthropic(
1478 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1479 ) as client:
1480 runner = client.beta.messages.tool_runner(
1481 max_tokens=1024,
1482 model="claude-haiku-4-5",
1483 tools=[get_weather],
1484 messages=[
1485 {"role": "user", "content": "What is the weather in SF?"},
1486 {"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]},
1487 ],
1488 )
1489 results: List[BetaMessageParam] = []
1490 for message in runner:
1491 if any(block.type == "tool_use" for block in message.content):
1492 # Re-add the withdrawn tool before dispatch: it must execute normally again.
1493 runner.append_messages(
1494 {"role": "system", "content": [_tool_reference_block("tool_addition", "get_weather")]}
1495 )
1496 response = runner.generate_tool_call_response()
1497 if response is not None:
1498 results.append(response)
1499
1500 assert weather_called is True
1501 assert results == [
1502 {
1503 "role": "user",
1504 "content": [
1505 {
1506 "type": "tool_result",
1507 "tool_use_id": "toolu_weather",
1508 "content": json.dumps(_get_weather("San Francisco, CA", "f")),
1509 }
1510 ],
1511 }
1512 ]
1513
1514
1515 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1516 @pytest.mark.respx(base_url=base_url)
1517 def test_tool_removal_in_echoed_compaction_turn_routes_call_down_unknown_tool_path_sync(
1518 respx_mock: MockRouter,
1519 ) -> None:
1520 # The compaction block comes from the server, so the runner holds it as a response model, not a dict.
1521 respx_mock.post("/v1/messages").mock(
1522 side_effect=[
1523 httpx2.Response(
1524 200,
1525 json={
1526 "id": "msg_compaction",
1527 "type": "message",
1528 "role": "assistant",
1529 "model": "claude-haiku-4-5",
1530 "content": [
1531 {
1532 "type": "compaction",
1533 "content": "Earlier turns, summarized.",
1534 "encrypted_content": None,
1535 "tool_changes": [
1536 {"type": "tool_removal", "tool": {"type": "tool_reference", "name": "get_weather"}}
1537 ],
1538 }
1539 ],
1540 "stop_reason": "compaction",
1541 "stop_sequence": None,
1542 "usage": {"input_tokens": 1, "output_tokens": 1},
1543 },
1544 ),
1545 _tool_use_response("get_weather", "toolu_change"),
1546 _end_turn_response(),
1547 ]
1548 )
1549
1550 weather_called = False
1551
1552 @beta_tool
1553 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1554 """Lookup the weather for a given city."""
1555 nonlocal weather_called
1556 weather_called = True
1557 return json.dumps(_get_weather(location, units))
1558
1559 with Anthropic(
1560 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1561 ) as client:
1562 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1563 results = _run_sync_tool_use(
1564 client,
1565 tools=[get_weather],
1566 messages=[{"role": "user", "content": "What is the weather in SF?"}],
1567 )
1568
1569 assert weather_called is False
1570 assert results == [_not_found_result("toolu_change")]
1571 echoed = _sent_request_bodies(respx_mock)[1]["messages"][1]
1572 assert echoed["content"][0]["tool_changes"] == [
1573 {"type": "tool_removal", "tool": {"type": "tool_reference", "name": "get_weather"}}
1574 ]
1575
1576
1577 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1578 @pytest.mark.respx(base_url=base_url)
1579 def test_tool_removal_in_compaction_tool_changes_routes_call_down_unknown_tool_path_sync(
1580 respx_mock: MockRouter,
1581 ) -> None:
1582 respx_mock.post("/v1/messages").mock(
1583 side_effect=[
1584 _tool_use_response("get_weather", "toolu_change"),
1585 _end_turn_response(),
1586 ]
1587 )
1588
1589 weather_called = False
1590
1591 @beta_tool
1592 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
1593 """Lookup the weather for a given city."""
1594 nonlocal weather_called
1595 weather_called = True
1596 return json.dumps(_get_weather(location, units))
1597
1598 with Anthropic(
1599 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
1600 ) as client:
1601 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1602 results = _run_sync_tool_use(
1603 client,
1604 tools=[get_weather],
1605 messages=[
1606 {
1607 "role": "assistant",
1608 "content": [
1609 {
1610 "type": "compaction",
1611 "content": "Earlier turns, summarized.",
1612 "tool_changes": [
1613 {"type": "tool_removal", "tool": {"type": "tool_reference", "name": "get_weather"}}
1614 ],
1615 }
1616 ],
1617 },
1618 {"role": "user", "content": "What is the weather in SF?"},
1619 ],
1620 )
1621
1622 assert weather_called is False
1623 assert results == [_not_found_result("toolu_change")]
1624
1625
1626 _ToolChangeScript = dict[str, Callable[[Any], None]]
1627 """What to do with the runner while handling the message with a given id."""
1628
1629 _WEB_SEARCH: BetaWebSearchTool20250305Param = {"type": "web_search_20250305", "name": "web_search", "max_uses": 3}
1630
1631 _sync_and_async = pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
1632
1633
1634 def _recording_tool(sync: bool, name: str, calls: list[str], label: str | None = None) -> Any:
1635 """A tool taking no input that appends `label` (its name by default) to `calls` when it runs."""
1636 label = label or name
1637
1638 def run() -> BetaFunctionToolResultType:
1639 calls.append(label)
1640 return f"{label} ran"
1641
1642 async def run_async() -> BetaFunctionToolResultType:
1643 return run()
1644
1645 if sync:
1646 return beta_tool(run, name=name, description=f"Run {name}.")
1647 return beta_async_tool(run_async, name=name, description=f"Run {name}.")
1648
1649
1650 def _calls_tool(name: str, tool_use_id: str) -> httpx2.Response:
1651 return _tool_use_response(name, tool_use_id, input={})
1652
1653
1654 def _ran_result(tool_use_id: str, label: str) -> BetaMessageParam:
1655 return {"role": "user", "content": [{"type": "tool_result", "tool_use_id": tool_use_id, "content": f"{label} ran"}]}
1656
1657
1658 def _tool_changes_message(*blocks: Any) -> BetaMessageParam:
1659 return {"role": "system", "content": list(blocks)}
1660
1661
1662 def _addition(definition: Any) -> BetaContentBlockParam:
1663 return {"type": "tool_addition", "tool": {"type": "tool_definition", "definition": definition}}
1664
1665
1666 async def _run_with_tool_changes(
1667 client: Anthropic | AsyncAnthropic,
1668 *,
1669 tools: list[Any],
1670 script: _ToolChangeScript,
1671 before_first_request: Callable[[Any], None] | None = None,
1672 max_iterations: int | Omit = omit,
1673 messages: list[BetaMessageParam] | None = None,
1674 stream: bool = False,
1675 ) -> None:
1676 """Drive a tool runner to the end, running `script[message.id]` while each message is being handled."""
1677 runner: Any = client.beta.messages.tool_runner(
1678 max_tokens=1024,
1679 model="claude-haiku-4-5",
1680 tools=tools,
1681 messages=messages or [{"role": "user", "content": "What time is it, and what is the weather in SF?"}],
1682 max_iterations=max_iterations,
1683 stream=stream,
1684 )
1685 if before_first_request is not None:
1686 before_first_request(runner)
1687 if isinstance(client, Anthropic):
1688 for item in runner:
1689 message = item.get_final_message() if stream else item
1690 script.get(message.id, _leave_tools_alone)(runner)
1691 else:
1692 async for item in runner:
1693 message = await item.get_final_message() if stream else item
1694 script.get(message.id, _leave_tools_alone)(runner)
1695
1696
1697 def _leave_tools_alone(runner: Any) -> None:
1698 pass
1699
1700
1701 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1702 @_sync_and_async
1703 @pytest.mark.respx(base_url=base_url)
1704 async def test_add_tools_sends_the_definition_with_the_next_request(
1705 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1706 ) -> None:
1707 respx_mock.post("/v1/messages").mock(
1708 side_effect=[
1709 _calls_tool("get_time", "toolu_time"),
1710 _calls_tool("get_weather", "toolu_weather"),
1711 _end_turn_response(),
1712 ]
1713 )
1714 calls: list[str] = []
1715 get_time = _recording_tool(sync, "get_time", calls)
1716 get_weather = _recording_tool(sync, "get_weather", calls)
1717
1718 await _run_with_tool_changes(
1719 client if sync else async_client,
1720 tools=[get_time],
1721 script={"msg_toolu_time": lambda runner: runner.add_tools(get_weather)},
1722 )
1723
1724 assert calls == ["get_time", "get_weather"]
1725 requests = _sent_request_bodies(respx_mock)
1726 assert [request["tools"] for request in requests] == [[get_time.to_dict()]] * 3
1727 assert requests[1]["messages"][-2:] == [
1728 _ran_result("toolu_time", "get_time"),
1729 _tool_changes_message(_addition(get_weather.to_dict())),
1730 ]
1731 assert requests[2]["messages"][-1] == _ran_result("toolu_weather", "get_weather")
1732 betas = [call.request.headers.get("anthropic-beta", "") for call in cast("list[Any]", respx_mock.calls)]
1733 assert all("inline-tools-2026-09-15" not in header for header in betas)
1734
1735
1736 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1737 @_sync_and_async
1738 @pytest.mark.respx(base_url=base_url)
1739 async def test_tool_changes_made_before_the_first_request_follow_a_trailing_assistant_message(
1740 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1741 ) -> None:
1742 respx_mock.post("/v1/messages").mock(
1743 side_effect=[_calls_tool("get_weather", "toolu_weather"), _end_turn_response()]
1744 )
1745 calls: list[str] = []
1746 get_weather = _recording_tool(sync, "get_weather", calls)
1747
1748 await _run_with_tool_changes(
1749 client if sync else async_client,
1750 tools=[],
1751 script={},
1752 messages=[cast(BetaMessageParam, _COMPACTION_ASSISTANT_TURN)],
1753 before_first_request=lambda runner: runner.add_tools(get_weather),
1754 )
1755
1756 assert calls == ["get_weather"]
1757 assert _sent_request_bodies(respx_mock)[0]["messages"] == [
1758 _COMPACTION_ASSISTANT_TURN,
1759 _tool_changes_message(_addition(get_weather.to_dict())),
1760 ]
1761
1762
1763 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1764 @pytest.mark.parametrize("remove_by", ["tool", "name"])
1765 @_sync_and_async
1766 @pytest.mark.respx(base_url=base_url)
1767 async def test_remove_tools_stops_a_call_already_in_the_turn(
1768 sync: bool, remove_by: str, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1769 ) -> None:
1770 respx_mock.post("/v1/messages").mock(
1771 side_effect=[_calls_tool("get_weather", "toolu_weather"), _end_turn_response()]
1772 )
1773 calls: list[str] = []
1774 get_weather = _recording_tool(sync, "get_weather", calls)
1775 removed = get_weather if remove_by == "tool" else "get_weather"
1776
1777 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1778 await _run_with_tool_changes(
1779 client if sync else async_client,
1780 tools=[get_weather],
1781 script={"msg_toolu_weather": lambda runner: runner.remove_tools(removed)},
1782 )
1783
1784 assert calls == []
1785 requests = _sent_request_bodies(respx_mock)
1786 assert [request["tools"] for request in requests] == [[get_weather.to_dict()]] * 2
1787 assert requests[1]["messages"][-2:] == [
1788 _not_found_result("toolu_weather"),
1789 _tool_changes_message(_tool_reference_block("tool_removal", "get_weather")),
1790 ]
1791
1792
1793 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1794 @pytest.mark.parametrize("removed", ["starting_tool", "tool_added_in_the_same_turn"])
1795 @_sync_and_async
1796 @pytest.mark.respx(base_url=base_url)
1797 async def test_a_removed_tool_stays_removed_when_its_removal_block_leaves_the_history(
1798 sync: bool, removed: str, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1799 ) -> None:
1800 respx_mock.post("/v1/messages").mock(
1801 side_effect=[
1802 _calls_tool("get_time", "toolu_time"),
1803 _calls_tool("get_time", "toolu_time_again"),
1804 _calls_tool("get_weather", "toolu_weather"),
1805 _end_turn_response(),
1806 ]
1807 )
1808 calls: list[str] = []
1809 get_time = _recording_tool(sync, "get_time", calls)
1810 get_weather = _recording_tool(sync, "get_weather", calls)
1811
1812 def remove_weather(runner: Any) -> None:
1813 if removed == "tool_added_in_the_same_turn":
1814 runner.add_tools(get_weather)
1815 runner.remove_tools(get_weather)
1816
1817 def keep_first_message(params: Any) -> Any:
1818 return {**params, "messages": list(params["messages"])[:1]}
1819
1820 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1821 await _run_with_tool_changes(
1822 client if sync else async_client,
1823 tools=[get_weather, get_time] if removed == "starting_tool" else [get_time],
1824 script={
1825 "msg_toolu_time": remove_weather,
1826 "msg_toolu_time_again": lambda runner: runner.set_messages_params(keep_first_message),
1827 },
1828 )
1829
1830 assert calls == ["get_time", "get_time"]
1831 requests = _sent_request_bodies(respx_mock)
1832 # Nothing left in the conversation removes get_weather.
1833 assert [message["role"] for message in requests[2]["messages"]] == ["user", "assistant", "user"]
1834 assert requests[3]["messages"][-1] == _not_found_result("toolu_weather")
1835
1836
1837 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1838 @pytest.mark.parametrize("order", ["add_then_remove", "remove_then_add"])
1839 @_sync_and_async
1840 @pytest.mark.respx(base_url=base_url)
1841 async def test_tool_changes_in_one_turn_are_sent_together_in_call_order(
1842 sync: bool, order: str, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1843 ) -> None:
1844 respx_mock.post("/v1/messages").mock(
1845 side_effect=[
1846 _calls_tool("get_time", "toolu_time"),
1847 _calls_tool("get_weather", "toolu_weather"),
1848 _end_turn_response(),
1849 ]
1850 )
1851 calls: list[str] = []
1852 get_time = _recording_tool(sync, "get_time", calls)
1853 get_weather = _recording_tool(sync, "get_weather", calls)
1854 addition = _addition(get_weather.to_dict())
1855 removal = _tool_reference_block("tool_removal", "get_weather")
1856
1857 def add_then_remove(runner: Any) -> None:
1858 runner.add_tools(get_weather)
1859 runner.remove_tools(get_weather)
1860
1861 def remove_then_add(runner: Any) -> None:
1862 runner.remove_tools(get_weather)
1863 runner.add_tools(get_weather)
1864
1865 if order == "add_then_remove":
1866 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
1867 await _run_with_tool_changes(
1868 client if sync else async_client, tools=[get_time], script={"msg_toolu_time": add_then_remove}
1869 )
1870 expected_changes, expected_calls = [addition, removal], ["get_time"]
1871 else:
1872 await _run_with_tool_changes(
1873 client if sync else async_client, tools=[get_weather, get_time], script={"msg_toolu_time": remove_then_add}
1874 )
1875 expected_changes, expected_calls = [removal, addition], ["get_time", "get_weather"]
1876
1877 assert calls == expected_calls
1878 assert _sent_request_bodies(respx_mock)[1]["messages"][-2:] == [
1879 _ran_result("toolu_time", "get_time"),
1880 _tool_changes_message(*expected_changes),
1881 ]
1882
1883
1884 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1885 @_sync_and_async
1886 @pytest.mark.respx(base_url=base_url)
1887 async def test_add_tools_replaces_a_tool_of_the_same_name_straight_away(
1888 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1889 ) -> None:
1890 respx_mock.post("/v1/messages").mock(
1891 side_effect=[
1892 _calls_tool("get_weather", "toolu_weather"),
1893 _calls_tool("get_weather", "toolu_weather_again"),
1894 _end_turn_response(),
1895 ]
1896 )
1897 calls: list[str] = []
1898 old_get_weather = _recording_tool(sync, "get_weather", calls, label="old get_weather")
1899 new_get_weather = _recording_tool(sync, "get_weather", calls, label="new get_weather")
1900
1901 await _run_with_tool_changes(
1902 client if sync else async_client,
1903 tools=[old_get_weather],
1904 script={"msg_toolu_weather": lambda runner: runner.add_tools(new_get_weather)},
1905 )
1906
1907 # Even the call the model made before the swap ran the new function.
1908 assert calls == ["new get_weather", "new get_weather"]
1909
1910
1911 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1912 @_sync_and_async
1913 @pytest.mark.respx(base_url=base_url)
1914 async def test_a_call_already_in_the_turn_gets_the_input_error_of_the_tool_added_under_its_name(
1915 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1916 ) -> None:
1917 respx_mock.post("/v1/messages").mock(
1918 side_effect=[_calls_tool("get_weather", "toolu_weather"), _end_turn_response()]
1919 )
1920 calls: list[str] = []
1921 old_get_weather = _recording_tool(sync, "get_weather", calls)
1922
1923 def get_weather(city: str) -> str:
1924 calls.append(city)
1925 return f"Raining in {city}"
1926
1927 async def get_weather_async(city: str) -> str:
1928 return get_weather(city)
1929
1930 description = "Lookup the weather for a given city."
1931 new_get_weather: Any = (
1932 beta_tool(get_weather, description=description)
1933 if sync
1934 else beta_async_tool(get_weather_async, name="get_weather", description=description)
1935 )
1936
1937 await _run_with_tool_changes(
1938 client if sync else async_client,
1939 tools=[old_get_weather],
1940 script={"msg_toolu_weather": lambda runner: runner.add_tools(new_get_weather)},
1941 )
1942
1943 assert calls == []
1944 assert _sent_request_bodies(respx_mock)[1]["messages"][-2:] == [
1945 {
1946 "role": "user",
1947 "content": [
1948 {
1949 "type": "tool_result",
1950 "tool_use_id": "toolu_weather",
1951 "content": "ValueError('Invalid arguments for function get_weather')",
1952 "is_error": True,
1953 }
1954 ],
1955 },
1956 _tool_changes_message(_addition(new_get_weather.to_dict())),
1957 ]
1958
1959
1960 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1961 @_sync_and_async
1962 @pytest.mark.respx(base_url=base_url)
1963 async def test_a_removed_tool_added_back_while_handling_a_call_to_it_is_run(
1964 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
1965 ) -> None:
1966 respx_mock.post("/v1/messages").mock(
1967 side_effect=[
1968 _calls_tool("get_time", "toolu_time"),
1969 _calls_tool("get_weather", "toolu_weather"),
1970 _end_turn_response(),
1971 ]
1972 )
1973 calls: list[str] = []
1974 get_time = _recording_tool(sync, "get_time", calls)
1975 get_weather = _recording_tool(sync, "get_weather", calls)
1976
1977 await _run_with_tool_changes(
1978 client if sync else async_client,
1979 tools=[get_time, get_weather],
1980 script={
1981 "msg_toolu_time": lambda runner: runner.remove_tools(get_weather),
1982 "msg_toolu_weather": lambda runner: runner.add_tools(get_weather),
1983 },
1984 )
1985
1986 assert calls == ["get_time", "get_weather"]
1987 requests = _sent_request_bodies(respx_mock)
1988 # The removal is in the history when the model calls the tool anyway.
1989 assert requests[1]["messages"][-1] == _tool_changes_message(_tool_reference_block("tool_removal", "get_weather"))
1990 assert requests[2]["messages"][-2:] == [
1991 _ran_result("toolu_weather", "get_weather"),
1992 _tool_changes_message(_addition(get_weather.to_dict())),
1993 ]
1994
1995
1996 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
1997 @_sync_and_async
1998 @pytest.mark.respx(base_url=base_url)
1999 async def test_a_raw_definition_is_sent_as_given_and_never_run(
2000 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2001 ) -> None:
2002 respx_mock.post("/v1/messages").mock(
2003 side_effect=[
2004 _calls_tool("get_time", "toolu_time"),
2005 _calls_tool("get_weather", "toolu_weather"),
2006 _end_turn_response(),
2007 ]
2008 )
2009 calls: list[str] = []
2010 get_time = _recording_tool(sync, "get_time", calls)
2011 get_weather = _recording_tool(sync, "get_weather", calls)
2012 web_search = copy(_WEB_SEARCH)
2013 raw_get_weather: BetaToolParam = {
2014 "name": "get_weather",
2015 "description": "Lookup the weather for a given city.",
2016 "input_schema": {"type": "object", "properties": {}},
2017 }
2018
2019 def add_raw_definitions(runner: Any) -> None:
2020 runner.add_tools(web_search, raw_get_weather)
2021 # The runner keeps its own copy, so a later edit doesn't change what is sent.
2022 web_search["max_uses"] = 10
2023
2024 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
2025 await _run_with_tool_changes(
2026 client if sync else async_client,
2027 tools=[get_time, get_weather],
2028 script={"msg_toolu_time": add_raw_definitions},
2029 )
2030
2031 # The raw definition took over the name of the function tool, so the function is not run.
2032 assert calls == ["get_time"]
2033 requests = _sent_request_bodies(respx_mock)
2034 assert requests[1]["messages"][-1] == _tool_changes_message(_addition(_WEB_SEARCH), _addition(raw_get_weather))
2035 assert requests[2]["messages"][-1] == _not_found_result("toolu_weather")
2036
2037
2038 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2039 @_sync_and_async
2040 @pytest.mark.respx(base_url=base_url)
2041 async def test_tool_changes_made_during_a_paused_turn_are_sent_one_request_later(
2042 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2043 ) -> None:
2044 respx_mock.post("/v1/messages").mock(
2045 side_effect=[
2046 _paused_server_tool_use(),
2047 _calls_tool("get_weather", "toolu_weather"),
2048 _calls_tool("get_time", "toolu_time"),
2049 _end_turn_response(),
2050 ]
2051 )
2052 calls: list[str] = []
2053 get_time = _recording_tool(sync, "get_time", calls)
2054 get_weather = _recording_tool(sync, "get_weather", calls)
2055
2056 def swap_tools(runner: Any) -> None:
2057 runner.remove_tools(get_weather)
2058 runner.add_tools(get_time)
2059
2060 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
2061 await _run_with_tool_changes(
2062 client if sync else async_client, tools=[get_weather, _WEB_SEARCH], script={"msg_paused": swap_tools}
2063 )
2064
2065 assert calls == ["get_time"]
2066 requests = _sent_request_bodies(respx_mock)
2067 # The paused turn is sent back as it came; it has to stay last to be continued.
2068 assert requests[1]["messages"][1:] == [_PAUSED_ASSISTANT_TURN]
2069 assert requests[2]["messages"][-2:] == [
2070 _not_found_result("toolu_weather"),
2071 _tool_changes_message(_tool_reference_block("tool_removal", "get_weather"), _addition(get_time.to_dict())),
2072 ]
2073
2074
2075 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2076 @_sync_and_async
2077 @pytest.mark.respx(base_url=base_url)
2078 async def test_tool_changes_go_out_with_the_compaction_request_and_follow_its_response(
2079 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2080 ) -> None:
2081 respx_mock.post("/v1/messages").mock(
2082 side_effect=[
2083 _calls_tool("get_time", "toolu_time"),
2084 _compacted_response(),
2085 _calls_tool("get_forecast", "toolu_forecast"),
2086 _calls_tool("get_weather", "toolu_weather"),
2087 _end_turn_response(),
2088 ]
2089 )
2090 calls: list[str] = []
2091 get_time = _recording_tool(sync, "get_time", calls)
2092 get_weather = _recording_tool(sync, "get_weather", calls)
2093 get_forecast = _recording_tool(sync, "get_forecast", calls)
2094
2095 def add_weather_and_compact(runner: Any) -> None:
2096 runner.add_tools(get_weather)
2097 runner.compact_before_next_turn()
2098
2099 await _run_with_tool_changes(
2100 client if sync else async_client,
2101 tools=[get_time],
2102 script={
2103 "msg_toolu_time": add_weather_and_compact,
2104 "msg_compacted": lambda runner: runner.add_tools(get_forecast),
2105 },
2106 )
2107
2108 # A tool added before the compaction is still run after it.
2109 assert calls == ["get_time", "get_forecast", "get_weather"]
2110 _, compaction, after, _, _ = _sent_request_bodies(respx_mock)
2111 assert compaction["compaction"] == {"type": "summarize"}
2112 assert compaction["messages"][-2:] == [
2113 _ran_result("toolu_time", "get_time"),
2114 _tool_changes_message(_addition(get_weather.to_dict())),
2115 ]
2116 assert after["messages"] == [*_compaction_block_alone(), _tool_changes_message(_addition(get_forecast.to_dict()))]
2117
2118
2119 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2120 @_sync_and_async
2121 @pytest.mark.respx(base_url=base_url)
2122 async def test_a_removed_tool_added_back_while_handling_the_compaction_response_is_run(
2123 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2124 ) -> None:
2125 respx_mock.post("/v1/messages").mock(
2126 side_effect=[
2127 _calls_tool("get_time", "toolu_time"),
2128 _compacted_response(),
2129 _calls_tool("get_weather", "toolu_weather"),
2130 _end_turn_response(),
2131 ]
2132 )
2133 calls: list[str] = []
2134 get_time = _recording_tool(sync, "get_time", calls)
2135 get_weather = _recording_tool(sync, "get_weather", calls)
2136
2137 def remove_weather_and_compact(runner: Any) -> None:
2138 runner.remove_tools(get_weather)
2139 runner.compact_before_next_turn()
2140
2141 await _run_with_tool_changes(
2142 client if sync else async_client,
2143 tools=[get_time, get_weather],
2144 script={
2145 "msg_toolu_time": remove_weather_and_compact,
2146 "msg_compacted": lambda runner: runner.add_tools(get_weather),
2147 },
2148 )
2149
2150 assert calls == ["get_time", "get_weather"]
2151 _, compaction, after, _ = _sent_request_bodies(respx_mock)
2152 assert compaction["messages"][-1] == _tool_changes_message(_tool_reference_block("tool_removal", "get_weather"))
2153 assert after["messages"] == [*_compaction_block_alone(), _tool_changes_message(_addition(get_weather.to_dict()))]
2154
2155
2156 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2157 @pytest.mark.parametrize("ended_by", ["end_turn", "max_iterations"])
2158 @_sync_and_async
2159 @pytest.mark.respx(base_url=base_url)
2160 async def test_tool_changes_pending_when_the_run_ends_are_not_sent(
2161 sync: bool, ended_by: str, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2162 ) -> None:
2163 calls: list[str] = []
2164 get_time = _recording_tool(sync, "get_time", calls)
2165 get_weather = _recording_tool(sync, "get_weather", calls)
2166
2167 def swap_tools(runner: Any) -> None:
2168 runner.add_tools(get_time)
2169 runner.remove_tools(get_weather)
2170
2171 if ended_by == "end_turn":
2172 respx_mock.post("/v1/messages").mock(side_effect=[_end_turn_response()])
2173 await _run_with_tool_changes(
2174 client if sync else async_client, tools=[get_weather], script={"msg_end_turn": swap_tools}
2175 )
2176 else:
2177 respx_mock.post("/v1/messages").mock(side_effect=[_calls_tool("get_weather", "toolu_weather")])
2178 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
2179 await _run_with_tool_changes(
2180 client if sync else async_client,
2181 tools=[get_weather],
2182 script={"msg_toolu_weather": swap_tools},
2183 max_iterations=1,
2184 )
2185
2186 assert calls == []
2187 assert len(_sent_request_bodies(respx_mock)) == 1
2188
2189
2190 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2191 @_sync_and_async
2192 @pytest.mark.respx(base_url=base_url)
2193 async def test_tool_changes_when_streaming(
2194 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
2195 ) -> None:
2196 respx_mock.post("/v1/messages").mock(
2197 side_effect=[
2198 _sse_message(
2199 {"type": "tool_use", "id": "toolu_time", "name": "get_time", "input": {}},
2200 "tool_use",
2201 {"type": "input_json_delta", "partial_json": "{}"},
2202 ),
2203 _sse_message({"type": "text", "text": ""}, "end_turn", {"type": "text_delta", "text": "Done."}),
2204 ]
2205 )
2206 calls: list[str] = []
2207 get_time = _recording_tool(sync, "get_time", calls)
2208 get_weather = _recording_tool(sync, "get_weather", calls)
2209
2210 await _run_with_tool_changes(
2211 client if sync else async_client,
2212 tools=[get_time],
2213 # Every streamed message has this id, so the final turn adds the tool again; that change is never sent.
2214 script={"msg_streamed": lambda runner: runner.add_tools(get_weather)},
2215 stream=True,
2216 )
2217
2218 assert calls == ["get_time"]
2219 requests = _sent_request_bodies(respx_mock)
2220 assert [request["stream"] for request in requests] == [True] * 2
2221 assert requests[1]["messages"][-2:] == [
2222 _ran_result("toolu_time", "get_time"),
2223 _tool_changes_message(_addition(get_weather.to_dict())),
2224 ]
2225
2226
2227 def _get_weather(location: str, units: Literal["c", "f"]) -> Dict[str, Any]:
2228 # Simulate a weather API call
2229 print(f"Fetching weather for {location} in {units}")
2230
2231 if units == "c":
2232 return {
2233 "location": location,
2234 "temperature": "20°C",
2235 "condition": "Sunny",
2236 }
2237 else:
2238 return {
2239 "location": location,
2240 "temperature": "68°F",
2241 "condition": "Sunny",
2242 }
2243
2244
2245 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
2246 def test_tool_runner_method_in_sync(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
2247 checking_client: "Anthropic | AsyncAnthropic" = client if sync else async_client
2248
2249 assert_signatures_in_sync(
2250 checking_client.beta.messages.create,
2251 checking_client.beta.messages.tool_runner,
2252 exclude_params={
2253 "tools",
2254 "output_format",
2255 # TODO
2256 "stream",
2257 # a tool runner can't take it: every request of the loop would compact again
2258 "compaction",
2259 },
2260 )
2261
2262
2263 def _sent_request_bodies(respx_mock: MockRouter) -> List[Any]:
2264 return [json.loads(call.request.content) for call in cast("List[Any]", respx_mock.calls)]
2265
2266
2267 def _compacted_response() -> httpx2.Response:
2268 return httpx2.Response(
2269 200,
2270 json={
2271 "id": "msg_compacted",
2272 "type": "message",
2273 "role": "assistant",
2274 "model": "claude-haiku-4-5",
2275 "content": [{"type": "compaction", "content": "Summary so far.", "signature": "sig_01"}],
2276 "stop_reason": "compaction",
2277 "stop_sequence": None,
2278 "usage": {"input_tokens": 1, "output_tokens": 1},
2279 },
2280 )
2281
2282
2283 def _compaction_block_alone() -> List[Any]:
2284 return [
2285 {"role": "assistant", "content": [{"type": "compaction", "content": "Summary so far.", "signature": "sig_01"}]}
2286 ]
2287
2288
2289 _COMPACTION_RESPONSE_CONTENT_WITH_AN_UNMODELLED_BLOCK: List[Dict[str, Any]] = [
2290 {"type": "compaction", "content": "Summary so far.", "signature": "sig_01"},
2291 {"type": "mcp_tool_listing", "mcp_server_name": "docs", "tools": []},
2292 ]
2293
2294
2295 def _compacted_response_with_an_unmodelled_block() -> httpx2.Response:
2296 body = _compacted_response().json()
2297 body["content"] = _COMPACTION_RESPONSE_CONTENT_WITH_AN_UNMODELLED_BLOCK
2298 return httpx2.Response(200, json=body)
2299
2300
2301 _FINAL_ASSISTANT_TURN = {"role": "assistant", "content": [{"type": "text", "text": "Done."}]}
2302
2303
2304 def _response_without_a_summary(content: List[Any], stop_reason: str) -> httpx2.Response:
2305 body = _compacted_response().json()
2306 return httpx2.Response(200, json={**body, "content": content, "stop_reason": stop_reason})
2307
2308
2309 def _sync_weather_tool() -> BetaFunctionTool[Any]:
2310 @beta_tool
2311 def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
2312 """Lookup the weather for a given city."""
2313 return json.dumps(_get_weather(location, units))
2314
2315 return get_weather
2316
2317
2318 def _async_weather_tool() -> BetaAsyncFunctionTool[Any]:
2319 @beta_async_tool
2320 async def get_weather(location: str, units: Literal["c", "f"]) -> BetaFunctionToolResultType:
2321 """Lookup the weather for a given city."""
2322 return json.dumps(_get_weather(location, units))
2323
2324 return get_weather
2325
2326
2327 def _sync_compact_runner(
2328 client: Anthropic,
2329 *,
2330 betas: Union[List[AnthropicBetaParam], Omit] = omit,
2331 context_management: Union[BetaContextManagementConfigParam, Omit] = omit,
2332 max_iterations: Union[int, Omit] = omit,
2333 ) -> BetaToolRunner[None]:
2334 return client.beta.messages.tool_runner(
2335 max_tokens=1024,
2336 model="claude-haiku-4-5",
2337 tools=[_sync_weather_tool()],
2338 messages=[{"role": "user", "content": "What is the weather in SF?"}],
2339 betas=betas,
2340 context_management=context_management,
2341 max_iterations=max_iterations,
2342 )
2343
2344
2345 def _async_compact_runner(
2346 client: AsyncAnthropic,
2347 *,
2348 context_management: Union[BetaContextManagementConfigParam, Omit] = omit,
2349 max_iterations: Union[int, Omit] = omit,
2350 ) -> BetaAsyncToolRunner[None]:
2351 return client.beta.messages.tool_runner(
2352 max_tokens=1024,
2353 model="claude-haiku-4-5",
2354 tools=[_async_weather_tool()],
2355 messages=[{"role": "user", "content": "What is the weather in SF?"}],
2356 context_management=context_management,
2357 max_iterations=max_iterations,
2358 )
2359
2360
2361 def _current_messages(runner: Union[BetaToolRunner[None], BetaAsyncToolRunner[None]]) -> List[Any]:
2362 seen: List[Any] = []
2363
2364 def read(params: Any) -> Any:
2365 seen.append(params["messages"])
2366 return params
2367
2368 runner.set_messages_params(read)
2369 return [
2370 message
2371 if isinstance(message["content"], str)
2372 else {**message, "content": [block.to_dict() for block in message["content"]]}
2373 for message in seen[0]
2374 ]
2375
2376
2377 # `parse()` serializes the response it was given, and pydantic warns about a block type it doesn't know.
2378 @pytest.mark.filterwarnings("ignore:Pydantic serializer warnings:UserWarning")
2379 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2380 @pytest.mark.respx(base_url=base_url)
2381 def test_compact_before_next_turn_is_sent_after_the_tools_run_sync(respx_mock: MockRouter) -> None:
2382 respx_mock.post("/v1/messages").mock(
2383 side_effect=[
2384 _tool_use_response("get_weather", "toolu_1"),
2385 _compacted_response_with_an_unmodelled_block(),
2386 _end_turn_response(),
2387 ]
2388 )
2389
2390 # Strict response validation would reject the block type this SDK version doesn't model.
2391 with Anthropic(base_url=base_url, api_key="my-anthropic-api-key", max_retries=0) as client:
2392 runner = _sync_compact_runner(
2393 client,
2394 betas=["compact-2026-09-04"],
2395 context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
2396 # The compaction request is not a model turn, so both real turns still fit.
2397 max_iterations=2,
2398 )
2399 yielded: List[Any] = []
2400 for message in runner:
2401 yielded.append(message)
2402 if message.stop_reason == "tool_use":
2403 runner.compact_before_next_turn({"type": "summarize", "instructions": "Keep the city."})
2404
2405 assert [message.stop_reason for message in yielded] == ["tool_use", "compaction", "end_turn"]
2406 assert yielded[1].content[0].content == "Summary so far."
2407
2408 first, compaction, after = _sent_request_bodies(respx_mock)
2409 assert compaction["compaction"] == {"type": "summarize", "instructions": "Keep the city."}
2410 assert "context_management" not in compaction
2411 assert compaction["messages"] == [
2412 {"role": "user", "content": "What is the weather in SF?"},
2413 {
2414 "role": "assistant",
2415 "content": [
2416 {
2417 "type": "tool_use",
2418 "id": "toolu_1",
2419 "name": "get_weather",
2420 "input": {"location": "San Francisco, CA", "units": "f"},
2421 }
2422 ],
2423 },
2424 {
2425 "role": "user",
2426 "content": [
2427 {
2428 "type": "tool_result",
2429 "tool_use_id": "toolu_1",
2430 "content": json.dumps(_get_weather("San Francisco, CA", "f")),
2431 }
2432 ],
2433 },
2434 ]
2435
2436 # The response goes back as it came, blocks this SDK version doesn't model included.
2437 assert after["messages"] == [
2438 {"role": "assistant", "content": _COMPACTION_RESPONSE_CONTENT_WITH_AN_UNMODELLED_BLOCK}
2439 ]
2440 assert "compaction" not in after
2441 assert after["context_management"] == first["context_management"]
2442 # The beta is the caller's to pass; the runner sends what it was given and nothing more.
2443 assert [call.request.headers.get("anthropic-beta") for call in cast("List[Any]", respx_mock.calls)] == [
2444 "compact-2026-09-04"
2445 ] * 3
2446
2447
2448 @pytest.mark.filterwarnings("ignore:Pydantic serializer warnings:UserWarning")
2449 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2450 @pytest.mark.respx(base_url=base_url)
2451 async def test_compact_before_next_turn_is_sent_after_the_tools_run_async(respx_mock: MockRouter) -> None:
2452 respx_mock.post("/v1/messages").mock(
2453 side_effect=[
2454 _tool_use_response("get_weather", "toolu_1"),
2455 _compacted_response_with_an_unmodelled_block(),
2456 _end_turn_response(),
2457 ]
2458 )
2459
2460 async with AsyncAnthropic(base_url=base_url, api_key="my-anthropic-api-key", max_retries=0) as client:
2461 runner = _async_compact_runner(
2462 client,
2463 context_management={"edits": [{"type": "clear_tool_uses_20250919"}]},
2464 max_iterations=2,
2465 )
2466 stop_reasons: List[Any] = []
2467 async for message in runner:
2468 stop_reasons.append(message.stop_reason)
2469 if message.stop_reason == "tool_use":
2470 runner.compact_before_next_turn()
2471
2472 assert stop_reasons == ["tool_use", "compaction", "end_turn"]
2473 first, compaction, after = _sent_request_bodies(respx_mock)
2474 assert compaction["compaction"] == {"type": "summarize"}
2475 assert "context_management" not in compaction
2476 assert [message["role"] for message in compaction["messages"]] == ["user", "assistant", "user"]
2477 assert compaction["messages"][-1]["content"][0]["type"] == "tool_result"
2478 assert after["messages"] == [
2479 {"role": "assistant", "content": _COMPACTION_RESPONSE_CONTENT_WITH_AN_UNMODELLED_BLOCK}
2480 ]
2481 assert "compaction" not in after
2482 assert after["context_management"] == first["context_management"]
2483 assert all(
2484 "compact-2026-09-04" not in call.request.headers.get("anthropic-beta", "")
2485 for call in cast("List[Any]", respx_mock.calls)
2486 )
2487
2488
2489 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2490 @pytest.mark.respx(base_url=base_url)
2491 def test_compact_before_next_turn_on_the_final_turn_is_sent_before_stopping_sync(respx_mock: MockRouter) -> None:
2492 respx_mock.post("/v1/messages").mock(side_effect=[_end_turn_response(), _compacted_response()])
2493
2494 with Anthropic(
2495 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2496 ) as client:
2497 # The final answer is also the last iteration allowed; the compaction still goes out.
2498 runner = _sync_compact_runner(client, max_iterations=1)
2499 stop_reasons: List[Any] = []
2500 for message in runner:
2501 stop_reasons.append(message.stop_reason)
2502 if message.stop_reason == "end_turn":
2503 runner.compact_before_next_turn()
2504
2505 assert stop_reasons == ["end_turn", "compaction"]
2506 _, compaction = _sent_request_bodies(respx_mock)
2507 assert compaction["compaction"] == {"type": "summarize"}
2508 assert compaction["messages"] == [{"role": "user", "content": "What is the weather in SF?"}, _FINAL_ASSISTANT_TURN]
2509 assert _current_messages(runner) == _compaction_block_alone()
2510
2511
2512 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2513 @pytest.mark.respx(base_url=base_url)
2514 async def test_compact_before_next_turn_on_the_final_turn_is_sent_before_stopping_async(
2515 respx_mock: MockRouter,
2516 ) -> None:
2517 respx_mock.post("/v1/messages").mock(side_effect=[_end_turn_response(), _compacted_response()])
2518
2519 async with AsyncAnthropic(
2520 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2521 ) as client:
2522 runner = _async_compact_runner(client, max_iterations=1)
2523 stop_reasons: List[Any] = []
2524 async for message in runner:
2525 stop_reasons.append(message.stop_reason)
2526 if message.stop_reason == "end_turn":
2527 runner.compact_before_next_turn()
2528
2529 assert stop_reasons == ["end_turn", "compaction"]
2530 _, compaction = _sent_request_bodies(respx_mock)
2531 assert compaction["compaction"] == {"type": "summarize"}
2532 assert compaction["messages"] == [{"role": "user", "content": "What is the weather in SF?"}, _FINAL_ASSISTANT_TURN]
2533 assert _current_messages(runner) == _compaction_block_alone()
2534
2535
2536 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2537 @pytest.mark.respx(base_url=base_url)
2538 def test_pending_compaction_is_skipped_on_a_final_turn_with_unrun_tool_calls_sync(
2539 respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
2540 ) -> None:
2541 respx_mock.post("/v1/messages").mock(side_effect=[_max_tokens_with_tool_use()])
2542
2543 with Anthropic(
2544 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2545 ) as client:
2546 runner = _sync_compact_runner(client)
2547 stop_reasons: List[Any] = []
2548 with caplog.at_level(logging.WARNING, logger="anthropic.lib.tools._beta_runner"):
2549 for message in runner:
2550 stop_reasons.append(message.stop_reason)
2551 runner.compact_before_next_turn()
2552
2553 assert stop_reasons == ["max_tokens"]
2554 assert len(respx_mock.calls) == 1
2555 assert _current_messages(runner) == [{"role": "user", "content": "What is the weather in SF?"}]
2556 assert "pending compaction was skipped" in caplog.text
2557
2558
2559 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2560 @pytest.mark.respx(base_url=base_url)
2561 async def test_pending_compaction_is_skipped_on_a_final_turn_with_unrun_tool_calls_async(
2562 respx_mock: MockRouter, caplog: pytest.LogCaptureFixture
2563 ) -> None:
2564 respx_mock.post("/v1/messages").mock(side_effect=[_max_tokens_with_tool_use()])
2565
2566 async with AsyncAnthropic(
2567 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2568 ) as client:
2569 runner = _async_compact_runner(client)
2570 stop_reasons: List[Any] = []
2571 with caplog.at_level(logging.WARNING, logger="anthropic.lib.tools._beta_runner"):
2572 async for message in runner:
2573 stop_reasons.append(message.stop_reason)
2574 runner.compact_before_next_turn()
2575
2576 assert stop_reasons == ["max_tokens"]
2577 assert len(respx_mock.calls) == 1
2578 assert _current_messages(runner) == [{"role": "user", "content": "What is the weather in SF?"}]
2579 assert "pending compaction was skipped" in caplog.text
2580
2581
2582 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2583 @pytest.mark.respx(base_url=base_url)
2584 def test_compact_before_next_turn_waits_out_a_paused_turn_sync(respx_mock: MockRouter) -> None:
2585 respx_mock.post("/v1/messages").mock(
2586 side_effect=[
2587 _paused_server_tool_use(),
2588 _tool_use_response("get_weather", "toolu_1"),
2589 _compacted_response(),
2590 _end_turn_response(),
2591 ]
2592 )
2593
2594 with Anthropic(
2595 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2596 ) as client:
2597 runner = _sync_compact_runner(client)
2598 for message in runner:
2599 if message.stop_reason == "pause_turn":
2600 runner.compact_before_next_turn()
2601
2602 _, resumed, compaction, after = _sent_request_bodies(respx_mock)
2603 assert "compaction" not in resumed
2604 assert resumed["messages"][-1] == _PAUSED_ASSISTANT_TURN
2605 assert compaction["compaction"] == {"type": "summarize"}
2606 assert compaction["messages"][-1]["content"][0]["type"] == "tool_result"
2607 assert after["messages"] == _compaction_block_alone()
2608
2609
2610 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2611 @pytest.mark.respx(base_url=base_url)
2612 async def test_compact_before_next_turn_waits_out_a_paused_turn_async(respx_mock: MockRouter) -> None:
2613 respx_mock.post("/v1/messages").mock(
2614 side_effect=[
2615 _paused_server_tool_use(),
2616 _tool_use_response("get_weather", "toolu_1"),
2617 _compacted_response(),
2618 _end_turn_response(),
2619 ]
2620 )
2621
2622 async with AsyncAnthropic(
2623 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2624 ) as client:
2625 runner = _async_compact_runner(client)
2626 async for message in runner:
2627 if message.stop_reason == "pause_turn":
2628 runner.compact_before_next_turn()
2629
2630 _, resumed, compaction, after = _sent_request_bodies(respx_mock)
2631 assert "compaction" not in resumed
2632 assert resumed["messages"][-1] == _PAUSED_ASSISTANT_TURN
2633 assert compaction["compaction"] == {"type": "summarize"}
2634 assert compaction["messages"][-1]["content"][0]["type"] == "tool_result"
2635 assert after["messages"] == _compaction_block_alone()
2636
2637
2638 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2639 @pytest.mark.respx(base_url=base_url)
2640 def test_compact_before_next_turn_before_the_first_iteration_is_the_first_request_sync(
2641 respx_mock: MockRouter,
2642 ) -> None:
2643 respx_mock.post("/v1/messages").mock(side_effect=[_compacted_response(), _end_turn_response()])
2644
2645 with Anthropic(
2646 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2647 ) as client:
2648 runner = _sync_compact_runner(client)
2649 # An edit made before the compaction request is part of what gets summarized.
2650 runner.append_messages({"role": "user", "content": "And in NYC?"})
2651 runner.compact_before_next_turn()
2652 final = runner.until_done()
2653
2654 assert final.stop_reason == "end_turn"
2655 compaction, after = _sent_request_bodies(respx_mock)
2656 assert compaction["compaction"] == {"type": "summarize"}
2657 assert [message["content"] for message in compaction["messages"]] == ["What is the weather in SF?", "And in NYC?"]
2658 assert after["messages"] == _compaction_block_alone()
2659
2660
2661 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2662 @pytest.mark.respx(base_url=base_url)
2663 async def test_compact_before_next_turn_before_the_first_iteration_is_the_first_request_async(
2664 respx_mock: MockRouter,
2665 ) -> None:
2666 respx_mock.post("/v1/messages").mock(side_effect=[_compacted_response(), _end_turn_response()])
2667
2668 async with AsyncAnthropic(
2669 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2670 ) as client:
2671 runner = _async_compact_runner(client)
2672 runner.append_messages({"role": "user", "content": "And in NYC?"})
2673 runner.compact_before_next_turn()
2674 final = await runner.until_done()
2675
2676 assert final.stop_reason == "end_turn"
2677 compaction, after = _sent_request_bodies(respx_mock)
2678 assert compaction["compaction"] == {"type": "summarize"}
2679 assert [message["content"] for message in compaction["messages"]] == ["What is the weather in SF?", "And in NYC?"]
2680 assert after["messages"] == _compaction_block_alone()
2681
2682
2683 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2684 @pytest.mark.respx(base_url=base_url)
2685 def test_compact_before_next_turn_again_replaces_the_pending_compaction_sync(respx_mock: MockRouter) -> None:
2686 respx_mock.post("/v1/messages").mock(
2687 side_effect=[
2688 _tool_use_response("get_weather", "toolu_1"),
2689 _compacted_response(),
2690 _end_turn_response(),
2691 ]
2692 )
2693
2694 with Anthropic(
2695 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2696 ) as client:
2697 runner = _sync_compact_runner(client)
2698 for message in runner:
2699 if message.stop_reason == "tool_use":
2700 runner.compact_before_next_turn({"type": "summarize", "instructions": "Keep the city."})
2701 runner.compact_before_next_turn({"type": "summarize", "instructions": "Keep the units."})
2702
2703 requests = _sent_request_bodies(respx_mock)
2704 assert [request.get("compaction") for request in requests] == [
2705 None,
2706 {"type": "summarize", "instructions": "Keep the units."},
2707 None,
2708 ]
2709
2710
2711 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2712 @pytest.mark.respx(base_url=base_url)
2713 def test_compact_before_next_turn_on_the_compaction_response_is_ignored_sync(respx_mock: MockRouter) -> None:
2714 # A fourth request would exhaust the mocked responses and fail the test.
2715 respx_mock.post("/v1/messages").mock(
2716 side_effect=[
2717 _tool_use_response("get_weather", "toolu_1"),
2718 _compacted_response(),
2719 _end_turn_response(),
2720 ]
2721 )
2722
2723 with Anthropic(
2724 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2725 ) as client:
2726 edits: List[Any] = []
2727 runner = _sync_compact_runner(client, context_management={"edits": edits})
2728 stop_reasons: List[Any] = []
2729 for message in runner:
2730 stop_reasons.append(message.stop_reason)
2731 if message.stop_reason == "compaction":
2732 # A call that is going to be ignored doesn't raise over a compaction edit either.
2733 edits.append({"type": "compact_20260112"})
2734 if message.stop_reason != "end_turn":
2735 runner.compact_before_next_turn()
2736
2737 assert stop_reasons == ["tool_use", "compaction", "end_turn"]
2738 assert [request.get("compaction") for request in _sent_request_bodies(respx_mock)] == [
2739 None,
2740 {"type": "summarize"},
2741 None,
2742 ]
2743
2744
2745 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2746 @pytest.mark.respx(base_url=base_url)
2747 def test_a_tool_removed_in_the_history_stays_removed_after_compaction_sync(respx_mock: MockRouter) -> None:
2748 respx_mock.post("/v1/messages").mock(
2749 side_effect=[
2750 _compacted_response(),
2751 _tool_use_response("get_weather", "toolu_1", input={}),
2752 _end_turn_response(),
2753 ]
2754 )
2755 calls: List[str] = []
2756
2757 @beta_tool
2758 def get_weather() -> BetaFunctionToolResultType:
2759 """Lookup the weather."""
2760 calls.append("get_weather")
2761 return "sunny"
2762
2763 with Anthropic(
2764 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2765 ) as client:
2766 runner = client.beta.messages.tool_runner(
2767 max_tokens=1024,
2768 model="claude-haiku-4-5",
2769 tools=[get_weather],
2770 messages=[{"role": "user", "content": "What is the weather in SF?"}],
2771 )
2772 runner.append_messages({"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]})
2773 runner.compact_before_next_turn()
2774 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
2775 runner.until_done()
2776
2777 assert calls == []
2778 assert _sent_request_bodies(respx_mock)[2]["messages"][-1] == _not_found_result("toolu_1")
2779
2780
2781 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2782 @pytest.mark.respx(base_url=base_url)
2783 async def test_a_tool_removed_in_the_history_stays_removed_after_compaction_async(respx_mock: MockRouter) -> None:
2784 respx_mock.post("/v1/messages").mock(
2785 side_effect=[
2786 _compacted_response(),
2787 _tool_use_response("get_weather", "toolu_1", input={}),
2788 _end_turn_response(),
2789 ]
2790 )
2791 calls: List[str] = []
2792
2793 @beta_async_tool
2794 async def get_weather() -> BetaFunctionToolResultType:
2795 """Lookup the weather."""
2796 calls.append("get_weather")
2797 return "sunny"
2798
2799 async with AsyncAnthropic(
2800 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2801 ) as client:
2802 runner = client.beta.messages.tool_runner(
2803 max_tokens=1024,
2804 model="claude-haiku-4-5",
2805 tools=[get_weather],
2806 messages=[{"role": "user", "content": "What is the weather in SF?"}],
2807 )
2808 runner.append_messages({"role": "system", "content": [_tool_reference_block("tool_removal", "get_weather")]})
2809 runner.compact_before_next_turn()
2810 with pytest.warns(UserWarning, match="Tool 'get_weather' not found in tool runner"):
2811 await runner.until_done()
2812
2813 assert calls == []
2814 assert _sent_request_bodies(respx_mock)[2]["messages"][-1] == _not_found_result("toolu_1")
2815
2816
2817 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2818 @pytest.mark.respx(base_url=base_url)
2819 def test_pending_compaction_is_skipped_when_max_iterations_ends_the_run_sync(respx_mock: MockRouter) -> None:
2820 respx_mock.post("/v1/messages").mock(side_effect=[_tool_use_response("get_weather", "toolu_1")])
2821
2822 with Anthropic(
2823 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2824 ) as client:
2825 runner = _sync_compact_runner(client, max_iterations=1)
2826 for _ in runner:
2827 runner.compact_before_next_turn()
2828
2829 assert len(respx_mock.calls) == 1
2830
2831
2832 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2833 @pytest.mark.parametrize(
2834 "content, stop_reason",
2835 [([{"type": "compaction", "content": None}], "compaction"), ([], "max_tokens")],
2836 ids=["block without content", "no block"],
2837 )
2838 @pytest.mark.respx(base_url=base_url)
2839 def test_compaction_without_a_summary_keeps_the_history_and_warns_sync(
2840 respx_mock: MockRouter, caplog: pytest.LogCaptureFixture, content: List[Any], stop_reason: str
2841 ) -> None:
2842 respx_mock.post("/v1/messages").mock(
2843 side_effect=[
2844 _response_without_a_summary(content, stop_reason),
2845 _tool_use_response("get_weather", "toolu_1"),
2846 _end_turn_response(),
2847 ]
2848 )
2849
2850 with Anthropic(
2851 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2852 ) as client:
2853 runner = _sync_compact_runner(client)
2854 runner.append_messages({"role": "user", "content": "And in NYC?"})
2855 runner.compact_before_next_turn()
2856 yielded = 0
2857 with caplog.at_level(logging.WARNING, logger="anthropic.lib.tools._beta_runner"):
2858 for _ in runner:
2859 yielded += 1
2860 # This call is made on the compaction response, so it is ignored: no retry is sent.
2861 if yielded == 1:
2862 runner.compact_before_next_turn()
2863
2864 compaction, after, last = _sent_request_bodies(respx_mock)
2865 assert after["messages"] == compaction["messages"]
2866 assert "compaction" not in after
2867 # The edit made before the compaction request doesn't keep the turn that follows out of the history.
2868 assert [message["role"] for message in last["messages"]] == ["user", "user", "assistant", "user"]
2869 assert "Compaction produced no summary" in caplog.text
2870
2871
2872 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2873 @pytest.mark.respx(base_url=base_url)
2874 def test_until_done_returns_the_final_turn_after_a_compaction_without_a_summary_sync(
2875 respx_mock: MockRouter,
2876 ) -> None:
2877 respx_mock.post("/v1/messages").mock(
2878 side_effect=[_end_turn_response(), _response_without_a_summary([], "max_tokens")]
2879 )
2880
2881 with Anthropic(
2882 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2883 ) as client:
2884 runner = _sync_compact_runner(client)
2885 stop_reasons: List[Any] = []
2886 for message in runner:
2887 stop_reasons.append(message.stop_reason)
2888 runner.compact_before_next_turn()
2889 final = runner.until_done()
2890
2891 assert stop_reasons == ["end_turn", "max_tokens"]
2892 assert final.stop_reason == "end_turn"
2893
2894
2895 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2896 @pytest.mark.respx(base_url=base_url)
2897 async def test_until_done_returns_the_final_turn_after_a_compaction_without_a_summary_async(
2898 respx_mock: MockRouter,
2899 ) -> None:
2900 respx_mock.post("/v1/messages").mock(
2901 side_effect=[_end_turn_response(), _response_without_a_summary([], "max_tokens")]
2902 )
2903
2904 async with AsyncAnthropic(
2905 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2906 ) as client:
2907 runner = _async_compact_runner(client)
2908 stop_reasons: List[Any] = []
2909 async for message in runner:
2910 stop_reasons.append(message.stop_reason)
2911 runner.compact_before_next_turn()
2912 final = await runner.until_done()
2913
2914 assert stop_reasons == ["end_turn", "max_tokens"]
2915 assert final.stop_reason == "end_turn"
2916
2917
2918 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2919 @pytest.mark.respx(base_url=base_url)
2920 def test_messages_cannot_be_replaced_while_compacting_sync(respx_mock: MockRouter) -> None:
2921 respx_mock.post("/v1/messages").mock(
2922 side_effect=[
2923 _tool_use_response("get_weather", "toolu_1"),
2924 _compacted_response(),
2925 _end_turn_response(),
2926 ]
2927 )
2928
2929 with Anthropic(
2930 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2931 ) as client:
2932 runner = _sync_compact_runner(client)
2933 for message in runner:
2934 if message.stop_reason == "tool_use":
2935 runner.compact_before_next_turn()
2936 elif message.stop_reason == "compaction":
2937 with pytest.raises(ValueError, match="Message params can't be changed"):
2938 runner.append_messages({"role": "user", "content": "And in NYC?"})
2939 with pytest.raises(ValueError, match="while the conversation is being compacted"):
2940 runner.set_messages_params(lambda params: {**params, "messages": []})
2941 # Other params can still change, and the change is kept after the history is replaced.
2942 runner.set_messages_params(lambda params: {**params, "max_tokens": 2048})
2943
2944 after = _sent_request_bodies(respx_mock)[2]
2945 assert after["messages"] == _compaction_block_alone()
2946 assert after["max_tokens"] == 2048
2947
2948
2949 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2950 @pytest.mark.respx(base_url=base_url)
2951 def test_failed_compaction_request_is_not_retried_and_frees_the_messages_sync(respx_mock: MockRouter) -> None:
2952 respx_mock.post("/v1/messages").mock(
2953 side_effect=[_tool_use_response("get_weather", "toolu_1"), httpx2.Response(500, json={"type": "error"})]
2954 )
2955
2956 with Anthropic(
2957 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2958 ) as client:
2959 runner = _sync_compact_runner(client)
2960 with pytest.raises(InternalServerError):
2961 for _ in runner:
2962 runner.compact_before_next_turn()
2963
2964 runner.append_messages({"role": "user", "content": "And in NYC?"})
2965 assert list(runner) == []
2966
2967 assert [request.get("compaction") for request in _sent_request_bodies(respx_mock)] == [None, {"type": "summarize"}]
2968
2969
2970 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2971 @pytest.mark.respx(base_url=base_url)
2972 async def test_failed_compaction_request_is_not_retried_and_frees_the_messages_async(respx_mock: MockRouter) -> None:
2973 respx_mock.post("/v1/messages").mock(
2974 side_effect=[_tool_use_response("get_weather", "toolu_1"), httpx2.Response(500, json={"type": "error"})]
2975 )
2976
2977 async with AsyncAnthropic(
2978 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
2979 ) as client:
2980 runner = _async_compact_runner(client)
2981 with pytest.raises(InternalServerError):
2982 async for _ in runner:
2983 runner.compact_before_next_turn()
2984
2985 runner.append_messages({"role": "user", "content": "And in NYC?"})
2986 assert [message async for message in runner] == []
2987
2988 assert [request.get("compaction") for request in _sent_request_bodies(respx_mock)] == [None, {"type": "summarize"}]
2989
2990
2991 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
2992 def test_compaction_param_is_refused_on_a_tool_runner() -> None:
2993 refusal = (
2994 "`compaction` cannot be set on a tool runner: every request in the loop would compact again. "
2995 "Call `runner.compact_before_next_turn()` when the conversation should be compacted instead."
2996 )
2997 with Anthropic(base_url=base_url, api_key="my-anthropic-api-key") as client:
2998 runner = _sync_compact_runner(client)
2999 with pytest.raises(ValueError) as from_setter:
3000 runner.set_messages_params(lambda params: {**params, "compaction": {"type": "summarize"}})
3001 with pytest.raises(ValueError) as from_constructor:
3002 BetaToolRunner(
3003 params={
3004 "max_tokens": 1024,
3005 "model": "claude-haiku-4-5",
3006 "messages": [{"role": "user", "content": "What is the weather in SF?"}],
3007 "compaction": {"type": "summarize"},
3008 "output_format": type(None),
3009 },
3010 options={},
3011 tools=[_sync_weather_tool()],
3012 client=client,
3013 )
3014
3015 assert str(from_setter.value) == str(from_constructor.value) == refusal
3016
3017
3018 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3019 def test_compact_before_next_turn_is_refused_beside_a_compaction_edit() -> None:
3020 with Anthropic(base_url=base_url, api_key="my-anthropic-api-key") as client:
3021 runner = _sync_compact_runner(client, context_management={"edits": [{"type": "compact_20260112"}]})
3022 with pytest.raises(ValueError, match="has a compaction edit"):
3023 runner.compact_before_next_turn()
3024
3025 edits: List[Any] = []
3026 runner = _sync_compact_runner(client, context_management={"edits": edits})
3027 runner.compact_before_next_turn()
3028 with pytest.raises(ValueError, match="has a compaction edit"):
3029 runner.set_messages_params(
3030 lambda params: {**params, "context_management": {"edits": [{"type": "compact_20260112"}]}}
3031 )
3032 # An edit made in place never reaches the setter, so the refusal comes when the request would be sent.
3033 edits.append({"type": "compact_20260112"})
3034 with pytest.raises(ValueError, match="has a compaction edit"):
3035 next(runner)
3036
3037
3038 class _Forecast(pydantic.BaseModel):
3039 summary: str
3040
3041
3042 _FORECAST_FORMAT: BetaJSONOutputFormatParam = {
3043 "type": "json_schema",
3044 "schema": {
3045 "type": "object",
3046 "properties": {"summary": {"type": "string"}},
3047 "required": ["summary"],
3048 "additionalProperties": False,
3049 },
3050 }
3051
3052 _REPLY_PARAMS_CASES = pytest.mark.parametrize(
3053 "tool_choice, output_format, output_config, fallbacks, tool_choice_on_compaction",
3054 [
3055 pytest.param(
3056 {"type": "tool", "name": "get_weather"},
3057 _Forecast,
3058 {"effort": "low"},
3059 omit,
3060 None,
3061 id="forced tool and output_format",
3062 ),
3063 pytest.param(
3064 {"type": "any"},
3065 omit,
3066 {"effort": "low", "format": _FORECAST_FORMAT},
3067 omit,
3068 None,
3069 id="any tool and output_config.format",
3070 ),
3071 pytest.param(
3072 {"type": "auto"},
3073 omit,
3074 {"effort": "low", "format": _FORECAST_FORMAT},
3075 omit,
3076 {"type": "auto"},
3077 id="auto tool_choice stays",
3078 ),
3079 pytest.param(
3080 {"type": "auto"},
3081 omit,
3082 {"effort": "low", "format": _FORECAST_FORMAT},
3083 [
3084 {"model": "claude-sonnet-4-5", "output_config": {"effort": "medium", "format": _FORECAST_FORMAT}},
3085 {"model": "claude-opus-4-5", "max_tokens": 512},
3086 ],
3087 {"type": "auto"},
3088 id="fallback output_config.format",
3089 ),
3090 ],
3091 )
3092
3093
3094 def _compaction_then_forecast_responses() -> List[httpx2.Response]:
3095 forecast = {**_end_turn_response().json(), "content": [{"type": "text", "text": '{"summary": "Sunny"}'}]}
3096 return [_compacted_response(), httpx2.Response(200, json=forecast)]
3097
3098
3099 def _assert_reply_params_are_left_off_the_compaction_request_only(
3100 respx_mock: MockRouter,
3101 tool_choice: BetaToolChoiceParam,
3102 fallbacks: Union[List[BetaFallbackParam], Omit],
3103 tool_choice_on_compaction: Union[BetaToolChoiceParam, None],
3104 ) -> None:
3105 compaction, after = _sent_request_bodies(respx_mock)
3106 assert compaction["compaction"] == {"type": "summarize"}
3107 assert "stop_sequences" not in compaction
3108 assert "output_format" not in compaction
3109 assert compaction["output_config"] == {"effort": "low"}
3110 assert compaction.get("tool_choice") == tool_choice_on_compaction
3111 if isinstance(fallbacks, Omit):
3112 assert "fallbacks" not in compaction
3113 else:
3114 assert compaction["fallbacks"] == [
3115 {"model": "claude-sonnet-4-5", "output_config": {"effort": "medium"}},
3116 {"model": "claude-opus-4-5", "max_tokens": 512},
3117 ]
3118 assert after["fallbacks"] == fallbacks
3119 for kept in ("max_tokens", "system", "tools"):
3120 assert compaction[kept] == after[kept]
3121 assert compaction["system"] == "Be brief."
3122 assert [tool["name"] for tool in compaction["tools"]] == ["get_weather"]
3123
3124 assert after["stop_sequences"] == ["STOP"]
3125 assert after["tool_choice"] == tool_choice
3126 assert after["output_config"]["effort"] == "low"
3127 assert after["output_config"]["format"]["type"] == "json_schema"
3128 assert [call.request.headers.get("anthropic-beta") for call in cast("List[Any]", respx_mock.calls)] == [
3129 "compact-2026-09-04"
3130 ] * 2
3131
3132
3133 @_REPLY_PARAMS_CASES
3134 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3135 @pytest.mark.respx(base_url=base_url)
3136 def test_compaction_request_leaves_off_reply_params_sync(
3137 respx_mock: MockRouter,
3138 tool_choice: BetaToolChoiceParam,
3139 output_format: Union[Type[_Forecast], Omit],
3140 output_config: BetaOutputConfigParam,
3141 fallbacks: Union[List[BetaFallbackParam], Omit],
3142 tool_choice_on_compaction: Union[BetaToolChoiceParam, None],
3143 ) -> None:
3144 respx_mock.post("/v1/messages").mock(side_effect=_compaction_then_forecast_responses())
3145
3146 with Anthropic(
3147 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
3148 ) as client:
3149 runner = client.beta.messages.tool_runner(
3150 max_tokens=1024,
3151 model="claude-haiku-4-5",
3152 system="Be brief.",
3153 tools=[_sync_weather_tool()],
3154 messages=[{"role": "user", "content": "What is the weather in SF?"}],
3155 betas=["compact-2026-09-04"],
3156 stop_sequences=["STOP"],
3157 tool_choice=tool_choice,
3158 output_format=output_format,
3159 output_config=output_config,
3160 fallbacks=fallbacks,
3161 )
3162 runner.compact_before_next_turn()
3163 runner.until_done()
3164
3165 _assert_reply_params_are_left_off_the_compaction_request_only(
3166 respx_mock, tool_choice, fallbacks, tool_choice_on_compaction
3167 )
3168
3169
3170 @_REPLY_PARAMS_CASES
3171 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3172 @pytest.mark.respx(base_url=base_url)
3173 async def test_compaction_request_leaves_off_reply_params_async(
3174 respx_mock: MockRouter,
3175 tool_choice: BetaToolChoiceParam,
3176 output_format: Union[Type[_Forecast], Omit],
3177 output_config: BetaOutputConfigParam,
3178 fallbacks: Union[List[BetaFallbackParam], Omit],
3179 tool_choice_on_compaction: Union[BetaToolChoiceParam, None],
3180 ) -> None:
3181 respx_mock.post("/v1/messages").mock(side_effect=_compaction_then_forecast_responses())
3182
3183 async with AsyncAnthropic(
3184 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
3185 ) as client:
3186 runner = client.beta.messages.tool_runner(
3187 max_tokens=1024,
3188 model="claude-haiku-4-5",
3189 system="Be brief.",
3190 tools=[_async_weather_tool()],
3191 messages=[{"role": "user", "content": "What is the weather in SF?"}],
3192 betas=["compact-2026-09-04"],
3193 stop_sequences=["STOP"],
3194 tool_choice=tool_choice,
3195 output_format=output_format,
3196 output_config=output_config,
3197 fallbacks=fallbacks,
3198 )
3199 runner.compact_before_next_turn()
3200 await runner.until_done()
3201
3202 _assert_reply_params_are_left_off_the_compaction_request_only(
3203 respx_mock, tool_choice, fallbacks, tool_choice_on_compaction
3204 )
3205
3206
3207 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3208 @_sync_and_async
3209 @pytest.mark.respx(base_url=base_url)
3210 async def test_runner_sends_no_beta_header_when_given_no_betas(
3211 sync: bool, client: Anthropic, async_client: AsyncAnthropic, respx_mock: MockRouter
3212 ) -> None:
3213 respx_mock.post("/v1/messages").mock(
3214 side_effect=[_tool_use_response("get_weather", "toolu_weather"), _end_turn_response()]
3215 )
3216
3217 tools: List[Any] = [_sync_weather_tool() if sync else _async_weather_tool()]
3218 runner: Any = (client if sync else async_client).beta.messages.tool_runner(
3219 max_tokens=1024,
3220 model="claude-haiku-4-5",
3221 tools=tools,
3222 messages=[{"role": "user", "content": "What is the weather in SF?"}],
3223 output_config={"format": _FORECAST_FORMAT},
3224 )
3225 if sync:
3226 runner.until_done()
3227 else:
3228 await runner.until_done()
3229
3230 assert [body["output_config"]["format"] for body in _sent_request_bodies(respx_mock)] == [_FORECAST_FORMAT] * 2
3231 assert [call.request.headers.get("anthropic-beta") for call in cast("List[Any]", respx_mock.calls)] == [None] * 2
3232
3233
3234 def _sse_message(content_block: Dict[str, Any], stop_reason: str, *deltas: Dict[str, Any]) -> httpx2.Response:
3235 events: List[Dict[str, Any]] = [
3236 {
3237 "type": "message_start",
3238 "message": {
3239 "id": "msg_streamed",
3240 "type": "message",
3241 "role": "assistant",
3242 "model": "claude-haiku-4-5",
3243 "content": [],
3244 "stop_reason": None,
3245 "stop_sequence": None,
3246 "usage": {"input_tokens": 1, "output_tokens": 1},
3247 },
3248 },
3249 {"type": "content_block_start", "index": 0, "content_block": content_block},
3250 *({"type": "content_block_delta", "index": 0, "delta": delta} for delta in deltas),
3251 {"type": "content_block_stop", "index": 0},
3252 {
3253 "type": "message_delta",
3254 "delta": {"stop_reason": stop_reason, "stop_sequence": None},
3255 "usage": {"output_tokens": 1},
3256 },
3257 {"type": "message_stop"},
3258 ]
3259 body = "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events)
3260 return httpx2.Response(200, content=body.encode(), headers={"content-type": "text/event-stream"})
3261
3262
3263 def _streamed_responses() -> List[httpx2.Response]:
3264 return [
3265 _sse_message(
3266 {"type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {}},
3267 "tool_use",
3268 {"type": "input_json_delta", "partial_json": '{"location": "SF", "units": "f"}'},
3269 ),
3270 # A compaction block arrives whole on the start event; there is no delta for it.
3271 _sse_message({"type": "compaction", "content": "Summary so far.", "signature": "sig_01"}, "compaction"),
3272 _sse_message({"type": "text", "text": ""}, "end_turn", {"type": "text_delta", "text": "Done."}),
3273 ]
3274
3275
3276 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3277 @pytest.mark.respx(base_url=base_url)
3278 def test_compact_before_next_turn_when_streaming_sync(respx_mock: MockRouter) -> None:
3279 respx_mock.post("/v1/messages").mock(side_effect=_streamed_responses())
3280
3281 with Anthropic(
3282 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
3283 ) as client:
3284 runner = client.beta.messages.tool_runner(
3285 max_tokens=1024,
3286 model="claude-haiku-4-5",
3287 tools=[_sync_weather_tool()],
3288 messages=[{"role": "user", "content": "What is the weather in SF?"}],
3289 stream=True,
3290 )
3291 stop_reasons: List[Any] = []
3292 for stream in runner:
3293 stop_reasons.append(stream.get_final_message().stop_reason)
3294 if stop_reasons[-1] == "tool_use":
3295 runner.compact_before_next_turn()
3296
3297 assert stop_reasons == ["tool_use", "compaction", "end_turn"]
3298 _, compaction, after = _sent_request_bodies(respx_mock)
3299 assert compaction["compaction"] == {"type": "summarize"}
3300 assert compaction["stream"] is True
3301 assert after["messages"] == _compaction_block_alone()
3302
3303
3304 @pytest.mark.skipif(PYDANTIC_V1, reason="tool runner not supported with pydantic v1")
3305 @pytest.mark.respx(base_url=base_url)
3306 async def test_compact_before_next_turn_when_streaming_async(respx_mock: MockRouter) -> None:
3307 respx_mock.post("/v1/messages").mock(side_effect=_streamed_responses())
3308
3309 async with AsyncAnthropic(
3310 base_url=base_url, api_key="my-anthropic-api-key", _strict_response_validation=True, max_retries=0
3311 ) as client:
3312 runner = client.beta.messages.tool_runner(
3313 max_tokens=1024,
3314 model="claude-haiku-4-5",
3315 tools=[_async_weather_tool()],
3316 messages=[{"role": "user", "content": "What is the weather in SF?"}],
3317 stream=True,
3318 )
3319 stop_reasons: List[Any] = []
3320 async for stream in runner:
3321 stop_reasons.append((await stream.get_final_message()).stop_reason)
3322 if stop_reasons[-1] == "tool_use":
3323 runner.compact_before_next_turn()
3324
3325 assert stop_reasons == ["tool_use", "compaction", "end_turn"]
3326 _, compaction, after = _sent_request_bodies(respx_mock)
3327 assert compaction["compaction"] == {"type": "summarize"}
3328 assert compaction["stream"] is True
3329 assert after["messages"] == _compaction_block_alone()