| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import sys |
| 4 |
import logging |
| 5 |
from abc import ABC, abstractmethod |
| 6 |
from typing import Any, Union, Generic, TypeVar, Callable, Iterable, Coroutine, cast, overload |
| 7 |
from inspect import isawaitable, isasyncgenfunction, iscoroutinefunction, isgeneratorfunction |
| 8 |
from collections.abc import Awaitable |
| 9 |
from typing_extensions import Literal, TypeAlias, override |
| 10 |
|
| 11 |
import anyio |
| 12 |
import pydantic |
| 13 |
import docstring_parser |
| 14 |
from pydantic import BaseModel |
| 15 |
|
| 16 |
from ... import _compat |
| 17 |
from ..._utils import is_dict |
| 18 |
from ..._compat import cached_property |
| 19 |
from ..._models import TypeAdapter |
| 20 |
from ...types.beta import BetaToolParam, BetaToolUnionParam, BetaCacheControlEphemeralParam |
| 21 |
from ..._utils._utils import CallableT |
| 22 |
from ...types.tool_param import InputSchema |
| 23 |
from ...types.beta.beta_tool_result_block_param import Content as BetaContent |
| 24 |
|
| 25 |
log = logging.getLogger(__name__) |
| 26 |
|
| 27 |
BetaFunctionToolResultType: TypeAlias = Union[str, Iterable[BetaContent]] |
| 28 |
|
| 29 |
|
| 30 |
class ToolError(Exception): |
| 31 |
"""Error that can be raised from a tool to return structured content with `is_error: True`. |
| 32 |
|
| 33 |
When the tool runner catches this error, it will use the `content` |
| 34 |
property as the tool result instead of `repr(exc)`. |
| 35 |
|
| 36 |
Example: |
| 37 |
|
| 38 |
```py |
| 39 |
raise ToolError( |
| 40 |
[ |
| 41 |
{"type": "text", "text": "Error details here"}, |
| 42 |
{"type": "image", "source": {"type": "base64", "data": "...", "media_type": "image/png"}}, |
| 43 |
] |
| 44 |
) |
| 45 |
``` |
| 46 |
""" |
| 47 |
|
| 48 |
content: BetaFunctionToolResultType |
| 49 |
|
| 50 |
def __init__(self, content: BetaFunctionToolResultType) -> None: |
| 51 |
if isinstance(content, str): |
| 52 |
message = content |
| 53 |
else: |
| 54 |
parts: list[str] = [] |
| 55 |
for block in content: |
| 56 |
text = block.get("text") |
| 57 |
if text is not None: |
| 58 |
parts.append(str(text)) |
| 59 |
else: |
| 60 |
parts.append(f"[{block.get('type', 'unknown')}]") |
| 61 |
message = " ".join(parts) if parts else "Tool error" |
| 62 |
super().__init__(message) |
| 63 |
self.content = content |
| 64 |
|
| 65 |
|
| 66 |
Function = Callable[..., BetaFunctionToolResultType] |
| 67 |
FunctionT = TypeVar("FunctionT", bound=Function) |
| 68 |
|
| 69 |
AsyncFunction = Callable[..., Coroutine[Any, Any, BetaFunctionToolResultType]] |
| 70 |
AsyncFunctionT = TypeVar("AsyncFunctionT", bound=AsyncFunction) |
| 71 |
|
| 72 |
|
| 73 |
class BetaBuiltinFunctionTool(ABC): |
| 74 |
@abstractmethod |
| 75 |
def to_dict(self) -> BetaToolUnionParam: ... |
| 76 |
|
| 77 |
@abstractmethod |
| 78 |
def call(self, input: object) -> BetaFunctionToolResultType: ... |
| 79 |
|
| 80 |
@property |
| 81 |
def name(self) -> str: |
| 82 |
raw = self.to_dict() |
| 83 |
if "mcp_server_name" in raw: |
| 84 |
return raw["mcp_server_name"] |
| 85 |
name = raw.get("name") |
| 86 |
if name is None: |
| 87 |
raise ValueError(f"Tool of type {raw.get('type')!r} does not have a name") |
| 88 |
return name |
| 89 |
|
| 90 |
|
| 91 |
class BetaAsyncBuiltinFunctionTool(ABC): |
| 92 |
@abstractmethod |
| 93 |
def to_dict(self) -> BetaToolUnionParam: ... |
| 94 |
|
| 95 |
@abstractmethod |
| 96 |
async def call(self, input: object) -> BetaFunctionToolResultType: ... |
| 97 |
|
| 98 |
@property |
| 99 |
def name(self) -> str: |
| 100 |
raw = self.to_dict() |
| 101 |
if "mcp_server_name" in raw: |
| 102 |
return raw["mcp_server_name"] |
| 103 |
name = raw.get("name") |
| 104 |
if name is None: |
| 105 |
raise ValueError(f"Tool of type {raw.get('type')!r} does not have a name") |
| 106 |
return name |
| 107 |
|
| 108 |
|
| 109 |
class BaseFunctionTool(Generic[CallableT]): |
| 110 |
func: CallableT |
| 111 |
"""The function this tool is wrapping""" |
| 112 |
|
| 113 |
name: str |
| 114 |
"""The name of the tool that will be sent to the API""" |
| 115 |
|
| 116 |
description: str |
| 117 |
|
| 118 |
input_schema: InputSchema |
| 119 |
|
| 120 |
close: Callable[[], None | Awaitable[None]] | None = None |
| 121 |
"""Optional cleanup hook. |
| 122 |
|
| 123 |
A tool that owns a resource (a subprocess, a connection, …) may set this on |
| 124 |
its instance; the result is awaited if it returns an awaitable. |
| 125 |
|
| 126 |
Which runners actually invoke it differs — check before relying on it for a |
| 127 |
stateful tool: |
| 128 |
|
| 129 |
- `SessionToolRunner` (`client.beta.sessions.events.tool_runner(...)`) |
| 130 |
and the `anthropic.lib.environments.EnvironmentWorker` built on it |
| 131 |
**do** call `close` when the run ends. |
| 132 |
- The Messages `BetaToolRunner` / `BetaAsyncToolRunner` |
| 133 |
(`client.beta.messages.tool_runner(...)`) does **not** call `close`. |
| 134 |
A stateful tool (e.g. the `bash` tool's subprocess) handed to the |
| 135 |
Messages tool runner therefore leaks its resource — run it under |
| 136 |
`SessionToolRunner` / the environment worker instead. |
| 137 |
""" |
| 138 |
|
| 139 |
_context_manager: object | None = None |
| 140 |
"""Set by `beta_tool` / `beta_async_tool` when the tool was |
| 141 |
defined as a (sync/async) context manager: the *entered* context manager |
| 142 |
whose `__exit__` / `__aexit__` the tool-runner cleanup path drives on the |
| 143 |
way out. Additive to `close` — both run if both are present, so other |
| 144 |
tool-runner consumers that only set `close` keep working unchanged. |
| 145 |
""" |
| 146 |
|
| 147 |
def __init__( |
| 148 |
self, |
| 149 |
func: CallableT, |
| 150 |
*, |
| 151 |
name: str | None = None, |
| 152 |
description: str | None = None, |
| 153 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 154 |
defer_loading: bool | None = None, |
| 155 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 156 |
allowed_callers: list[ |
| 157 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 158 |
] |
| 159 |
| None = None, |
| 160 |
eager_input_streaming: bool | None = None, |
| 161 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 162 |
strict: bool | None = None, |
| 163 |
) -> None: |
| 164 |
if _compat.PYDANTIC_V1: |
| 165 |
raise RuntimeError("Tool functions are only supported with Pydantic v2") |
| 166 |
|
| 167 |
self.func = func |
| 168 |
self._func_with_validate = pydantic.validate_call(func) |
| 169 |
self.name = name or func.__name__ |
| 170 |
self._defer_loading = defer_loading |
| 171 |
self._cache_control = cache_control |
| 172 |
self._allowed_callers = allowed_callers |
| 173 |
self._eager_input_streaming = eager_input_streaming |
| 174 |
self._input_examples = input_examples |
| 175 |
self._strict = strict |
| 176 |
|
| 177 |
self.description = description or self._get_description_from_docstring() |
| 178 |
|
| 179 |
if input_schema is not None: |
| 180 |
if isinstance(input_schema, type): |
| 181 |
self.input_schema: InputSchema = input_schema.model_json_schema() |
| 182 |
else: |
| 183 |
self.input_schema = input_schema |
| 184 |
else: |
| 185 |
self.input_schema = self._create_schema_from_function() |
| 186 |
|
| 187 |
@property |
| 188 |
def __call__(self) -> CallableT: |
| 189 |
return self.func |
| 190 |
|
| 191 |
def to_dict(self) -> BetaToolParam: |
| 192 |
defn: BetaToolParam = { |
| 193 |
"name": self.name, |
| 194 |
"description": self.description, |
| 195 |
"input_schema": self.input_schema, |
| 196 |
} |
| 197 |
if self._defer_loading is not None: |
| 198 |
defn["defer_loading"] = self._defer_loading |
| 199 |
if self._cache_control is not None: |
| 200 |
defn["cache_control"] = self._cache_control |
| 201 |
if self._allowed_callers is not None: |
| 202 |
defn["allowed_callers"] = self._allowed_callers |
| 203 |
if self._eager_input_streaming is not None: |
| 204 |
defn["eager_input_streaming"] = self._eager_input_streaming |
| 205 |
if self._input_examples is not None: |
| 206 |
defn["input_examples"] = self._input_examples |
| 207 |
if self._strict is not None: |
| 208 |
defn["strict"] = self._strict |
| 209 |
return defn |
| 210 |
|
| 211 |
@cached_property |
| 212 |
def _parsed_docstring(self) -> docstring_parser.Docstring: |
| 213 |
return docstring_parser.parse(self.func.__doc__ or "") |
| 214 |
|
| 215 |
def _get_description_from_docstring(self) -> str: |
| 216 |
"""Extract description from parsed docstring.""" |
| 217 |
if self._parsed_docstring.short_description: |
| 218 |
description = self._parsed_docstring.short_description |
| 219 |
if self._parsed_docstring.long_description: |
| 220 |
description += f"\n\n{self._parsed_docstring.long_description}" |
| 221 |
return description |
| 222 |
return "" |
| 223 |
|
| 224 |
def _create_schema_from_function(self) -> InputSchema: |
| 225 |
"""Create JSON schema from function signature using pydantic.""" |
| 226 |
|
| 227 |
from pydantic_core import CoreSchema |
| 228 |
from pydantic.json_schema import JsonSchemaValue, GenerateJsonSchema |
| 229 |
from pydantic_core.core_schema import ArgumentsParameter |
| 230 |
|
| 231 |
class CustomGenerateJsonSchema(GenerateJsonSchema): |
| 232 |
def __init__(self, *, func: Callable[..., Any], parsed_docstring: Any) -> None: |
| 233 |
super().__init__() |
| 234 |
self._func = func |
| 235 |
self._parsed_docstring = parsed_docstring |
| 236 |
|
| 237 |
def __call__(self, *_args: Any, **_kwds: Any) -> "CustomGenerateJsonSchema": # noqa: ARG002 |
| 238 |
return self |
| 239 |
|
| 240 |
@override |
| 241 |
def kw_arguments_schema( |
| 242 |
self, |
| 243 |
arguments: "list[ArgumentsParameter]", |
| 244 |
var_kwargs_schema: CoreSchema | None, |
| 245 |
) -> JsonSchemaValue: |
| 246 |
schema = super().kw_arguments_schema(arguments, var_kwargs_schema) |
| 247 |
if schema.get("type") != "object": |
| 248 |
return schema |
| 249 |
|
| 250 |
properties = schema.get("properties") |
| 251 |
if not properties or not is_dict(properties): |
| 252 |
return schema |
| 253 |
|
| 254 |
for param in self._parsed_docstring.params: |
| 255 |
prop_schema = properties.get(param.arg_name) |
| 256 |
if not prop_schema or not is_dict(prop_schema): |
| 257 |
continue |
| 258 |
|
| 259 |
if param.description and "description" not in prop_schema: |
| 260 |
prop_schema["description"] = param.description |
| 261 |
|
| 262 |
return schema |
| 263 |
|
| 264 |
schema_generator = CustomGenerateJsonSchema(func=self.func, parsed_docstring=self._parsed_docstring) |
| 265 |
return self._adapter.json_schema(schema_generator=schema_generator) # type: ignore |
| 266 |
|
| 267 |
@cached_property |
| 268 |
def _adapter(self) -> TypeAdapter[Any]: |
| 269 |
return TypeAdapter(self._func_with_validate) |
| 270 |
|
| 271 |
|
| 272 |
class BetaFunctionTool(BaseFunctionTool[FunctionT]): |
| 273 |
def call(self, input: object) -> BetaFunctionToolResultType: |
| 274 |
if iscoroutinefunction(self.func): |
| 275 |
raise RuntimeError("Cannot call a coroutine function synchronously. Use `@async_tool` instead.") |
| 276 |
|
| 277 |
if not is_dict(input): |
| 278 |
raise TypeError(f"Input must be a dictionary, got {type(input).__name__}") |
| 279 |
|
| 280 |
try: |
| 281 |
return self._func_with_validate(**cast(Any, input)) |
| 282 |
except pydantic.ValidationError as e: |
| 283 |
raise ValueError(f"Invalid arguments for function {self.name}") from e |
| 284 |
|
| 285 |
|
| 286 |
class BetaAsyncFunctionTool(BaseFunctionTool[AsyncFunctionT]): |
| 287 |
async def call(self, input: object) -> BetaFunctionToolResultType: |
| 288 |
if not iscoroutinefunction(self.func): |
| 289 |
raise RuntimeError("Cannot call a synchronous function asynchronously. Use `@tool` instead.") |
| 290 |
|
| 291 |
if not is_dict(input): |
| 292 |
raise TypeError(f"Input must be a dictionary, got {type(input).__name__}") |
| 293 |
|
| 294 |
try: |
| 295 |
return await self._func_with_validate(**cast(Any, input)) |
| 296 |
except pydantic.ValidationError as e: |
| 297 |
raise ValueError(f"Invalid arguments for function {self.name}") from e |
| 298 |
|
| 299 |
|
| 300 |
def _is_sync_cm_factory(fn: object) -> bool: |
| 301 |
"""True when `fn` is a function produced by `contextlib.contextmanager`. |
| 302 |
|
| 303 |
`contextmanager` wraps the generator function with `functools.wraps`, so |
| 304 |
the original generator function is reachable as `__wrapped__` — the same |
| 305 |
signal `inspect` itself uses. We never call `fn` to find out, so a |
| 306 |
plain tool function is never accidentally invoked during detection. |
| 307 |
""" |
| 308 |
wrapped = getattr(fn, "__wrapped__", None) |
| 309 |
return wrapped is not None and isgeneratorfunction(wrapped) |
| 310 |
|
| 311 |
|
| 312 |
def _is_async_cm_factory(fn: object) -> bool: |
| 313 |
"""True when `fn` is a function produced by `contextlib.asynccontextmanager`.""" |
| 314 |
wrapped = getattr(fn, "__wrapped__", None) |
| 315 |
return wrapped is not None and isasyncgenfunction(wrapped) |
| 316 |
|
| 317 |
|
| 318 |
async def aclose_runnable_tool(tool: object) -> None: |
| 319 |
"""Run a runnable tool's optional cleanup. |
| 320 |
|
| 321 |
Drives the legacy `aclose` / `close` attribute (awaited if it returns an |
| 322 |
awaitable) and, when the tool was defined as a context manager via |
| 323 |
`beta_tool` / `beta_async_tool`, its `__exit__` / |
| 324 |
`__aexit__`. Both run when both are present — the context-manager support |
| 325 |
is purely additive to `close`. Exceptions are logged, never raised, so one |
| 326 |
tool's bad cleanup can't abort another tool's. |
| 327 |
""" |
| 328 |
closer = getattr(tool, "aclose", None) or getattr(tool, "close", None) |
| 329 |
if closer is not None: |
| 330 |
try: |
| 331 |
result = closer() |
| 332 |
if isawaitable(result): |
| 333 |
await result |
| 334 |
except Exception as e: |
| 335 |
log.warning("tool.close failed tool=%s error=%s", getattr(tool, "name", "?"), e) |
| 336 |
|
| 337 |
cm = getattr(tool, "_context_manager", None) |
| 338 |
if cm is not None: |
| 339 |
try: |
| 340 |
aexit = getattr(cm, "__aexit__", None) |
| 341 |
if aexit is not None: |
| 342 |
await aexit(None, None, None) |
| 343 |
else: |
| 344 |
cm.__exit__(None, None, None) |
| 345 |
except Exception as e: |
| 346 |
log.warning("tool context-manager cleanup failed tool=%s error=%s", getattr(tool, "name", "?"), e) |
| 347 |
|
| 348 |
|
| 349 |
@overload |
| 350 |
def beta_tool(func: FunctionT) -> BetaFunctionTool[FunctionT]: ... |
| 351 |
|
| 352 |
|
| 353 |
@overload |
| 354 |
def beta_tool( |
| 355 |
func: FunctionT, |
| 356 |
*, |
| 357 |
name: str | None = None, |
| 358 |
description: str | None = None, |
| 359 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 360 |
defer_loading: bool | None = None, |
| 361 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 362 |
allowed_callers: list[ |
| 363 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 364 |
] |
| 365 |
| None = None, |
| 366 |
eager_input_streaming: bool | None = None, |
| 367 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 368 |
strict: bool | None = None, |
| 369 |
) -> BetaFunctionTool[FunctionT]: ... |
| 370 |
|
| 371 |
|
| 372 |
@overload |
| 373 |
def beta_tool( |
| 374 |
*, |
| 375 |
name: str | None = None, |
| 376 |
description: str | None = None, |
| 377 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 378 |
defer_loading: bool | None = None, |
| 379 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 380 |
allowed_callers: list[ |
| 381 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 382 |
] |
| 383 |
| None = None, |
| 384 |
eager_input_streaming: bool | None = None, |
| 385 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 386 |
strict: bool | None = None, |
| 387 |
) -> Callable[[FunctionT], BetaFunctionTool[FunctionT]]: ... |
| 388 |
|
| 389 |
|
| 390 |
def beta_tool( |
| 391 |
func: FunctionT | None = None, |
| 392 |
*, |
| 393 |
name: str | None = None, |
| 394 |
description: str | None = None, |
| 395 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 396 |
defer_loading: bool | None = None, |
| 397 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 398 |
allowed_callers: list[ |
| 399 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 400 |
] |
| 401 |
| None = None, |
| 402 |
eager_input_streaming: bool | None = None, |
| 403 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 404 |
strict: bool | None = None, |
| 405 |
) -> BetaFunctionTool[FunctionT] | Callable[[FunctionT], BetaFunctionTool[FunctionT]]: |
| 406 |
"""Create a FunctionTool from a function with automatic schema inference. |
| 407 |
|
| 408 |
Can be used as a decorator with or without parentheses: |
| 409 |
|
| 410 |
@function_tool |
| 411 |
def my_func(x: int) -> str: ... |
| 412 |
|
| 413 |
@function_tool() |
| 414 |
def my_func(x: int) -> str: ... |
| 415 |
|
| 416 |
@function_tool(name="custom_name") |
| 417 |
def my_func(x: int) -> str: ... |
| 418 |
|
| 419 |
`SessionToolRunner` and `EnvironmentWorker` call the function on a |
| 420 |
worker thread. A `@contextmanager` tool is entered at decoration time and |
| 421 |
exited by the runner's cleanup, both off that thread, so avoid thread-bound |
| 422 |
resources such as a default `sqlite3` connection in `__enter__`. |
| 423 |
""" |
| 424 |
if _compat.PYDANTIC_V1: |
| 425 |
raise RuntimeError("Tool functions are only supported with Pydantic v2") |
| 426 |
|
| 427 |
def _make(fn: FunctionT) -> BetaFunctionTool[FunctionT]: |
| 428 |
if _is_async_cm_factory(fn): |
| 429 |
raise TypeError( |
| 430 |
"@beta_tool was applied to an @asynccontextmanager; " |
| 431 |
"use @beta_async_tool for an async context-manager tool" |
| 432 |
) |
| 433 |
if _is_sync_cm_factory(fn): |
| 434 |
# The decorated function is a @contextmanager that yields the tool |
| 435 |
# callable: enter it now to obtain the callable, build the tool from |
| 436 |
# it (so schema inference still sees the real signature), and keep |
| 437 |
# the entered context manager so the runner cleanup can exit it. |
| 438 |
cm = cast(Any, fn)() |
| 439 |
inner = cm.__enter__() |
| 440 |
try: |
| 441 |
tool = BetaFunctionTool( |
| 442 |
cast(FunctionT, inner), |
| 443 |
name=name, |
| 444 |
description=description, |
| 445 |
input_schema=input_schema, |
| 446 |
defer_loading=defer_loading, |
| 447 |
cache_control=cache_control, |
| 448 |
allowed_callers=allowed_callers, |
| 449 |
eager_input_streaming=eager_input_streaming, |
| 450 |
input_examples=input_examples, |
| 451 |
strict=strict, |
| 452 |
) |
| 453 |
except BaseException: |
| 454 |
# Construction failed after we entered the context manager — |
| 455 |
# unwind it so its resource isn't leaked. |
| 456 |
cm.__exit__(*sys.exc_info()) |
| 457 |
raise |
| 458 |
tool._context_manager = cm |
| 459 |
return tool |
| 460 |
return BetaFunctionTool( |
| 461 |
fn, |
| 462 |
name=name, |
| 463 |
description=description, |
| 464 |
input_schema=input_schema, |
| 465 |
defer_loading=defer_loading, |
| 466 |
cache_control=cache_control, |
| 467 |
allowed_callers=allowed_callers, |
| 468 |
eager_input_streaming=eager_input_streaming, |
| 469 |
input_examples=input_examples, |
| 470 |
strict=strict, |
| 471 |
) |
| 472 |
|
| 473 |
if func is not None: |
| 474 |
return _make(func) |
| 475 |
|
| 476 |
return _make |
| 477 |
|
| 478 |
|
| 479 |
@overload |
| 480 |
def beta_async_tool(func: AsyncFunctionT) -> BetaAsyncFunctionTool[AsyncFunctionT]: ... |
| 481 |
|
| 482 |
|
| 483 |
@overload |
| 484 |
def beta_async_tool( |
| 485 |
func: AsyncFunctionT, |
| 486 |
*, |
| 487 |
name: str | None = None, |
| 488 |
description: str | None = None, |
| 489 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 490 |
defer_loading: bool | None = None, |
| 491 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 492 |
allowed_callers: list[ |
| 493 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 494 |
] |
| 495 |
| None = None, |
| 496 |
eager_input_streaming: bool | None = None, |
| 497 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 498 |
strict: bool | None = None, |
| 499 |
) -> BetaAsyncFunctionTool[AsyncFunctionT]: ... # noqa: E501 |
| 500 |
|
| 501 |
|
| 502 |
@overload |
| 503 |
def beta_async_tool( |
| 504 |
*, |
| 505 |
name: str | None = None, |
| 506 |
description: str | None = None, |
| 507 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 508 |
defer_loading: bool | None = None, |
| 509 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 510 |
allowed_callers: list[ |
| 511 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 512 |
] |
| 513 |
| None = None, |
| 514 |
eager_input_streaming: bool | None = None, |
| 515 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 516 |
strict: bool | None = None, |
| 517 |
) -> Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]]: ... |
| 518 |
|
| 519 |
|
| 520 |
def beta_async_tool( |
| 521 |
func: AsyncFunctionT | None = None, |
| 522 |
*, |
| 523 |
name: str | None = None, |
| 524 |
description: str | None = None, |
| 525 |
input_schema: InputSchema | type[BaseModel] | None = None, |
| 526 |
defer_loading: bool | None = None, |
| 527 |
cache_control: BetaCacheControlEphemeralParam | None = None, |
| 528 |
allowed_callers: list[ |
| 529 |
Literal["direct", "code_execution_20250825", "code_execution_20260120", "code_execution_20260521"] |
| 530 |
] |
| 531 |
| None = None, |
| 532 |
eager_input_streaming: bool | None = None, |
| 533 |
input_examples: Iterable[dict[str, object]] | None = None, |
| 534 |
strict: bool | None = None, |
| 535 |
) -> BetaAsyncFunctionTool[AsyncFunctionT] | Callable[[AsyncFunctionT], BetaAsyncFunctionTool[AsyncFunctionT]]: |
| 536 |
"""Create an AsyncFunctionTool from a function with automatic schema inference. |
| 537 |
|
| 538 |
Can be used as a decorator with or without parentheses: |
| 539 |
|
| 540 |
@async_tool |
| 541 |
async def my_func(x: int) -> str: ... |
| 542 |
|
| 543 |
@async_tool() |
| 544 |
async def my_func(x: int) -> str: ... |
| 545 |
|
| 546 |
@async_tool(name="custom_name") |
| 547 |
async def my_func(x: int) -> str: ... |
| 548 |
""" |
| 549 |
if _compat.PYDANTIC_V1: |
| 550 |
raise RuntimeError("Tool functions are only supported with Pydantic v2") |
| 551 |
|
| 552 |
def _make(fn: AsyncFunctionT) -> BetaAsyncFunctionTool[AsyncFunctionT]: |
| 553 |
if _is_sync_cm_factory(fn): |
| 554 |
raise TypeError( |
| 555 |
"@beta_async_tool was applied to a @contextmanager; use @beta_tool for a sync context-manager tool" |
| 556 |
) |
| 557 |
if _is_async_cm_factory(fn): |
| 558 |
# The decorated function is an @asynccontextmanager that yields the |
| 559 |
# tool callable. Entering it requires awaiting, which the decorator |
| 560 |
# can't do, so enter lazily on first call and cache the result; the |
| 561 |
# parameters can't be inferred until then, so an explicit |
| 562 |
# `input_schema` is required. |
| 563 |
if input_schema is None: |
| 564 |
raise TypeError( |
| 565 |
"an @asynccontextmanager tool needs an explicit input_schema= " |
| 566 |
"(its parameters can't be inferred until the context manager is entered)" |
| 567 |
) |
| 568 |
cm = cast(Any, fn)() |
| 569 |
state: dict[str, Any] = {"validated": None, "entered": False} |
| 570 |
enter_lock = anyio.Lock() |
| 571 |
tool_box: list[BetaAsyncFunctionTool[AsyncFunctionT]] = [] |
| 572 |
|
| 573 |
async def _entered() -> Any: |
| 574 |
if not state["entered"]: |
| 575 |
async with enter_lock: |
| 576 |
if not state["entered"]: |
| 577 |
inner = await cm.__aenter__() |
| 578 |
state["validated"] = pydantic.validate_call(inner) |
| 579 |
state["entered"] = True |
| 580 |
# Only now is there an entered __aexit__ to drive on |
| 581 |
# the cleanup path. |
| 582 |
tool_box[0]._context_manager = cm |
| 583 |
return state["validated"] |
| 584 |
|
| 585 |
async def _lazy(**kwargs: Any) -> BetaFunctionToolResultType: |
| 586 |
validated = await _entered() |
| 587 |
return cast(BetaFunctionToolResultType, await validated(**kwargs)) |
| 588 |
|
| 589 |
_lazy.__name__ = name or getattr(fn, "__name__", "tool") |
| 590 |
_lazy.__doc__ = description if description is not None else getattr(fn, "__doc__", None) |
| 591 |
tool = BetaAsyncFunctionTool( |
| 592 |
cast(AsyncFunctionT, _lazy), |
| 593 |
name=name, |
| 594 |
description=description, |
| 595 |
input_schema=input_schema, |
| 596 |
defer_loading=defer_loading, |
| 597 |
cache_control=cache_control, |
| 598 |
allowed_callers=allowed_callers, |
| 599 |
eager_input_streaming=eager_input_streaming, |
| 600 |
input_examples=input_examples, |
| 601 |
strict=strict, |
| 602 |
) |
| 603 |
tool_box.append(tool) |
| 604 |
return tool |
| 605 |
return BetaAsyncFunctionTool( |
| 606 |
fn, |
| 607 |
name=name, |
| 608 |
description=description, |
| 609 |
input_schema=input_schema, |
| 610 |
defer_loading=defer_loading, |
| 611 |
cache_control=cache_control, |
| 612 |
allowed_callers=allowed_callers, |
| 613 |
eager_input_streaming=eager_input_streaming, |
| 614 |
input_examples=input_examples, |
| 615 |
strict=strict, |
| 616 |
) |
| 617 |
|
| 618 |
if func is not None: |
| 619 |
return _make(func) |
| 620 |
|
| 621 |
return _make |
| 622 |
|
| 623 |
|
| 624 |
BetaRunnableTool = Union[BetaFunctionTool[Any], BetaBuiltinFunctionTool] |
| 625 |
BetaAsyncRunnableTool = Union[BetaAsyncFunctionTool[Any], BetaAsyncBuiltinFunctionTool] |