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 ...types.beta import (
30 BetaMessage,
31 BetaMessageParam,
32 BetaToolUnionParam,
33 BetaRequestToolRemovalBlockParam,
34 BetaRequestToolAdditionBlockParam,
35 )
36 from ..._base_client import merge_headers
37 from ._tool_dispatch import tool_registry, tool_error_content, available_tool_names
38 from ._beta_functions import (
39 ToolError,
40 BetaFunctionTool,
41 BetaRunnableTool,
42 BetaAsyncFunctionTool,
43 BetaAsyncRunnableTool,
44 BetaBuiltinFunctionTool,
45 BetaAsyncBuiltinFunctionTool,
46 )
47 from .._stainless_helpers import stainless_helper_header
48 from ..streaming._beta_messages import BetaMessageStream, BetaAsyncMessageStream
49 from ...types.beta.beta_stop_reason import BetaStopReason
50 from ...types.beta.parsed_beta_message import ResponseFormatT, ParsedBetaMessage, ParsedBetaContentBlock
51 from ...types.beta.message_create_params import ParseMessageCreateParamsBase
52 from ...types.beta.beta_output_config_param import BetaOutputConfigParam
53 from ...types.beta.beta_compaction_config_param import BetaCompactionConfigParam
54 from ...types.beta.beta_tool_result_block_param import BetaToolResultBlockParam
55
56 if TYPE_CHECKING:
57 from ..._client import Anthropic, AsyncAnthropic
58
59
60 AnyFunctionToolT = TypeVar(
61 "AnyFunctionToolT",
62 bound=Union[
63 BetaFunctionTool[Any], BetaAsyncFunctionTool[Any], BetaBuiltinFunctionTool, BetaAsyncBuiltinFunctionTool
64 ],
65 )
66 RunnerItemT = TypeVar("RunnerItemT")
67
68
69 log = logging.getLogger(__name__)
70
71 _Step = Literal["run_tools", "resume", "stop"]
72
73 # Every stop reason maps to exactly one step. The runner tests assert this mapping
74 # covers `BetaStopReason`, so a newly generated value must be classified here.
75 _STOP_REASON_STEPS: dict[BetaStopReason, _Step] = {
76 "tool_use": "run_tools",
77 "pause_turn": "resume",
78 # pause_after_compaction hands the turn back before the model answers; sending it back unchanged continues it.
79 "compaction": "resume",
80 "end_turn": "stop",
81 "stop_sequence": "stop",
82 "max_tokens": "stop",
83 "model_context_window_exceeded": "stop",
84 "refusal": "stop",
85 }
86
87
88 def _determine_next_step_from_stop_reason(stop_reason: BetaStopReason | None) -> _Step:
89 """Decide how the runner loop treats a finished assistant turn.
90
91 - `run_tools`: run the turn's client tool calls, append their results and continue; stop if there are none.
92 - `resume`: the turn is not finished; send it back unchanged, running no tool calls, so the server continues it.
93 - `stop`: terminal; the turn is the final message and its tool_use blocks must not be executed.
94 """
95 if stop_reason is not None and stop_reason in _STOP_REASON_STEPS:
96 return _STOP_REASON_STEPS[stop_reason]
97 # Absent and unknown (forward-compatible) values stop like any other finished turn.
98 return "stop"
99
100
101 def _reject_compaction_param(params: ParseMessageCreateParamsBase[Any]) -> None:
102 compaction = params.get("compaction")
103 if compaction is not None and is_given(compaction):
104 raise ValueError(
105 "`compaction` cannot be set on a tool runner: every request in the loop would compact again. "
106 "Call `runner.compact_before_next_turn()` when the conversation should be compacted instead."
107 )
108
109
110 def _without_format(output_config: BetaOutputConfigParam) -> Dict[str, Any]:
111 return {key: value for key, value in output_config.items() if key != "format"}
112
113
114 def _without_compaction_incompatible_params(params: ParseMessageCreateParamsBase[Any]) -> Dict[str, Any]:
115 """A compaction request returns only the compaction block, never a reply, so the API rejects the
116 params that only shape a reply. The runner's later requests keep them.
117 """
118 trimmed: Dict[str, Any] = {**params}
119 for name in ("context_management", "stop_sequences", "output_format"):
120 trimmed.pop(name, None)
121 tool_choice = params.get("tool_choice")
122 if is_given(tool_choice) and tool_choice and tool_choice["type"] in ("any", "tool"):
123 del trimmed["tool_choice"]
124 output_config = params.get("output_config")
125 if is_given(output_config) and output_config:
126 trimmed["output_config"] = _without_format(output_config)
127 fallbacks = params.get("fallbacks")
128 if is_given(fallbacks) and fallbacks and not isinstance(fallbacks, str):
129 trimmed["fallbacks"] = [
130 {**fallback, "output_config": _without_format(fallback_output_config)}
131 if (fallback_output_config := fallback.get("output_config"))
132 else fallback
133 for fallback in fallbacks
134 ]
135 return trimmed
136
137
138 class RequestOptions(TypedDict, total=False):
139 extra_headers: Headers | None
140 extra_query: Query | None
141 extra_body: Body | None
142 timeout: float | httpx2.Timeout | None | NotGiven
143
144
145 class BaseToolRunner(Generic[AnyFunctionToolT, ResponseFormatT]):
146 def __init__(
147 self,
148 *,
149 params: ParseMessageCreateParamsBase[ResponseFormatT],
150 options: RequestOptions,
151 tools: Iterable[AnyFunctionToolT],
152 max_iterations: int | None = None,
153 ) -> None:
154 _reject_compaction_param(params)
155 self._tools_by_name = tool_registry(tools)
156 self._params: ParseMessageCreateParamsBase[ResponseFormatT] = {
157 **params,
158 "messages": [message for message in params["messages"]],
159 }
160 helper_header = stainless_helper_header(
161 tools=self._tools_by_name.values(),
162 messages=params.get("messages"),
163 )
164 if helper_header:
165 merged_headers = merge_headers(helper_header, options.get("extra_headers") or {})
166 options = {**options, "extra_headers": merged_headers}
167 self._options = options
168 self._messages_modified = False
169 self._cached_tool_call_response: BetaMessageParam | None = None
170 self._max_iterations = max_iterations
171 self._iteration_count = 0
172 self._pending_compaction: BetaCompactionConfigParam | None = None
173 self._messages_being_compacted: Iterable[BetaMessageParam] | None = None
174 self._pending_tool_changes: list[BetaRequestToolAdditionBlockParam | BetaRequestToolRemovalBlockParam] = []
175
176 def set_messages_params(
177 self,
178 params: ParseMessageCreateParamsBase[ResponseFormatT]
179 | Callable[[ParseMessageCreateParamsBase[ResponseFormatT]], ParseMessageCreateParamsBase[ResponseFormatT]],
180 ) -> None:
181 """
182 Update the parameters for the next API call. This invalidates any cached tool responses.
183
184 Args:
185 params (ParsedMessageCreateParamsBase[ResponseFormatT] | Callable): Either new parameters or a function to mutate existing parameters
186 """
187 if callable(params):
188 params = params(self._params)
189 _reject_compaction_param(params)
190 if self._messages_being_compacted is not None and params["messages"] is not self._messages_being_compacted:
191 raise ValueError(
192 "Message params can't be changed while the conversation is being compacted, because the compaction "
193 "response replaces them. Make the change on the next iteration."
194 )
195 if self._pending_compaction is not None or self._messages_being_compacted is not None:
196 self._check_can_compact(params)
197 self._params = params
198
199 def append_messages(self, *messages: BetaMessageParam | ParsedBetaMessage[ResponseFormatT]) -> None:
200 """Add one or more messages to the conversation history.
201
202 This invalidates the cached tool response, i.e. if tools were already called, then they will
203 be called again on the next loop iteration.
204 """
205 message_params: List[BetaMessageParam] = [
206 message.to_param() if isinstance(message, BetaMessage) else message for message in messages
207 ]
208 self.set_messages_params(lambda params: {**params, "messages": [*params["messages"], *message_params]})
209 self._messages_modified = True
210 self._cached_tool_call_response = None
211
212 def compact_before_next_turn(self, compaction: BetaCompactionConfigParam | None = None) -> None:
213 """Compact the conversation before the model's next turn.
214
215 This only schedules the compaction. Once the current turn has finished, including
216 any tool calls, the runner requests a summary and replaces the message history with
217 the compaction response the API returns. That response is yielded like any other
218 message, with `stop_reason == "compaction"`, and the runner then carries on.
219
220 Calling this again before the compaction runs replaces the pending one. Requires
221 the `compact-2026-09-04` beta.
222
223 Args:
224 compaction: The compaction config to send. Defaults to `{"type": "summarize"}`.
225 """
226 if self._messages_being_compacted is not None:
227 return
228 self._check_can_compact(self._params)
229 self._pending_compaction = {"type": "summarize"} if compaction is None else compaction
230
231 def _check_can_compact(self, params: ParseMessageCreateParamsBase[ResponseFormatT]) -> None:
232 # The compaction request is sent without `context_management`, so the API can't reject this
233 # combination there: it would run and bill the compaction, then reject the next request, where
234 # the compaction response and the compaction edit meet.
235 context_management = params.get("context_management")
236 edits = context_management.get("edits") if is_given(context_management) and context_management else None
237 if any(edit["type"].startswith("compact_") for edit in edits or ()):
238 raise ValueError(
239 "`compact_before_next_turn()` can't be used while `context_management` has a compaction edit, "
240 "because the API doesn't accept a compaction block together with one. Remove the edit first."
241 )
242
243 def _pop_compaction_request_params(
244 self, compaction: BetaCompactionConfigParam
245 ) -> ParseMessageCreateParamsBase[ResponseFormatT]:
246 self._check_can_compact(self._params)
247 params = {**_without_compaction_incompatible_params(self._params), "compaction": compaction}
248 self._pending_compaction = None
249 self._messages_being_compacted = self._params["messages"]
250 return cast("ParseMessageCreateParamsBase[ResponseFormatT]", params)
251
252 def _prepare_compaction_after_final_turn(
253 self, message: ParsedBetaMessage[ResponseFormatT]
254 ) -> BetaCompactionConfigParam | None:
255 compaction = self._pending_compaction
256 if compaction is not None and not self._messages_modified:
257 if any(block.type == "tool_use" for block in message.content):
258 # A turn that was cut short can end with tool calls that are never run, and the API
259 # can't compact a conversation whose last turn has an unanswered tool call.
260 log.warning(
261 "The pending compaction was skipped because the last turn (stop_reason=%r) ended with tool calls "
262 "that were not run. Call `compact_before_next_turn()` again if you continue the conversation.",
263 message.stop_reason,
264 )
265 self._pending_compaction = None
266 return None
267 self.append_messages(message)
268 return compaction
269
270 def _register_compaction_response(self, message: ParsedBetaMessage[ResponseFormatT]) -> bool:
271 # Summary or not, the request went out with any edit made before it.
272 self._messages_modified = False
273 if not any(block.type == "compaction" and block.content for block in message.content):
274 log.warning("Compaction produced no summary; keeping the conversation as it is.")
275 return False
276 for name in self._tools_by_name.keys() - self._available_tool_names():
277 del self._tools_by_name[name]
278 # The response has to be sent back as it came, first, replacing the messages it summarizes.
279 self._params = {**self._params, "messages": [message.to_param()]}
280 return True
281
282 def add_tools(self, *tools: AnyFunctionToolT | BetaToolUnionParam) -> None:
283 """Give the model more tools without changing the `tools` param, which would miss the prompt cache.
284
285 The definitions are sent in `tool_addition` blocks with the next request. A function tool is run straight
286 away, in place of any tool of the same name, even for a call already in the message being handled. A raw
287 definition is for server tools, such as web search: the tool runner never runs it, and it stops running a
288 function tool of the same name. Requires the `inline-tools-2026-09-15` beta.
289
290 Args:
291 *tools: Function tools, such as `@beta_tool` functions, or raw tool definitions.
292 """
293 for tool in tools:
294 if isinstance(tool, dict):
295 definition: BetaToolUnionParam = copy(tool)
296 name = tool.get("name")
297 if isinstance(name, str):
298 self._tools_by_name.pop(name, None)
299 else:
300 definition = tool.to_dict()
301 self._tools_by_name[tool.name] = tool
302 self._pending_tool_changes.append(
303 {"type": "tool_addition", "tool": {"type": "tool_definition", "definition": definition}}
304 )
305
306 def remove_tools(self, *tools: AnyFunctionToolT | str) -> None:
307 """Take tools away from the model without changing the `tools` param, which would miss the prompt cache.
308
309 The tools stop being run at once, and the model is told in `tool_removal` blocks with the next request.
310 Requires the `inline-tools-2026-09-15` beta.
311
312 Args:
313 *tools: The tools to remove, or their names.
314 """
315 for tool in tools:
316 name = tool if isinstance(tool, str) else tool.name
317 self._tools_by_name.pop(name, None)
318 self._pending_tool_changes.append(
319 {"type": "tool_removal", "tool": {"type": "tool_reference", "name": name}}
320 )
321
322 def _send_pending_tool_changes(self, hold: bool) -> None:
323 # A turn that stopped on `pause_turn` is sent back to be continued, so it has to stay last.
324 if hold or not self._pending_tool_changes:
325 return
326 # Not `append_messages()`: that would make the runner leave this turn's messages for the caller to append.
327 self._params = {
328 **self._params,
329 "messages": [*self._params["messages"], {"role": "system", "content": self._pending_tool_changes}],
330 }
331 self._pending_tool_changes = []
332
333 def _should_stop(self) -> bool:
334 if self._max_iterations is not None and self._iteration_count >= self._max_iterations:
335 return True
336 return False
337
338 def _available_tool_names(self) -> set[str]:
339 """The tool names currently available, after applying any
340 mid-conversation `tool_removal` / `tool_addition` blocks.
341
342 Removal is only a hint to the model, which can still emit a `tool_use`
343 for a withdrawn tool; a name absent from this set routes that call down
344 the same unknown-tool path as a tool that was never declared.
345 """
346 # Changes made since the last request are not in the history yet.
347 pending: BetaMessageParam = {"role": "system", "content": self._pending_tool_changes}
348 return available_tool_names([*self._params["messages"], pending], self._tools_by_name)
349
350
351 class BaseSyncToolRunner(BaseToolRunner[BetaRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC):
352 def __init__(
353 self,
354 *,
355 params: ParseMessageCreateParamsBase[ResponseFormatT],
356 options: RequestOptions,
357 tools: Iterable[BetaRunnableTool],
358 client: Anthropic,
359 max_iterations: int | None = None,
360 ) -> None:
361 super().__init__(
362 params=params,
363 options=options,
364 tools=tools,
365 max_iterations=max_iterations,
366 )
367 self._client = client
368 self._iterator = self.__run__()
369 self._last_message: (
370 Callable[[], ParsedBetaMessage[ResponseFormatT]] | ParsedBetaMessage[ResponseFormatT] | None
371 ) = None
372
373 def __next__(self) -> RunnerItemT:
374 return self._iterator.__next__()
375
376 def __iter__(self) -> Iterator[RunnerItemT]:
377 for item in self._iterator:
378 yield item
379
380 @abstractmethod
381 @contextmanager
382 def _handle_request(self, params: ParseMessageCreateParamsBase[ResponseFormatT]) -> Iterator[RunnerItemT]:
383 raise NotImplementedError()
384 yield # type: ignore[unreachable]
385
386 def _compact(self, compaction: BetaCompactionConfigParam) -> Iterator[RunnerItemT]:
387 last_message = self._last_message
388 try:
389 with self._handle_request(self._pop_compaction_request_params(compaction)) as item:
390 yield item
391 message = self._get_last_message()
392 assert message is not None
393 finally:
394 self._messages_being_compacted = None
395 if not self._register_compaction_response(message):
396 # `until_done()` still returns the turn the run ended on.
397 self._last_message = last_message
398
399 def _compact_after_final_turn(self, message: ParsedBetaMessage[ResponseFormatT]) -> Iterator[RunnerItemT]:
400 compaction = self._prepare_compaction_after_final_turn(message)
401 if compaction is not None:
402 yield from self._compact(compaction)
403
404 def __run__(self) -> Iterator[RunnerItemT]:
405 stop_reason: BetaStopReason | None = None
406 while not self._should_stop():
407 self._send_pending_tool_changes(hold=stop_reason == "pause_turn")
408 # The API can't compact a conversation that ends mid-turn, so a paused turn is resumed first.
409 turn_paused = _determine_next_step_from_stop_reason(stop_reason) == "resume"
410 compaction = None if turn_paused else self._pending_compaction
411 if compaction is not None:
412 yield from self._compact(compaction)
413 continue
414
415 with self._handle_request(self._params) as item:
416 yield item
417 message = self._get_last_message()
418 assert message is not None
419
420 # Update container from response for programmatic tool calling support
421 last_assistant_message = self._get_last_assistant_message()
422 if last_assistant_message is not None and last_assistant_message.container is not None:
423 self._params["container"] = last_assistant_message.container.id
424
425 self._iteration_count += 1
426
427 stop_reason = message.stop_reason
428 next_step = _determine_next_step_from_stop_reason(stop_reason)
429 if next_step == "stop":
430 log.debug("Turn ended with stop_reason %r, exiting from tool runner loop.", message.stop_reason)
431 yield from self._compact_after_final_turn(message)
432 return
433
434 if next_step == "resume":
435 if not self._messages_modified:
436 self.append_messages(message)
437 else:
438 response = self.generate_tool_call_response()
439 if response is None:
440 log.debug("Tool call was not requested, exiting from tool runner loop.")
441 yield from self._compact_after_final_turn(message)
442 return
443 if not self._messages_modified:
444 self.append_messages(message, response)
445
446 self._messages_modified = False
447 self._cached_tool_call_response = None
448
449 def until_done(self) -> ParsedBetaMessage[ResponseFormatT]:
450 """
451 Consumes the tool runner stream and returns the last message if it has not been consumed yet.
452 If it has, it simply returns the last message.
453 """
454 consume_sync_iterator(self)
455 last_message = self._get_last_message()
456 assert last_message is not None
457 return last_message
458
459 def generate_tool_call_response(self) -> BetaMessageParam | None:
460 """Generate a MessageParam by calling tool functions with any tool use blocks from the last message.
461
462 Note the tool call response is cached, repeated calls to this method will return the same response.
463
464 None can be returned if no tool call was applicable.
465 """
466 if self._cached_tool_call_response is not None:
467 log.debug("Returning cached tool call response.")
468 return self._cached_tool_call_response
469 response = self._generate_tool_call_response()
470 self._cached_tool_call_response = response
471 return response
472
473 def _generate_tool_call_response(self) -> BetaMessageParam | None:
474 content = self._get_last_assistant_message_content()
475 if not content:
476 return None
477
478 tool_use_blocks = [block for block in content if block.type == "tool_use"]
479 if not tool_use_blocks:
480 return None
481
482 results: list[BetaToolResultBlockParam] = []
483 available = self._available_tool_names()
484
485 for tool_use in tool_use_blocks:
486 tool = self._tools_by_name.get(tool_use.name) if tool_use.name in available else None
487 if tool is None:
488 warnings.warn(
489 f"Tool '{tool_use.name}' not found in tool runner. "
490 f"Available tools: {list(self._tools_by_name.keys())}. "
491 f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. "
492 f"Otherwise, pass the tool using `beta_tool(func)` or a `@beta_tool` decorated function.",
493 UserWarning,
494 stacklevel=3,
495 )
496 results.append(
497 {
498 "type": "tool_result",
499 "tool_use_id": tool_use.id,
500 "content": f"Error: Tool '{tool_use.name}' not found",
501 "is_error": True,
502 }
503 )
504 continue
505
506 try:
507 result = tool.call(tool_use.input)
508 results.append({"type": "tool_result", "tool_use_id": tool_use.id, "content": result})
509 except ToolError as exc:
510 results.append(
511 {
512 "type": "tool_result",
513 "tool_use_id": tool_use.id,
514 "content": tool_error_content(exc),
515 "is_error": True,
516 }
517 )
518 except Exception as exc:
519 log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc)
520 results.append(
521 {
522 "type": "tool_result",
523 "tool_use_id": tool_use.id,
524 "content": tool_error_content(exc),
525 "is_error": True,
526 }
527 )
528
529 return {"role": "user", "content": results}
530
531 def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
532 if callable(self._last_message):
533 return self._last_message()
534 return self._last_message
535
536 def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
537 last_message = self._get_last_message()
538 if last_message is None or last_message.role != "assistant" or not last_message.content:
539 return None
540
541 return last_message
542
543 def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None:
544 last_assistant_message = self._get_last_assistant_message()
545 if last_assistant_message is None:
546 return None
547
548 return last_assistant_message.content
549
550
551 class BetaToolRunner(BaseSyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]):
552 @override
553 @contextmanager
554 def _handle_request(
555 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
556 ) -> Iterator[ParsedBetaMessage[ResponseFormatT]]:
557 message = self._client.beta.messages.parse(**params, **self._options)
558 self._last_message = message
559 yield message
560
561
562 class BetaStreamingToolRunner(BaseSyncToolRunner[BetaMessageStream[ResponseFormatT], ResponseFormatT]):
563 @override
564 @contextmanager
565 def _handle_request(
566 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
567 ) -> Iterator[BetaMessageStream[ResponseFormatT]]:
568 with self._client.beta.messages.stream(**params, **self._options) as stream:
569 self._last_message = stream.get_final_message
570 yield stream
571
572
573 class BaseAsyncToolRunner(
574 BaseToolRunner[BetaAsyncRunnableTool, ResponseFormatT], Generic[RunnerItemT, ResponseFormatT], ABC
575 ):
576 def __init__(
577 self,
578 *,
579 params: ParseMessageCreateParamsBase[ResponseFormatT],
580 options: RequestOptions,
581 tools: Iterable[BetaAsyncRunnableTool],
582 client: AsyncAnthropic,
583 max_iterations: int | None = None,
584 ) -> None:
585 super().__init__(
586 params=params,
587 options=options,
588 tools=tools,
589 max_iterations=max_iterations,
590 )
591 self._client = client
592 self._iterator = self.__run__()
593 self._last_message: (
594 Callable[[], Coroutine[None, None, ParsedBetaMessage[ResponseFormatT]]]
595 | ParsedBetaMessage[ResponseFormatT]
596 | None
597 ) = None
598
599 async def __anext__(self) -> RunnerItemT:
600 return await self._iterator.__anext__()
601
602 async def __aiter__(self) -> AsyncIterator[RunnerItemT]:
603 async for item in self._iterator:
604 yield item
605
606 @abstractmethod
607 @asynccontextmanager
608 async def _handle_request(
609 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
610 ) -> AsyncIterator[RunnerItemT]:
611 raise NotImplementedError()
612 yield # type: ignore[unreachable]
613
614 async def _compact(self, compaction: BetaCompactionConfigParam) -> AsyncIterator[RunnerItemT]:
615 last_message = self._last_message
616 try:
617 async with self._handle_request(self._pop_compaction_request_params(compaction)) as item:
618 yield item
619 message = await self._get_last_message()
620 assert message is not None
621 finally:
622 self._messages_being_compacted = None
623 if not self._register_compaction_response(message):
624 # `until_done()` still returns the turn the run ended on.
625 self._last_message = last_message
626
627 async def _compact_after_final_turn(
628 self, message: ParsedBetaMessage[ResponseFormatT]
629 ) -> AsyncIterator[RunnerItemT]:
630 compaction = self._prepare_compaction_after_final_turn(message)
631 if compaction is not None:
632 async for item in self._compact(compaction):
633 yield item
634
635 async def __run__(self) -> AsyncIterator[RunnerItemT]:
636 stop_reason: BetaStopReason | None = None
637 while not self._should_stop():
638 self._send_pending_tool_changes(hold=stop_reason == "pause_turn")
639 # The API can't compact a conversation that ends mid-turn, so a paused turn is resumed first.
640 turn_paused = _determine_next_step_from_stop_reason(stop_reason) == "resume"
641 compaction = None if turn_paused else self._pending_compaction
642 if compaction is not None:
643 async for item in self._compact(compaction):
644 yield item
645 continue
646
647 async with self._handle_request(self._params) as item:
648 yield item
649 message = await self._get_last_message()
650 assert message is not None
651
652 # Update container from response for programmatic tool calling support
653 last_assistant_message = await self._get_last_assistant_message()
654 if last_assistant_message is not None and last_assistant_message.container is not None:
655 self._params["container"] = last_assistant_message.container.id
656
657 self._iteration_count += 1
658
659 stop_reason = message.stop_reason
660 next_step = _determine_next_step_from_stop_reason(stop_reason)
661 if next_step == "stop":
662 log.debug("Turn ended with stop_reason %r, exiting from tool runner loop.", message.stop_reason)
663 async for item in self._compact_after_final_turn(message):
664 yield item
665 return
666
667 if next_step == "resume":
668 if not self._messages_modified:
669 self.append_messages(message)
670 else:
671 response = await self.generate_tool_call_response()
672 if response is None:
673 log.debug("Tool call was not requested, exiting from tool runner loop.")
674 async for item in self._compact_after_final_turn(message):
675 yield item
676 return
677 if not self._messages_modified:
678 self.append_messages(message, response)
679
680 self._messages_modified = False
681 self._cached_tool_call_response = None
682
683 async def until_done(self) -> ParsedBetaMessage[ResponseFormatT]:
684 """
685 Consumes the tool runner stream and returns the last message if it has not been consumed yet.
686 If it has, it simply returns the last message.
687 """
688 await consume_async_iterator(self)
689 last_message = await self._get_last_message()
690 assert last_message is not None
691 return last_message
692
693 async def generate_tool_call_response(self) -> BetaMessageParam | None:
694 """Generate a MessageParam by calling tool functions with any tool use blocks from the last message.
695
696 Note the tool call response is cached, repeated calls to this method will return the same response.
697
698 None can be returned if no tool call was applicable.
699 """
700 if self._cached_tool_call_response is not None:
701 log.debug("Returning cached tool call response.")
702 return self._cached_tool_call_response
703
704 response = await self._generate_tool_call_response()
705 self._cached_tool_call_response = response
706 return response
707
708 async def _get_last_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
709 if callable(self._last_message):
710 return await self._last_message()
711 return self._last_message
712
713 async def _get_last_assistant_message(self) -> ParsedBetaMessage[ResponseFormatT] | None:
714 last_message = await self._get_last_message()
715 if last_message is None or last_message.role != "assistant" or not last_message.content:
716 return None
717
718 return last_message
719
720 async def _get_last_assistant_message_content(self) -> list[ParsedBetaContentBlock[ResponseFormatT]] | None:
721 last_assistant_message = await self._get_last_assistant_message()
722 if last_assistant_message is None:
723 return None
724
725 return last_assistant_message.content
726
727 async def _generate_tool_call_response(self) -> BetaMessageParam | None:
728 content = await self._get_last_assistant_message_content()
729 if not content:
730 return None
731
732 tool_use_blocks = [block for block in content if block.type == "tool_use"]
733 if not tool_use_blocks:
734 return None
735
736 results: list[BetaToolResultBlockParam] = []
737 available = self._available_tool_names()
738
739 for tool_use in tool_use_blocks:
740 tool = self._tools_by_name.get(tool_use.name) if tool_use.name in available else None
741 if tool is None:
742 warnings.warn(
743 f"Tool '{tool_use.name}' not found in tool runner. "
744 f"Available tools: {list(self._tools_by_name.keys())}. "
745 f"If using a raw tool definition, handle the tool call manually and use `append_messages()` to add the result. "
746 f"Otherwise, pass the tool using `beta_async_tool(func)` or a `@beta_async_tool` decorated function.",
747 UserWarning,
748 stacklevel=3,
749 )
750 results.append(
751 {
752 "type": "tool_result",
753 "tool_use_id": tool_use.id,
754 "content": f"Error: Tool '{tool_use.name}' not found",
755 "is_error": True,
756 }
757 )
758 continue
759
760 try:
761 result = await tool.call(tool_use.input)
762 results.append({"type": "tool_result", "tool_use_id": tool_use.id, "content": result})
763 except ToolError as exc:
764 results.append(
765 {
766 "type": "tool_result",
767 "tool_use_id": tool_use.id,
768 "content": tool_error_content(exc),
769 "is_error": True,
770 }
771 )
772 except Exception as exc:
773 log.exception(f"Error occurred while calling tool: {tool.name}", exc_info=exc)
774 results.append(
775 {
776 "type": "tool_result",
777 "tool_use_id": tool_use.id,
778 "content": tool_error_content(exc),
779 "is_error": True,
780 }
781 )
782
783 return {"role": "user", "content": results}
784
785
786 class BetaAsyncToolRunner(BaseAsyncToolRunner[ParsedBetaMessage[ResponseFormatT], ResponseFormatT]):
787 @override
788 @asynccontextmanager
789 async def _handle_request(
790 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
791 ) -> AsyncIterator[ParsedBetaMessage[ResponseFormatT]]:
792 message = await self._client.beta.messages.parse(**params, **self._options)
793 self._last_message = message
794 yield message
795
796
797 class BetaAsyncStreamingToolRunner(BaseAsyncToolRunner[BetaAsyncMessageStream[ResponseFormatT], ResponseFormatT]):
798 @override
799 @asynccontextmanager
800 async def _handle_request(
801 self, params: ParseMessageCreateParamsBase[ResponseFormatT]
802 ) -> AsyncIterator[BetaAsyncMessageStream[ResponseFormatT]]:
803 async with self._client.beta.messages.stream(**params, **self._options) as stream:
804 self._last_message = stream.get_final_message
805 yield stream