pydantic-ai-slim 0.0.6a4__py3-none-any.whl → 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of pydantic-ai-slim might be problematic. Click here for more details.

pydantic_ai/__init__.py CHANGED
@@ -1,8 +1,8 @@
1
1
  from importlib.metadata import version
2
2
 
3
3
  from .agent import Agent
4
- from .dependencies import CallContext
4
+ from .dependencies import RunContext
5
5
  from .exceptions import ModelRetry, UnexpectedModelBehavior, UserError
6
6
 
7
- __all__ = 'Agent', 'CallContext', 'ModelRetry', 'UnexpectedModelBehavior', 'UserError', '__version__'
7
+ __all__ = 'Agent', 'RunContext', 'ModelRetry', 'UnexpectedModelBehavior', 'UserError', '__version__'
8
8
  __version__ = version('pydantic_ai_slim')
pydantic_ai/_pydantic.py CHANGED
@@ -20,8 +20,8 @@ from ._griffe import doc_descriptions
20
20
  from ._utils import ObjectJsonSchema, check_object_json_schema, is_model_like
21
21
 
22
22
  if TYPE_CHECKING:
23
- from . import _retriever
24
- from .dependencies import AgentDeps, RetrieverParams
23
+ from . import _tool
24
+ from .dependencies import AgentDeps, ToolParams
25
25
 
26
26
 
27
27
  __all__ = 'function_schema', 'LazyTypeAdapter'
@@ -39,8 +39,8 @@ class FunctionSchema(TypedDict):
39
39
  var_positional_field: str | None
40
40
 
41
41
 
42
- def function_schema(either_function: _retriever.RetrieverEitherFunc[AgentDeps, RetrieverParams]) -> FunctionSchema: # noqa: C901
43
- """Build a Pydantic validator and JSON schema from a retriever function.
42
+ def function_schema(either_function: _tool.ToolEitherFunc[AgentDeps, ToolParams]) -> FunctionSchema: # noqa: C901
43
+ """Build a Pydantic validator and JSON schema from a tool function.
44
44
 
45
45
  Args:
46
46
  either_function: The function to build a validator and JSON schema for.
