Debian Codegraph @

src/anthropic/lib/tools/_tool_params.py

raw
1 """Serializing SDK tool objects into the `tools[]` entries the Messages API accepts."""
2
3 from __future__ import annotations
4
5 from typing import Union, Iterable
6 from typing_extensions import Protocol, TypeAlias, runtime_checkable
7
8 from ..._types import Omit, NotGiven, omit
9 from ..._utils import is_given
10 from .._stainless_helpers import carry_helper_tag
11 from ...types.beta.beta_tool_union_param import BetaToolUnionParam
12
13 __all__ = ["BetaToolLike"]
14
15
16 @runtime_checkable
17 class SupportsToDict(Protocol):
18 """An object whose `to_dict()` is the `tools[]` entry to send for it.
19
20 `@beta_tool` function tools and builtin tools satisfy this, as does anything else
21 with a matching `to_dict()`.
22 """
23
24 def to_dict(self) -> BetaToolUnionParam: ...
25
26
27 BetaToolLike: TypeAlias = Union[BetaToolUnionParam, SupportsToDict]
28 """A `tools[]` entry, or an object that serializes to one through `to_dict()`."""
29
30
31 def to_tool_params(tools: Iterable[BetaToolLike] | Omit | NotGiven) -> list[BetaToolUnionParam] | Omit:
32 """Replace every `to_dict()`-bearing object in `tools` with its entry, keeping order and helper tags."""
33 if not is_given(tools):
34 return omit
35 return [carry_helper_tag(tool, tool.to_dict()) if isinstance(tool, SupportsToDict) else tool for tool in tools]