Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions pydantic_ai_slim/pydantic_ai/_function_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,20 @@ def function_schema( # noqa: C901
config = ConfigDict(title=function.__name__, use_attribute_docstrings=True)
config_wrapper = ConfigWrapper(config)
gen_schema = _generate_schema.GenerateSchema(config_wrapper)
errors: list[str] = []

sig = signature(function)
try:
sig = signature(function)
except ValueError as e:
errors.append(f'Error getting signature for {function.__qualname__}: {e}')
sig = signature(lambda: None)

type_hints = _typing_extra.get_function_type_hints(function)

var_kwargs_schema: core_schema.CoreSchema | None = None
fields: dict[str, core_schema.TypedDictField] = {}
positional_fields: list[str] = []
var_positional_field: str | None = None
errors: list[str] = []
decorators = _decorators.DecoratorInfos()

description, field_descriptions = doc_descriptions(function, sig, docstring_format=docstring_format)
Expand Down Expand Up @@ -235,14 +239,19 @@ def _takes_ctx(function: TargetFunc[P, R]) -> TypeIs[WithCtx[P, R]]:
Returns:
`True` if the function takes a `RunContext` as first argument, `False` otherwise.
"""
sig = signature(function)
try:
sig = signature(function)
except ValueError:
return False
try:
first_param_name = next(iter(sig.parameters.keys()))
except StopIteration:
return False
else:
type_hints = _typing_extra.get_function_type_hints(function)
annotation = type_hints[first_param_name]
annotation = type_hints.get(first_param_name)
if annotation is None:
return False # pragma: no cover
return True is not sig.empty and _is_call_ctx(annotation)


Expand Down
28 changes: 28 additions & 0 deletions tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import json
from dataclasses import dataclass, replace
from inspect import signature
from typing import Annotated, Any, Callable, Literal, Union

import pydantic_core
import pytest
from _pytest.logging import LogCaptureFixture
from inline_snapshot import snapshot
from pydantic import BaseModel, Field, WithJsonSchema
from pydantic._internal._typing_extra import get_function_type_hints
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaValue
from pydantic_core import PydanticSerializationError, core_schema
from typing_extensions import TypedDict
Expand Down Expand Up @@ -55,6 +57,32 @@ async def invalid_tool(ctx: RunContext[None]) -> str: # pragma: no cover
)


def test_builtin_tool_registry():
"""
Test that built-in functions can be registered as tools.
"""

with pytest.raises(UserError, match='Error generating schema for'):
Agent(TestModel(), tools=[max])

with pytest.raises(UserError, match='Error generating schema for'):
agent = Agent(TestModel())
agent.tool_plain(min)

def test_tool(*args): # type: ignore[reportUnknownParameterType, reportUnknownArgumentType]
pass

with pytest.raises(ValueError, match='no signature found for'):
signature(max)
sig = signature(test_tool) # type: ignore[reportUnknownArgumentType]
type_hints = get_function_type_hints(test_tool) # type: ignore[reportUnknownArgumentType]
first_param_name = next(iter(sig.parameters.keys()))
with pytest.raises(KeyError):
type_hints[first_param_name] # KeyError

assert first_param_name not in type_hints


def test_tool_ctx_second():
agent = Agent(TestModel())

Expand Down