@@ -78,13 +78,13 @@ def function_schema(either_function: _retriever.RetrieverEitherFunc[AgentDeps, R
78
78
 
79
79
  if index == 0 and takes_ctx:
80
80
  if not _is_call_ctx(annotation):
81
- errors.append('First argument must be a CallContext instance when using `.retriever`')
81
+ errors.append('First argument must be a RunContext instance when using `.tool`')
82
82
  continue
83
83
  elif not takes_ctx and _is_call_ctx(annotation):
84
- errors.append('CallContext instance can only be used with `.retriever`')
84
+ errors.append('RunContext instance can only be used with `.tool`')
85
85
  continue
86
86
  elif index != 0 and _is_call_ctx(annotation):
87
- errors.append('CallContext instance can only be used as the first argument')
87
+ errors.append('RunContext instance can only be used as the first argument')
88
88
  continue
89
89
 
90
90
  field_name = p.name
@@ -191,10 +191,10 @@ def _build_schema(
191
191
 
192
192
 
193
193
  def _is_call_ctx(annotation: Any) -> bool:
194
- from .dependencies import CallContext
194
+ from .dependencies import RunContext
195
195
 
196
- return annotation is CallContext or (
197
- _typing_extra.is_generic_alias(annotation) and get_origin(annotation) is CallContext
196
+ return annotation is RunContext or (
197
+ _typing_extra.is_generic_alias(annotation) and get_origin(annotation) is RunContext
198
198
  )
199
199
 
200
200
 
pydantic_ai/_result.py CHANGED
@@ -11,7 +11,7 @@ from pydantic import TypeAdapter, ValidationError
11
11
  from typing_extensions import Self, TypeAliasType, TypedDict
12
12
 
13
13
  from . import _utils, messages
14
- from .dependencies import AgentDeps, CallContext, ResultValidatorFunc
14
+ from .dependencies import AgentDeps, ResultValidatorFunc, RunContext
15
15
  from .exceptions import ModelRetry
16
16
  from .messages import ModelStructuredResponse, ToolCall
17
17
  from .result import ResultData
@@ -42,7 +42,7 @@ class ResultValidator(Generic[AgentDeps, ResultData]):
42
42
  Result of either the validated result data (ok) or a retry message (Err).
43
43
  """
44
44
  if self._takes_ctx:
45
- args = CallContext(deps, retry, tool_call.tool_name if tool_call else None), result
45
+ args = RunContext(deps, retry, tool_call.tool_name if tool_call else None), result
46
46
  else:
47
47
  args = (result,)
48
48
 
@@ -75,7 +75,7 @@ class ToolRetryError(Exception):
75
75
  class ResultSchema(Generic[ResultData]):
76
76
  """Model the final response from an agent run.
77
77
 
78
- Similar to `Retriever` but for the final result of running an agent.
78
+ Similar to `Tool` but for the final result of running an agent.
79
79
  """
80
80
 
81
81
  tools: dict[str, ResultTool[ResultData]]
@@ -191,7 +191,7 @@ class ResultTool(Generic[ResultData]):
191
191
  )
192
192
  else:
193
193
  result = self.type_adapter.validate_python(
194
- tool_call.args.args_object, experimental_allow_partial=pyd_allow_partial
194
+ tool_call.args.args_dict, experimental_allow_partial=pyd_allow_partial
195
195
  )
196
196
  except ValidationError as e:
197
197
  if wrap_validation_errors:
@@ -6,7 +6,7 @@ from dataclasses import dataclass, field
6
6
  from typing import Any, Callable, Generic, cast
7
7
 
8
8
  from . import _utils
9
- from .dependencies import AgentDeps, CallContext, SystemPromptFunc
9
+ from .dependencies import AgentDeps, RunContext, SystemPromptFunc
10
10
 
11
11
 
12
12
  @dataclass
@@ -21,7 +21,7 @@ class SystemPromptRunner(Generic[AgentDeps]):
21
21
 
22
22
  async def run(self, deps: AgentDeps) -> str:
23
23
  if self._takes_ctx:
24
- args = (CallContext(deps, 0, None),)
24
+ args = (RunContext(deps, 0, None),)
25
25
  else:
26
26
  args = ()
27
27
 
@@ -9,22 +9,20 @@ from pydantic import ValidationError
9
9
  from pydantic_core import SchemaValidator
10
10
 
11
11
  from . import _pydantic, _utils, messages
12
- from .dependencies import AgentDeps, CallContext, RetrieverContextFunc, RetrieverParams, RetrieverPlainFunc
12
+ from .dependencies import AgentDeps, RunContext, ToolContextFunc, ToolParams, ToolPlainFunc
13
13
  from .exceptions import ModelRetry, UnexpectedModelBehavior
14
14
 
15
- # Usage `RetrieverEitherFunc[AgentDependencies, P]`
16
- RetrieverEitherFunc = _utils.Either[
17
- RetrieverContextFunc[AgentDeps, RetrieverParams], RetrieverPlainFunc[RetrieverParams]
18
- ]
15
+ # Usage `ToolEitherFunc[AgentDependencies, P]`
16
+ ToolEitherFunc = _utils.Either[ToolContextFunc[AgentDeps, ToolParams], ToolPlainFunc[ToolParams]]
19
17
 
20
18
 
21
19
  @dataclass(init=False)
22
- class Retriever(Generic[AgentDeps, RetrieverParams]):
23
- """A retriever function for an agent."""
20
+ class Tool(Generic[AgentDeps, ToolParams]):
21
+ """A tool function for an agent."""
24
22
 
25
23
  name: str
26
24
  description: str
27
- function: RetrieverEitherFunc[AgentDeps, RetrieverParams] = field(repr=False)
25
+ function: ToolEitherFunc[AgentDeps, ToolParams] = field(repr=False)
28
26
  is_async: bool
29
27
  single_arg_name: str | None
30
28
  positional_fields: list[str]
@@ -35,8 +33,8 @@ class Retriever(Generic[AgentDeps, RetrieverParams]):
35
33
  _current_retry: int = 0
36
34
  outer_typed_dict_key: str | None = None
37
35
 
38
- def __init__(self, function: RetrieverEitherFunc[AgentDeps, RetrieverParams], retries: int):
39
- """Build a Retriever dataclass from a function."""
36
+ def __init__(self, function: ToolEitherFunc[AgentDeps, ToolParams], retries: int):
37
+ """Build a Tool dataclass from a function."""
40
38
  self.function = function
41
39
  # noinspection PyTypeChecker
42
40
  f = _pydantic.function_schema(function)
@@ -56,12 +54,12 @@ class Retriever(Generic[AgentDeps, RetrieverParams]):
56
54
  self._current_retry = 0
57
55
 
58
56
  async def run(self, deps: AgentDeps, message: messages.ToolCall) -> messages.Message:
59
- """Run the retriever function asynchronously."""
57
+ """Run the tool function asynchronously."""
60
58
  try:
61
59
  if isinstance(message.args, messages.ArgsJson):
62
60
  args_dict = self.validator.validate_json(message.args.args_json)
63
61
  else:
64
- args_dict = self.validator.validate_python(message.args.args_object)
62
+ args_dict = self.validator.validate_python(message.args.args_dict)
65
63
  except ValidationError as e:
66
64
  return self._on_error(e, message)
67
65
 
@@ -89,7 +87,7 @@ class Retriever(Generic[AgentDeps, RetrieverParams]):
89
87
  if self.single_arg_name:
90
88
  args_dict = {self.single_arg_name: args_dict}
91
89
 
92
- args = [CallContext(deps, self._current_retry, message.tool_name)] if self.function.is_left() else []
90
+ args = [RunContext(deps, self._current_retry, message.tool_name)] if self.function.is_left() else []
93
91
  for positional_field in self.positional_fields:
94
92
  args.append(args_dict.pop(positional_field))
95
93
  if self.var_positional_field:
@@ -100,8 +98,8 @@ class Retriever(Generic[AgentDeps, RetrieverParams]):
100
98
  def _on_error(self, exc: ValidationError | ModelRetry, call_message: messages.ToolCall) -> messages.RetryPrompt:
101
99
  self._current_retry += 1
102
100
  if self._current_retry > self.max_retries:
103
- # TODO custom error with details of the retriever
104
- raise UnexpectedModelBehavior(f'Retriever exceeded max retries count of {self.max_retries}') from exc
101
+ # TODO custom error with details of the tool
102
+ raise UnexpectedModelBehavior(f'Tool exceeded max retries count of {self.max_retries}') from exc
105
103
  else:
106
104
  if isinstance(exc, ValidationError):
107
105
  content = exc.errors(include_url=False)
pydantic_ai/_utils.py CHANGED
@@ -12,7 +12,7 @@ from typing import Any, Callable, Generic, TypeVar, Union, cast, overload
12
12
 
13
13
  from pydantic import BaseModel
14
14
  from pydantic.json_schema import JsonSchemaValue
15
- from typing_extensions import ParamSpec, TypeAlias, is_typeddict
15
+ from typing_extensions import ParamSpec, TypeAlias, TypeGuard, is_typeddict
16
16
 
17
17
  _P = ParamSpec('_P')
18
18
  _R = TypeVar('_R')
@@ -66,10 +66,6 @@ Option: TypeAlias = Union[Some[T], None]
66
66
  """Analogous to Rust's `Option` type, usage: `Option[Thing]` is equivalent to `Some[Thing] | None`."""
67
67
 
68
68
 
69
- Left = TypeVar('Left')
70
- Right = TypeVar('Right')
71
-
72
-
73
69
  class Unset:
74
70
  """A singleton to represent an unset value."""
75
71
 
@@ -79,6 +75,14 @@ class Unset:
79
75
  UNSET = Unset()
80
76
 
81
77
 
78
+ def is_set(t_or_unset: T | Unset) -> TypeGuard[T]:
79
+ return t_or_unset is not UNSET
80
+
81
+
82
+ Left = TypeVar('Left')
83
+ Right = TypeVar('Right')
84
+
85
+
82
86
  class Either(Generic[Left, Right]):
83
87
  """Two member Union that records which member was set, this is analogous to Rust enums with two variants.
84
88