Debian Codegraph @

src/anthropic/lib/tools/_beta_runner.py

raw
1 from __future__ import annotations
2
3 import logging
4 import warnings
5 from abc import ABC, abstractmethod
6 from copy import copy
7 from typing import (
8 TYPE_CHECKING,
9 Any,
10 Dict,
11 List,
12 Union,
13 Generic,
14 TypeVar,
15 Callable,
16 Iterable,
17 Iterator,
18 Coroutine,
19 AsyncIterator,
20 cast,
21 )
22 from contextlib import contextmanager, asynccontextmanager
23 from typing_extensions import Literal, TypedDict, override
24
25 import httpx2
26
27 from ..._types import Body, Query, Headers, NotGiven
28 from ..._utils import is_given, consume_sync_iterator, consume_async_iterator
29 from ..streaming import BetaMessageStream, BetaAsyncMessageStream, ParsedBetaMessageStreamEvent
30 from ...types.beta import (
31 BetaMessage,
32 BetaMessageParam,
33 BetaToolUseBlock,
34 BetaToolUnionParam,
35 BetaRequestToolRemovalBlockParam,
36 BetaRequestToolAdditionBlockParam,
37 )
38 from ..._base_client import merge_headers
39 from ._tool_dispatch import tool_registry, tool_error_content, available_tool_names
40 from ._beta_functions import (
41 ToolError,
42 BetaFunctionTool,
43 BetaRunnableTool,
44 BetaAsyncFunctionTool,
45 BetaAsyncRunnableTool,
46 BetaBuiltinFunctionTool,
47 BetaAsyncBuiltinFunctionTool,
48 )
49 from .._stainless_helpers import stainless_helper_header
50 from ...types.beta.beta_stop_reason import BetaStopReason
51 from ...types.beta.parsed_beta_message import ResponseFormatT, ParsedBetaMessage, ParsedBetaContentBlock
52 from ...types.beta.message_create_params import ParseMessageCreateParamsBase
53 from ...types.beta.beta_output_config_param import BetaOutputConfigParam
54 from ...types.beta.beta_compaction_config_param import BetaCompactionConfigParam
55 from ...types.beta.beta_tool_result_block_param import BetaToolResultBlockParam
56
57 if TYPE_CHECKING:
58 from ..._client import Anthropic, AsyncAnthropic
59
60
61 AnyFunctionToolT = TypeVar(
62 "AnyFunctionToolT",
63 bound=Union[
64 BetaFunctionTool[Any], BetaAsyncFunctionTool[Any], BetaBuiltinFunctionTool, BetaAsyncBuiltinFunctionTool
65 ],
66 )
67 RunnerItemT = TypeVar("RunnerItemT")
68
69
70 log = logging.getLogger(__name__)
71
72 _Step = Literal["run_tools", "resume", "stop"]
73
74 # Every stop reason maps to exactly one step. The runner tests assert this mapping
75 # covers `BetaStopReason`, so a newly generated value must be classified here.
76 _STOP_REASON_STEPS: dict[BetaStopReason, _Step] = {
77 "tool_use": "run_tools",
78 "pause_turn": "resume",
79 # pause_after_compaction hands the turn back before the model answers; sending it back unchanged continues it.
80 "compaction": "resume",
81 "end_turn": "stop",
82 "stop_sequence": "stop",
83 "max_tokens": "stop",
84 "model_context_window_exceeded": "stop",
85 "refusal": "stop",
86 }
87
88
89 def _determine_next_step_from_stop_reason(stop_reason: BetaStopReason | None) -> _Step:
90 """Decide how the runner loop treats a finished assistant turn.
91
92 - `run_tools`: run the turn's client tool calls, append their results and continue; stop if there are none.
93 - `resume`: the turn is not finished; send it back unchanged, running no tool calls, so the server continues it.
94 - `stop`: terminal; the turn is the final message and its tool_use blocks must not be executed.
95 """
96 if stop_reason is not None and stop_reason in _STOP_REASON_STEPS:
97 return _STOP_REASON_STEPS[stop_reason]
98 # Absent and unknown (forward-compatible) values stop like any other finished turn.
99 return "stop"
100
101
102 def _reject_compaction_param(params: ParseMessageCreateParamsBase[Any]) -> None:
103 compaction = params.get("compaction")
104 if compaction is not None and is_given(compaction):
105 raise ValueError(
106 "`compaction` cannot be set on a tool runner: every request in the loop would compact again. "
107 "Call `runner.compact_before_next_turn()` when the conversation should be compacted instead."
108 )
109
110
111 def _without_format(output_config: BetaOutputConfigParam) -> Dict[str, Any]:
112 return {key: value for key, value in output_config.items() if key != "format"}
113
114
115 def _without_compaction_incompatible_params(params: ParseMessageCreateParamsBase[Any]) -> Dict[str, Any]:
116 """A compaction request returns only the compaction block, never a reply, so the API rejects the
117 params that only shape a reply. The runner's later requests keep them.
118 """
119 trimmed: Dict[str, Any] = {**params}
120 for name in ("context_management", "stop_sequences", "output_format"):
121 trimmed.pop(name, None)
122 tool_choice = params.get("tool_choice")
123 if is_given(tool_choice) and tool_choice and tool_choice["type"] in ("any", "tool"):
124 del trimmed["tool_choice"]
125 output_config = params.get("output_config")
126 if is_given(output_config) and output_config:
127 trimmed["output_config"] = _without_format(output_config)
128 fallbacks = params.get("fallbacks")
129 if is_given(fallbacks) and fallbacks and not isinstance(fallbacks, str):
130 trimmed["fallbacks"] = [
131 {**fallback, "output_config": _without_format(fallback_output_config)}
132 if (fallback_output_config := fallback.get("output_config"))
133 else fallback
134 for fallback in fallbacks
135 ]
136 return trimmed
137
138
139 class RequestOptions(TypedDict, total=False):
140 extra_headers: Headers | None
141 extra_query: Query | None
142 extra_body: Body | None
143 timeout: float | httpx2.Timeout | None | NotGiven
144
145
146 class BaseToolRunner(Generic[AnyFunctionToolT, ResponseFormatT]):
147 def __init__(
148 self,
149 *,
150 params: ParseMessageCreateParamsBase[ResponseFormatT],
151 options: RequestOptions,
152 tools: Iterable[AnyFunctionToolT],
153 max_iterations: int | None = None,
154 ) -> None:
155 _reject_compaction_param(params)
156 self._tools_by_name = tool_registry(tools)
157 self._params: ParseMessageCreateParamsBase[ResponseFormatT] = {
158 **params,
159 "messages": [message for message in params["messages"]],
160 }
161 helper_header = stainless_helper_header(
162 tools=self._tools_by_name.values(),
163 messages=params.get("messages"),
164 )
165 if helper_header:
166 merged_headers = merge_headers(helper_header, options.get("extra_headers") or {})
167 options = {**options, "extra_headers": merged_headers}
168 self._options = options
169 self._messages_modified = False
170 self._cached_tool_call_response: BetaMessageParam | None = None
171 self._max_iterations = max_iterations
172 self._iteration_count = 0
173 self._pending_compaction: BetaCompactionConfigParam | None = None
174 self._messages_being_compacted: Iterable[BetaMessageParam] | None = None
175 self._pending_tool_changes: list[BetaRequestToolAdditionBlockParam | BetaRequestToolRemovalBlockParam] = []
176 self._eager_tool_calls: EagerToolCalls | None = None
177 """The tool calls of the streamed reply being handled. It is `None` without `run_tools_eagerly`."""
178
179 def set_messages_params(
180 self,
181 params: ParseMessageCreateParamsBase[ResponseFormatT]
182 | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]],
183 ) -> None:
184 """
185 Update the parameters for the next API call. This invalidates any cached tool responses. With
186 `run_tools_eagerly`, a tool call of the reply that has run doesn't run again.
187
188 Args:
189 params (ParsedMessageCreateParamsBase[ResponseFormatT] | Callable): Either new parameters or a function to mutate existing parameters
190 """
191 if callable(params):
192 params = params(self._params)
193 _reject_compaction_param(params)
194 if self._messages_being_compacted is not None and params["messages"] is not self._messages_being_compacted:
195 raise ValueError(
196 "Message params can't be changed while the conversation is being compacted, because the compaction "
197 "response replaces them. Make the change on the next iteration."
198 )
199 if self._pending_compaction is not None or self._messages_being_compacted is not None:
200 self._check_can_compact(params)
201 self._params = params
202
203 def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None:
204 """Add one or more messages to the conversation history.
205
206 This invalidates the cached tool response, i.e. if tools were already called, then they will
207 be called again on the next loop iteration. With `run_tools_eagerly`, a tool call of the reply
208 that has run doesn't run again.
209 """
210 message_params: List[BetaMessageParam] = [
211 message.to_param() if isinstance(message, BetaMessage) else message for message in messages
212 ]
213 self.set_messages_params(lambda params: {**params, "messages": [*params["messages"], *message_params]})
214 self._messages_modified = True
215 self._cached_tool_call_response = None
216
217 def compact_before_next_turn(self, compaction: BetaCompactionConfigParam | None = None) -> None:
218 """Compact the conversation before the model's next turn.
219
220 This only schedules the compaction. Once the current turn has finished, including
221 any tool calls, the runner requests a summary and replaces the message history with
222 the compaction response the API returns. That response is yielded like any other
223 message, with `stop_reason == "compaction"`, and the runner then carries on.
224
225 Calling this again before the compaction runs replaces the pending one. Requires
226 the `compact-2026-09-04` beta.
227
228 Args:
229 compaction: The compaction config to send. Defaults to `{"type": "summarize"}`.
230 """
231 if self._messages_being_compacted is not None:
232 return
233 self._check_can_compact(self._params)
234 self._pending_compaction = {"type": "summarize"} if compaction is None else compaction
235
236 def _check_can_compact(self, params: ParseMessageCreateParamsBase[ResponseFormatT]) -> None:
237 # The compaction request is sent without `context_management`, so the API can't reject this
238 # combination there: it would run and bill the compaction, then reject the next request, where
239 # the compaction response and the compaction edit meet.
240 context_management = params.get("context_management")
241 edits = context_management.get("edits") if is_given(context_management) and context_management else None
242 if any(edit["type"].startswith("compact_") for edit in edits or ()):
243 raise ValueError(
244 "`compact_before_next_turn()` can't be used while `context_management` has a compaction edit, "
245 "because the API doesn't accept a compaction block together with one. Remove the edit first."
246 )
247
248 def _pop_compaction_request_params(
249 self, compaction: BetaCompactionConfigParam
250 ) -> ParseMessageCreateParamsBase[ResponseFormatT]:
251 self._check_can_compact(self._params)
252 params = {**_without_compaction_incompatible_params(self._params), "compaction": compaction}
253 self._pending_compaction = None
254 self._messages_being_compacted = self._params["messages"]
255 return cast("ParseMessageCreateParamsBase[ResponseFormatT]", params)
256
257 def _prepare_compaction_after_final_turn(
258 self, message: ParsedBetaMessage[ResponseFormatT]
259 ) -> BetaCompactionConfigParam | None:
260 compaction = self._pending_compaction
261 if compaction is not None and not self._messages_modified:
262 if any(block.type == "tool_use" for block in message.content):
263 # A turn that was cut short can end with tool calls that are never run, and the API
264 # can't compact a conversation whose last turn has an unanswered tool call.
265 log.warning(
266 "The pending compaction was skipped because the last turn (stop_reason=%r) ended with tool calls "
267 "whose results were not sent. Call `compact_before_next_turn()` again if you continue the "
268 "conversation.",
269 message.stop_reason,
270 )
271 self._pending_compaction = None
272 return None
273 self.append_messages(message)
274 return compaction
275
276 def _register_compaction_response(self, message: ParsedBetaMessage[ResponseFormatT]) -> bool:
277 # Summary or not, the request went out with any edit made before it.
278 self._messages_modified = False
279 if not any(block.type == "compaction" and block.content for block in message.content):
280 log.warning("Compaction produced no summary; keeping the conversation as it is.")
281 return False
282 for name in self._tools_by_name.keys() - self._available_tool_names():
283 del self._tools_by_name[name]
284 # The response has to be sent back as it came, first, replacing the messages it summarizes.
285 self._params = {**self._params, "messages": [message.to_param()]}
286 return True
287
288 def add_tools(self, *tools: AnyFunctionToolT | BetaToolUnionParam) -> None:
289 """Give the model more tools without changing the `tools` param, which would miss the prompt cache.
290
291 The definitions are sent in `tool_addition` blocks with the next request. A function tool is run straight
292 away, in place of any tool of the same name, even for a call already in the message being handled. A call
293 that ran while the reply streamed keeps its result. A raw definition is for server tools, such as web
294 search: the tool runner never runs it, and it stops running a function tool of the same name. Requires the
295 `inline-tools-2026-09-15` beta.
296
297 Args:
298 *tools: Function tools, such as `@beta_tool` functions, or raw tool definitions.
299 """
300 for tool in tools:
301 if isinstance(tool, dict):
302 definition: BetaToolUnionParam = copy(tool)
303 name = tool.get("name")
304 if isinstance(name, str):
305 self._tools_by_name.pop(name, None)
306 else:
307 definition = tool.to_dict()
308 self._tools_by_name[tool.name] = tool
309 self._pending_tool_changes.append(
310 {"type": "tool_addition", "tool": {"type": "tool_definition", "definition": definition}}
311 )
312
313 def remove_tools(self, *tools: AnyFunctionToolT | str) -> None:
314 """Take tools away from the model without changing the `tools` param, which would miss the prompt cache.
315
316 The tools stop being run at once, and the model is told in `tool_removal` blocks with the next request. A
317 call that ran while the reply streamed keeps its result. Requires the `inline-tools-2026-09-15` beta.
318
319 Args:
320 *tools: The tools to remove, or their names.
321 """
322 for tool in tools:
323 name = tool if isinstance(tool, str) else tool.name
324 self._tools_by_name.pop(name, None)
325 self._pending_tool_changes.append(
326 {"type": "tool_removal", "tool": {"type": "tool_reference", "name": name}}
327 )
328
329 def _send_pending_tool_changes(self, hold: bool) -> None:
330 # A turn that stopped on `pause_turn` is sent back to be continued, so it has to stay last.
331 if hold or not self._pending_tool_changes:
332 return
333 # Not `append_messages()`: that would make the runner leave this turn's messages for the caller to append.
334 self._params = {
335 **self._params,
336 "messages": [*self._params["messages"], {"role": "system", "content": self._pending_tool_changes}],
337 }
338 self._pending_tool_changes = []
339
340 def _should_stop(self) -> bool:
341 if self._max_iterations is not None and self._iteration_count >= self._max_iterations:
342 return True
343 return False
344
345 def _available_tool_names(self) -> set[str]:
346 """The tool names currently available, after applying any
347 mid-conversation `tool_removal` / `tool_addition` blocks.
348
349 Removal is only a hint to the model, which can still emit a `tool_use`
350 for a withdrawn tool; a name absent from this set routes that call down
351 the same unknown-tool path as a tool that was never declared.
352 """
353 # Changes made since the last request are not in the history yet.
354 pending: BetaMessageParam = {"role": "system", "content": self._pending_tool_changes}
355 return available_tool_names([*self._params["messages"], pending], self._tools_by_name)
356
357
358 class BaseSyncToolRunner(BaseToolRunner[BetaRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC):
359 def __init__(
360 self,
361 *,
362 params: ParseMessageCreateParamsBase[ResponseFormatT],
363 options: RequestOptions,
364 tools: Iterable[BetaRunnableTool],
365 client: Anthropic,
366 max_iterations: int | None = None,
367 ) -> None:
368 super().__init__(
369 params=params,
370 options=options,
371 tools=tools,
372 max_iterations=max_iterations,
373 )
374 self._client = client
375 self._iterator = self.__run__()
376 self._last_message: (
377 Callable[[], ParsedBetaMessage[ResponseFormatT]] | ParsedBetaMessage[ResponseFormatT] | None
378 ) = None
379
380 def __next__(self) -> RunnerItemT:
381 return self._iterator.__next__()
382
383 def __iter__(self) -> Iterator[RunnerItemT]:
384 for item in self._iterator:
385 yield item
386
387 @abstractmethod
388 @contextmanager
389 def _handle_request(self, params: ParseMessageCreateParamsBase[ResponseFormatT]) -> Iterator[RunnerItemT]:
390 raise NotImplementedError()
391 yield # type: ignore[unreachable]
392
393 def _compact(self, compaction: BetaCompactionConfigParam) -> Iterator[RunnerItemT]:
394 last_message = self._last_message
395 try:
396 with self._handle_request(self._pop_compaction_request_params(compaction)) as item:
397 yield item
398 message = self._get_last_message()
399 assert message is not None
400 finally:
401 self._messages_being_compacted = None
402 if not self._register_compaction_response(message):
403 # `until_done()` still returns the turn the run ended on.
404 self._last_message = last_message
405
406 def _compact_after_final_turn(self, message: ParsedBetaMessage[ResponseFormatT]) -> Iterator[RunnerItemT]:
407 compaction = self._prepare_compaction_after_final_turn(message)
408 if compaction is not None:
409 yield from self._compact(compaction)
410
411 def __run__(self) -> Iterator[RunnerItemT]:
412 stop_reason: BetaStopReason | None = None
413 while not self._should_stop():
414 self._send_pending_tool_changes(hold=stop_reason == "pause_turn")
415 # The API can't compact a conversation that ends mid-turn, so a paused turn is resumed first.
416 turn_paused = _determine_next_step_from_stop_reason(stop_reason) == "resume"
417 compaction = None if turn_paused else self._pending_compaction
418 if compaction is not None:
419 yield from self._compact(compaction)
420 continue
421
422 with self._handle_request(self._params) as item:
423 yield item
424 message = self._get_last_message()
425 assert message is not None
426
427 # Update container from response for programmatic tool calling support
428 last_assistant_message = self._get_last_assistant_message()
429 if last_assistant_message is not None and last_assistant_message.container is not None:
430 self._params["container"] = last_assistant_message.container.id
431
432 self._iteration_count += 1
433
434 stop_reason = message.stop_reason
435 next_step = _determine_next_step_from_stop_reason(stop_reason)
436 if next_step == "stop":
437 log.debug("Turn ended with stop_reason %r, exiting from tool runner loop.", message.stop_reason)
438 yield from self._compact_after_final_turn(message)
439 return
440
441 if next_step == "resume":
442 if not self._messages_modified:
443 self.append_messages(message)
444 else:
445 response = self.generate_tool_call_response()
446 if response is None:
447 log.debug("Tool call was not requested, exiting from tool runner loop.")
448 yield from self._compact_after_final_turn(message)
449 return
450 if not self._messages_modified:
451 self.append_messages(message, response)
452
453 self._messages_modified = False
454 self._cached_tool_call_response = None
455
456 def until_done(self) -> ParsedBetaMessage[ResponseFormatT]:
457 """
458 Consumes the tool runner stream and returns the last message if it has not been consumed yet.
459 If it has, it simply returns the last message.
460 """
461 consume_sync_iterator(self)
462 last_message = self._get_last_message()
463 assert last_message is not None
464 return last_message
465
466 def generate_tool_call_response(self) -> BetaMessageParam | None:
467 """Generate a MessageParam by calling tool functions with any tool use blocks from the last message.
468
469 Note the tool call response is cached, repeated calls to this method will return the same response.
470 With `run_tools_eagerly`, it reuses the results of the reply's calls that have run and runs the rest,
471 including the ones `defer_tool_call()` is holding, so that no call runs twice.
472
473 None can be returned if no tool call was applicable.
474 """
475 if self._cached_tool_call_response is not None:
476 log.debug("Returning cached tool call response.")
477 return self._cached_tool_call_response
478 response = self._generate_tool_call_response()
479 self._cached_tool_call_response = response
480 return response
481
482 def _generate_tool_call_response(self) -> BetaMessageParam | None:
483 content = self._get_last_assistant_message_content()
484 if not content:
485 return None
486
487 tool_use_blocks = [block for block in content if block.type == "tool_use"]
488 if not tool_use_blocks:
489 return None
490
491 results: list[BetaToolResultBlockParam] = []
492 available = self._available_tool_names()
493 eager_calls = self._eager_tool_calls
494
495 for tool_use in tool_use_blocks:
496 result: BetaToolResultBlockParam | None = None
497 if eager_calls is not None:
498 result = eager_calls.results.get(tool_use.id)
499 if result is None:
500 tool = self._tools_by_name.get(tool_use.name) if tool_use.name in available else None
501 if tool is None:
502 warnings.warn(
503 f"Tool '{tool_use.name}' not found in tool runner. "
504 f"Available tools: {list(self._tools_by_name.keys())}. "
505 f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. "
506 f"Otherwise, pass the tool using `beta_tool(func)` or a `@beta_tool` decorated function.",
507 UserWarning,
508 stacklevel=3,
509 )
510 result = {
511 "type": "tool_result",
512 "tool_use_id": tool_use.id,
513 "content": f"Error: Tool '{tool_use.name}' not found",
514 "is_error": True,
515 }
516 else:
517 result = self._run_tool(tool, tool_use)
518
519 if eager_calls is not None:
520 eager_calls.record(tool_use, result)
521
522 results.append(result)
523
524 return {"role": "user", "content": results}
525
526 def _run_tool(self, tool: BetaRunnableTool, tool_use: BetaToolUseBlock) -> BetaToolResultBlockParam:
527 try:
528 return {"type": "tool_result", "tool_use_id": tool_use.id, "content": tool.call(tool_use.input)}
529 except ToolError as exc:
530 return {
531 "type": "tool_result",
532 "tool_use_id": tool_use.id,
533 "content": tool_error_content(exc),
534 "is_error": True,
535 }
536 except Exception as exc:
537 log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc)
538 return {
539 "type": "tool_result",
540 "tool_use_id": tool_use.id,
541 "content": tool_error_content(exc),
542 "is_error": True,
543 }
544
545 def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
546 if callable(self._last_message):
547 return self._last_message()
548 return self._last_message
549
550 def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
551 last_message = self._get_last_message()
552 if last_message is None or last_message.role != "assistant" or not last_message.content:
553 return None
554
555 return last_message
556
557 def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None:
558 last_assistant_message = self._get_last_assistant_message()
559 if last_assistant_message is None:
560 return None
561
562 return last_assistant_message.content
563
564
565 class BetaToolRunner(BaseSyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]):
566 @override
567 @contextmanager
568 def _handle_request(
569 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
570 ) -> Iterator[ParsedBetaMessage[ResponseFormatT]]:
571 message = self._client.beta.messages.parse(**params, **self._options)
572 self._last_message = message
573 yield message
574
575
576 class BetaStreamingToolRunner(BaseSyncToolRunner[BetaMessageStream[ResponseFormatT], ResponseFormatT]):
577 def __init__(
578 self,
579 *,
580 params: ParseMessageCreateParamsBase[ResponseFormatT],
581 options: RequestOptions,
582 tools: Iterable[BetaRunnableTool],
583 client: Anthropic,
584 max_iterations: int | None = None,
585 run_tools_eagerly: bool = False,
586 ) -> None:
587 super().__init__(params=params, options=options, tools=tools, client=client, max_iterations=max_iterations)
588 self._run_tools_eagerly = run_tools_eagerly
589
590 def defer_tool_call(self, tool_use: BetaToolUseBlock | str) -> None:
591 """Hold a tool call of the current reply until you are done with the reply, which is when it runs without
592 `run_tools_eagerly`: at the end of the loop body, or when you call `generate_tool_call_response()`.
593
594 With `run_tools_eagerly` the runner otherwise runs each call while the reply streams, once the model has
595 moved on from it: when the next block starts, or the reply stops with `tool_use`. The call runs when you ask
596 for the event after that one, so you can hold it while you handle any event up to and including that one.
597 The other calls of the reply still run early. It does nothing for a call that has run, outside the loop
598 body, and without `run_tools_eagerly`.
599
600 ```py
601 for stream in runner:
602 for event in stream:
603 if event.type == "content_block_start" and event.content_block.type == "tool_use":
604 if event.content_block.name == "delete_file":
605 runner.defer_tool_call(event.content_block)
606 # No `delete_file` call has run yet.
607 ```
608
609 Args:
610 tool_use: The `tool_use` block of the call, or its id.
611 """
612 if self._eager_tool_calls is not None:
613 self._eager_tool_calls.hold(tool_use)
614
615 @property
616 def deferred_tool_calls(self) -> list[BetaToolUseBlock]:
617 """The tool calls of the current reply that `defer_tool_call()` is holding, in the model's order, as their
618 `tool_use` blocks.
619
620 A call is in the list once its block has finished streaming, so read the list when you are done with the
621 stream. A call that has run is not in it. It is empty without `run_tools_eagerly`.
622
623 Held calls are listed whatever the reply's `stop_reason`, because `generate_tool_call_response()` runs them
624 whatever it is. After `max_tokens` the input of the last call can be cut off.
625
626 ```py
627 for stream in runner:
628 for event in stream:
629 if event.type == "content_block_start" and event.content_block.type == "tool_use":
630 if event.content_block.name == "delete_file":
631 runner.defer_tool_call(event.content_block)
632
633 held = runner.deferred_tool_calls
634 if held and not confirm(held):
635 break
636 ```
637 """
638 return [] if self._eager_tool_calls is None else self._eager_tool_calls.held()
639
640 @override
641 @contextmanager
642 def _handle_request(
643 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
644 ) -> Iterator[BetaMessageStream[ResponseFormatT]]:
645 with self._client.beta.messages.stream(**params, **self._options) as stream:
646 self._last_message = stream.get_final_message
647 if self._run_tools_eagerly:
648 self._eager_tool_calls = EagerToolCalls()
649 stream._iterator = self._run_tools_while_streaming(stream._iterator, self._eager_tool_calls)
650 yield stream
651
652 def _run_tools_while_streaming(
653 self, events: Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]], calls: EagerToolCalls
654 ) -> Iterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]:
655 """Passes on the reply's events, and runs each tool call once the reader is done with the event that shows
656 the model has moved on from it. Asking for the next event is how the reader says it is done with the one it
657 holds."""
658 moved_on_from: BetaToolUseBlock | None = None
659 # The next event is read first, so that no call runs once reading the reply has failed.
660 for event in events:
661 if moved_on_from is not None and not calls.is_held(moved_on_from):
662 name = moved_on_from.name
663 tool = self._tools_by_name.get(name) if name in self._available_tool_names() else None
664 # A call to a tool the runner doesn't have gets its error result with the tool response.
665 if tool is not None:
666 calls.record(moved_on_from, self._run_tool(tool, moved_on_from))
667
668 moved_on_from = calls.track(event)
669 yield event
670
671
672 class BaseAsyncToolRunner(
673 BaseToolRunner[BetaAsyncRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC
674 ):
675 def __init__(
676 self,
677 *,
678 params: ParseMessageCreateParamsBase[ResponseFormatT],
679 options: RequestOptions,
680 tools: Iterable[BetaAsyncRunnableTool],
681 client: AsyncAnthropic,
682 max_iterations: int | None = None,
683 ) -> None:
684 super().__init__(
685 params=params,
686 options=options,
687 tools=tools,
688 max_iterations=max_iterations,
689 )
690 self._client = client
691 self._iterator = self.__run__()
692 self._last_message: (
693 Callable[[], Coroutine[None, None, ParsedBetaMessage[ResponseFormatT]]]
694 | ParsedBetaMessage[ResponseFormatT]
695 | None
696 ) = None
697
698 async def __anext__(self) -> RunnerItemT:
699 return await self._iterator.__anext__()
700
701 async def __aiter__(self) -> AsyncIterator[RunnerItemT]:
702 async for item in self._iterator:
703 yield item
704
705 @abstractmethod
706 @asynccontextmanager
707 async def _handle_request(
708 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
709 ) -> AsyncIterator[RunnerItemT]:
710 raise NotImplementedError()
711 yield # type: ignore[unreachable]
712
713 async def _compact(self, compaction: BetaCompactionConfigParam) -> AsyncIterator[RunnerItemT]:
714 last_message = self._last_message
715 try:
716 async with self._handle_request(self._pop_compaction_request_params(compaction)) as item:
717 yield item
718 message = await self._get_last_message()
719 assert message is not None
720 finally:
721 self._messages_being_compacted = None
722 if not self._register_compaction_response(message):
723 # `until_done()` still returns the turn the run ended on.
724 self._last_message = last_message
725
726 async def _compact_after_final_turn(
727 self, message: ParsedBetaMessage[ResponseFormatT]
728 ) -> AsyncIterator[RunnerItemT]:
729 compaction = self._prepare_compaction_after_final_turn(message)
730 if compaction is not None:
731 async for item in self._compact(compaction):
732 yield item
733
734 async def __run__(self) -> AsyncIterator[RunnerItemT]:
735 stop_reason: BetaStopReason | None = None
736 while not self._should_stop():
737 self._send_pending_tool_changes(hold=stop_reason == "pause_turn")
738 # The API can't compact a conversation that ends mid-turn, so a paused turn is resumed first.
739 turn_paused = _determine_next_step_from_stop_reason(stop_reason) == "resume"
740 compaction = None if turn_paused else self._pending_compaction
741 if compaction is not None:
742 async for item in self._compact(compaction):
743 yield item
744 continue
745
746 async with self._handle_request(self._params) as item:
747 yield item
748 message = await self._get_last_message()
749 assert message is not None
750
751 # Update container from response for programmatic tool calling support
752 last_assistant_message = await self._get_last_assistant_message()
753 if last_assistant_message is not None and last_assistant_message.container is not None:
754 self._params["container"] = last_assistant_message.container.id
755
756 self._iteration_count += 1
757
758 stop_reason = message.stop_reason
759 next_step = _determine_next_step_from_stop_reason(stop_reason)
760 if next_step == "stop":
761 log.debug("Turn ended with stop_reason %r, exiting from tool runner loop.", message.stop_reason)
762 async for item in self._compact_after_final_turn(message):
763 yield item
764 return
765
766 if next_step == "resume":
767 if not self._messages_modified:
768 self.append_messages(message)
769 else:
770 response = await self.generate_tool_call_response()
771 if response is None:
772 log.debug("Tool call was not requested, exiting from tool runner loop.")
773 async for item in self._compact_after_final_turn(message):
774 yield item
775 return
776 if not self._messages_modified:
777 self.append_messages(message, response)
778
779 self._messages_modified = False
780 self._cached_tool_call_response = None
781
782 async def until_done(self) -> ParsedBetaMessage[ResponseFormatT]:
783 """
784 Consumes the tool runner stream and returns the last message if it has not been consumed yet.
785 If it has, it simply returns the last message.
786 """
787 await consume_async_iterator(self)
788 last_message = await self._get_last_message()
789 assert last_message is not None
790 return last_message
791
792 async def generate_tool_call_response(self) -> BetaMessageParam | None:
793 """Generate a MessageParam by calling tool functions with any tool use blocks from the last message.
794
795 Note the tool call response is cached, repeated calls to this method will return the same response.
796 With `run_tools_eagerly`, it reuses the results of the reply's calls that have run and runs the rest,
797 including the ones `defer_tool_call()` is holding, so that no call runs twice.
798
799 None can be returned if no tool call was applicable.
800 """
801 if self._cached_tool_call_response is not None:
802 log.debug("Returning cached tool call response.")
803 return self._cached_tool_call_response
804
805 response = await self._generate_tool_call_response()
806 self._cached_tool_call_response = response
807 return response
808
809 async def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
810 if callable(self._last_message):
811 return await self._last_message()
812 return self._last_message
813
814 async def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
815 last_message = await self._get_last_message()
816 if last_message is None or last_message.role != "assistant" or not last_message.content:
817 return None
818
819 return last_message
820
821 async def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None:
822 last_assistant_message = await self._get_last_assistant_message()
823 if last_assistant_message is None:
824 return None
825
826 return last_assistant_message.content
827
828 async def _generate_tool_call_response(self) -> BetaMessageParam | None:
829 content = await self._get_last_assistant_message_content()
830 if not content:
831 return None
832
833 tool_use_blocks = [block for block in content if block.type == "tool_use"]
834 if not tool_use_blocks:
835 return None
836
837 results: list[BetaToolResultBlockParam] = []
838 available = self._available_tool_names()
839 eager_calls = self._eager_tool_calls
840
841 for tool_use in tool_use_blocks:
842 result: BetaToolResultBlockParam | None = None
843 if eager_calls is not None:
844 result = eager_calls.results.get(tool_use.id)
845 if result is None:
846 tool = self._tools_by_name.get(tool_use.name) if tool_use.name in available else None
847 if tool is None:
848 warnings.warn(
849 f"Tool '{tool_use.name}' not found in tool runner. "
850 f"Available tools: {list(self._tools_by_name.keys())}. "
851 f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. "
852 f"Otherwise, pass the tool using `beta_async_tool(func)` or a `@beta_async_tool` decorated function.",
853 UserWarning,
854 stacklevel=3,
855 )
856 result = {
857 "type": "tool_result",
858 "tool_use_id": tool_use.id,
859 "content": f"Error: Tool '{tool_use.name}' not found",
860 "is_error": True,
861 }
862 else:
863 result = await self._run_tool(tool, tool_use)
864
865 if eager_calls is not None:
866 eager_calls.record(tool_use, result)
867
868 results.append(result)
869
870 return {"role": "user", "content": results}
871
872 async def _run_tool(self, tool: BetaAsyncRunnableTool, tool_use: BetaToolUseBlock) -> BetaToolResultBlockParam:
873 try:
874 return {"type": "tool_result", "tool_use_id": tool_use.id, "content": await tool.call(tool_use.input)}
875 except ToolError as exc:
876 return {
877 "type": "tool_result",
878 "tool_use_id": tool_use.id,
879 "content": tool_error_content(exc),
880 "is_error": True,
881 }
882 except Exception as exc:
883 log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc)
884 return {
885 "type": "tool_result",
886 "tool_use_id": tool_use.id,
887 "content": tool_error_content(exc),
888 "is_error": True,
889 }
890
891
892 class BetaAsyncToolRunner(BaseAsyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]):
893 @override
894 @asynccontextmanager
895 async def _handle_request(
896 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
897 ) -> AsyncIterator[ParsedBetaMessage[ResponseFormatT]]:
898 message = await self._client.beta.messages.parse(**params, **self._options)
899 self._last_message = message
900 yield message
901
902
903 class BetaAsyncStreamingToolRunner(BaseAsyncToolRunner[BetaAsyncMessageStream[ResponseFormatT], ResponseFormatT]):
904 def __init__(
905 self,
906 *,
907 params: ParseMessageCreateParamsBase[ResponseFormatT],
908 options: RequestOptions,
909 tools: Iterable[BetaAsyncRunnableTool],
910 client: AsyncAnthropic,
911 max_iterations: int | None = None,
912 run_tools_eagerly: bool = False,
913 ) -> None:
914 super().__init__(params=params, options=options, tools=tools, client=client, max_iterations=max_iterations)
915 self._run_tools_eagerly = run_tools_eagerly
916
917 def defer_tool_call(self, tool_use: BetaToolUseBlock | str) -> None:
918 """Hold a tool call of the current reply until you are done with the reply, which is when it runs without
919 `run_tools_eagerly`: at the end of the loop body, or when you call `generate_tool_call_response()`.
920
921 With `run_tools_eagerly` the runner otherwise runs each call while the reply streams, once the model has
922 moved on from it: when the next block starts, or the reply stops with `tool_use`. The call runs when you ask
923 for the event after that one, so you can hold it while you handle any event up to and including that one.
924 The other calls of the reply still run early. It does nothing for a call that has run, outside the loop
925 body, and without `run_tools_eagerly`.
926
927 ```py
928 async for stream in runner:
929 async for event in stream:
930 if event.type == "content_block_start" and event.content_block.type == "tool_use":
931 if event.content_block.name == "delete_file":
932 runner.defer_tool_call(event.content_block)
933 # No `delete_file` call has run yet.
934 ```
935
936 Args:
937 tool_use: The `tool_use` block of the call, or its id.
938 """
939 if self._eager_tool_calls is not None:
940 self._eager_tool_calls.hold(tool_use)
941
942 @property
943 def deferred_tool_calls(self) -> list[BetaToolUseBlock]:
944 """The tool calls of the current reply that `defer_tool_call()` is holding, in the model's order, as their
945 `tool_use` blocks.
946
947 A call is in the list once its block has finished streaming, so read the list when you are done with the
948 stream. A call that has run is not in it. It is empty without `run_tools_eagerly`.
949
950 Held calls are listed whatever the reply's `stop_reason`, because `generate_tool_call_response()` runs them
951 whatever it is. After `max_tokens` the input of the last call can be cut off.
952
953 ```py
954 async for stream in runner:
955 async for event in stream:
956 if event.type == "content_block_start" and event.content_block.type == "tool_use":
957 if event.content_block.name == "delete_file":
958 runner.defer_tool_call(event.content_block)
959
960 held = runner.deferred_tool_calls
961 if held and not await confirm(held):
962 break
963 ```
964 """
965 return [] if self._eager_tool_calls is None else self._eager_tool_calls.held()
966
967 @override
968 @asynccontextmanager
969 async def _handle_request(
970 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
971 ) -> AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]:
972 async with self._client.beta.messages.stream(**params, **self._options) as stream:
973 self._last_message = stream.get_final_message
974 if self._run_tools_eagerly:
975 self._eager_tool_calls = EagerToolCalls()
976 stream._iterator = self._run_tools_while_streaming(stream._iterator, self._eager_tool_calls)
977 yield stream
978
979 async def _run_tools_while_streaming(
980 self, events: AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]], calls: EagerToolCalls
981 ) -> AsyncIterator[ParsedBetaMessageStreamEvent[ResponseFormatT]]:
982 """Passes on the reply's events, and runs each tool call once the reader is done with the event that shows
983 the model has moved on from it. Asking for the next event is how the reader says it is done with the one it
984 holds."""
985 moved_on_from: BetaToolUseBlock | None = None
986 # The next event is read first, so that no call runs once reading the reply has failed.
987 async for event in events:
988 if moved_on_from is not None and not calls.is_held(moved_on_from):
989 name = moved_on_from.name
990 tool = self._tools_by_name.get(name) if name in self._available_tool_names() else None
991 # A call to a tool the runner doesn't have gets its error result with the tool response.
992 if tool is not None:
993 calls.record(moved_on_from, await self._run_tool(tool, moved_on_from))
994
995 moved_on_from = calls.track(event)
996 yield event
997
998
999 class EagerToolCalls:
1000 """The tool calls of one streamed reply, for a tool runner with `run_tools_eagerly`."""
1001
1002 def __init__(self) -> None:
1003 self.results: dict[str, BetaToolResultBlockParam] = {}
1004 """The result of each call that has run, by `tool_use` id."""
1005
1006 self._finished: list[BetaToolUseBlock] = []
1007 """The `tool_use` blocks that have finished streaming, in the model's order."""
1008
1009 self._held_ids: set[str] = set()
1010 """The ids of the calls that `defer_tool_call()` is holding."""
1011
1012 self._closed: BetaToolUseBlock | None = None
1013 """The last `tool_use` block to close, until the model moves on from it."""
1014
1015 self._fallback = False
1016 """Whether a refusal has handed the reply to a fallback model."""
1017
1018 def hold(self, tool_use: BetaToolUseBlock | str) -> None:
1019 tool_use_id = tool_use if isinstance(tool_use, str) else tool_use.id
1020 if tool_use_id not in self.results:
1021 self._held_ids.add(tool_use_id)
1022
1023 def is_held(self, tool_use: BetaToolUseBlock) -> bool:
1024 return tool_use.id in self._held_ids
1025
1026 def held(self) -> list[BetaToolUseBlock]:
1027 return [tool_use for tool_use in self._finished if tool_use.id in self._held_ids]
1028
1029 def record(self, tool_use: BetaToolUseBlock, result: BetaToolResultBlockParam) -> None:
1030 self._held_ids.discard(tool_use.id)
1031 self.results[tool_use.id] = result
1032
1033 def track(self, event: ParsedBetaMessageStreamEvent[Any]) -> BetaToolUseBlock | None:
1034 """Follows the reply, and returns the call that `event` shows the model has moved on from, if any.
1035
1036 A call's own `content_block_stop` isn't enough, because a reply that is cut off closes its last call too.
1037 After a `fallback` block no call is returned, so the rest wait for the reply to end.
1038 """
1039 if event.type == "content_block_stop":
1040 if event.content_block.type == "tool_use":
1041 self._finished.append(event.content_block)
1042 self._closed = None if self._fallback else event.content_block
1043 return None
1044
1045 if event.type == "content_block_start" and event.content_block.type == "fallback":
1046 # The refusal that led to the fallback may have cut off the call before it.
1047 self._fallback = True
1048 self._closed = None
1049 return None
1050
1051 moved_on = event.type == "content_block_start" or (
1052 event.type == "message_delta" and event.delta.stop_reason == "tool_use"
1053 )
1054 if not moved_on:
1055 return None
1056
1057 moved_on_from, self._closed = self._closed, None
1058 return moved_on_from