pydantic-ai-slim 1.0.9__py3-none-any.whl → 1.0.11__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.
@@ -547,7 +547,7 @@ class CallToolsNode(AgentNode[DepsT, NodeRunEndT]):
547
547
  async def _run_stream() -> AsyncIterator[_messages.HandleResponseEvent]: # noqa: C901
548
548
  text = ''
549
549
  tool_calls: list[_messages.ToolCallPart] = []
550
- thinking_parts: list[_messages.ThinkingPart] = []
550
+ invisible_parts: bool = False
551
551
 
552
552
  for part in self.model_response.parts:
553
553
  if isinstance(part, _messages.TextPart):
@@ -558,11 +558,13 @@ class CallToolsNode(AgentNode[DepsT, NodeRunEndT]):
558
558
  # Text parts before a built-in tool call are essentially thoughts,
559
559
  # not part of the final result output, so we reset the accumulated text
560
560
  text = ''
561
+ invisible_parts = True
561
562
  yield _messages.BuiltinToolCallEvent(part) # pyright: ignore[reportDeprecated]
562
563
  elif isinstance(part, _messages.BuiltinToolReturnPart):
564
+ invisible_parts = True
563
565
  yield _messages.BuiltinToolResultEvent(part) # pyright: ignore[reportDeprecated]
564
566
  elif isinstance(part, _messages.ThinkingPart):
565
- thinking_parts.append(part)
567
+ invisible_parts = True
566
568
  else:
567
569
  assert_never(part)
568
570
 
@@ -570,43 +572,51 @@ class CallToolsNode(AgentNode[DepsT, NodeRunEndT]):
570
572
  # In the future, we'd consider making this configurable at the agent or run level.
571
573
  # This accounts for cases like anthropic returns that might contain a text response
572
574
  # and a tool call response, where the text response just indicates the tool call will happen.
573
- if tool_calls:
574
- async for event in self._handle_tool_calls(ctx, tool_calls):
575
- yield event
576
- elif text:
577
- # No events are emitted during the handling of text responses, so we don't need to yield anything
578
- self._next_node = await self._handle_text_response(ctx, text)
579
- elif thinking_parts:
580
- # handle thinking-only responses (responses that contain only ThinkingPart instances)
581
- # this can happen with models that support thinking mode when they don't provide
582
- # actionable output alongside their thinking content.
583
- self._next_node = ModelRequestNode[DepsT, NodeRunEndT](
584
- _messages.ModelRequest(
585
- parts=[_messages.RetryPromptPart('Responses without text or tool calls are not permitted.')]
575
+ try:
576
+ if tool_calls:
577
+ async for event in self._handle_tool_calls(ctx, tool_calls):
578
+ yield event
579
+ elif text:
580
+ # No events are emitted during the handling of text responses, so we don't need to yield anything
581
+ self._next_node = await self._handle_text_response(ctx, text)
582
+ elif invisible_parts:
583
+ # handle responses with only thinking or built-in tool parts.
584
+ # this can happen with models that support thinking mode when they don't provide
585
+ # actionable output alongside their thinking content. so we tell the model to try again.
586
+ m = _messages.RetryPromptPart(
587
+ content='Responses without text or tool calls are not permitted.',
586
588
  )
587
- )
588
- else:
589
- # we got an empty response with no tool calls, text, or thinking
590
- # this sometimes happens with anthropic (and perhaps other models)
591
- # when the model has already returned text along side tool calls
592
- # in this scenario, if text responses are allowed, we return text from the most recent model
593
- # response, if any
594
- if isinstance(ctx.deps.output_schema, _output.TextOutputSchema):
595
- for message in reversed(ctx.state.message_history):
596
- if isinstance(message, _messages.ModelResponse):
597
- text = ''
598
- for part in message.parts:
599
- if isinstance(part, _messages.TextPart):
600
- text += part.content
601
- elif isinstance(part, _messages.BuiltinToolCallPart):
602
- # Text parts before a built-in tool call are essentially thoughts,
603
- # not part of the final result output, so we reset the accumulated text
604
- text = '' # pragma: no cover
605
- if text:
606
- self._next_node = await self._handle_text_response(ctx, text)
607
- return
608
-
609
- raise exceptions.UnexpectedModelBehavior('Received empty model response')
589
+ raise ToolRetryError(m)
590
+ else:
591
+ # we got an empty response with no tool calls, text, thinking, or built-in tool calls.
592
+ # this sometimes happens with anthropic (and perhaps other models)
593
+ # when the model has already returned text along side tool calls
594
+ # in this scenario, if text responses are allowed, we return text from the most recent model
595
+ # response, if any
596
+ if isinstance(ctx.deps.output_schema, _output.TextOutputSchema):
597
+ for message in reversed(ctx.state.message_history):
598
+ if isinstance(message, _messages.ModelResponse):
599
+ text = ''
600
+ for part in message.parts:
601
+ if isinstance(part, _messages.TextPart):
602
+ text += part.content
603
+ elif isinstance(part, _messages.BuiltinToolCallPart):
604
+ # Text parts before a built-in tool call are essentially thoughts,
605
+ # not part of the final result output, so we reset the accumulated text
606
+ text = '' # pragma: no cover
607
+ if text:
608
+ self._next_node = await self._handle_text_response(ctx, text)
609
+ return
610
+
611
+ # Go back to the model request node with an empty request, which means we'll essentially
612
+ # resubmit the most recent request that resulted in an empty response,
613
+ # as the empty response and request will not create any items in the API payload,
614
+ # in the hope the model will return a non-empty response this time.
615
+ ctx.state.increment_retries(ctx.deps.max_result_retries)
616
+ self._next_node = ModelRequestNode[DepsT, NodeRunEndT](_messages.ModelRequest(parts=[]))
617
+ except ToolRetryError as e:
618
+ ctx.state.increment_retries(ctx.deps.max_result_retries, e)
619
+ self._next_node = ModelRequestNode[DepsT, NodeRunEndT](_messages.ModelRequest(parts=[e.tool_retry]))
610
620
 
611
621
  self._events_iterator = _run_stream()
612
622
 
@@ -666,23 +676,19 @@ class CallToolsNode(AgentNode[DepsT, NodeRunEndT]):
666
676
  text: str,
667
677
  ) -> ModelRequestNode[DepsT, NodeRunEndT] | End[result.FinalResult[NodeRunEndT]]:
668
678
  output_schema = ctx.deps.output_schema
669
- try:
670
- run_context = build_run_context(ctx)
671
- if isinstance(output_schema, _output.TextOutputSchema):
672
- result_data = await output_schema.process(text, run_context)
673
- else:
674
- m = _messages.RetryPromptPart(
675
- content='Plain text responses are not permitted, please include your response in a tool call',
676
- )
677
- raise ToolRetryError(m)
679
+ run_context = build_run_context(ctx)
678
680
 
679
- for validator in ctx.deps.output_validators:
680
- result_data = await validator.validate(result_data, run_context)
681
- except ToolRetryError as e:
682
- ctx.state.increment_retries(ctx.deps.max_result_retries, e)
683
- return ModelRequestNode[DepsT, NodeRunEndT](_messages.ModelRequest(parts=[e.tool_retry]))
681
+ if isinstance(output_schema, _output.TextOutputSchema):
682
+ result_data = await output_schema.process(text, run_context)
684
683
  else:
685
- return self._handle_final_result(ctx, result.FinalResult(result_data), [])
684
+ m = _messages.RetryPromptPart(
685
+ content='Plain text responses are not permitted, please include your response in a tool call',
686
+ )
687
+ raise ToolRetryError(m)
688
+
689
+ for validator in ctx.deps.output_validators:
690
+ result_data = await validator.validate(result_data, run_context)
691
+ return self._handle_final_result(ctx, result.FinalResult(result_data), [])
686
692
 
687
693
  __repr__ = dataclasses_no_defaults_repr
688
694
 
@@ -231,31 +231,39 @@ R = TypeVar('R')
231
231
 
232
232
  WithCtx = Callable[Concatenate[RunContext[Any], P], R]
233
233
  WithoutCtx = Callable[P, R]
234
- TargetFunc = WithCtx[P, R] | WithoutCtx[P, R]
234
+ TargetCallable = WithCtx[P, R] | WithoutCtx[P, R]
235
235
 
236
236
 
237
- def _takes_ctx(function: TargetFunc[P, R]) -> TypeIs[WithCtx[P, R]]:
238
- """Check if a function takes a `RunContext` first argument.
237
+ def _takes_ctx(callable_obj: TargetCallable[P, R]) -> TypeIs[WithCtx[P, R]]:
238
+ """Check if a callable takes a `RunContext` first argument.
239
239
 
240
240
  Args:
241
- function: The function to check.
241
+ callable_obj: The callable to check.
242
242
 
243
243
  Returns:
244
- `True` if the function takes a `RunContext` as first argument, `False` otherwise.
244
+ `True` if the callable takes a `RunContext` as first argument, `False` otherwise.
245
245
  """
246
246
  try:
247
- sig = signature(function)
248
- except ValueError: # pragma: no cover
249
- return False # pragma: no cover
247
+ sig = signature(callable_obj)
248
+ except ValueError:
249
+ return False
250
250
  try:
251
251
  first_param_name = next(iter(sig.parameters.keys()))
252
252
  except StopIteration:
253
253
  return False
254
254
  else:
255
- type_hints = _typing_extra.get_function_type_hints(function)
255
+ # See https://github.com/pydantic/pydantic/pull/11451 for a similar implementation in Pydantic
256
+ if not isinstance(callable_obj, _decorators._function_like): # pyright: ignore[reportPrivateUsage]
257
+ call_func = getattr(type(callable_obj), '__call__', None)
258
+ if call_func is not None:
259
+ callable_obj = call_func
260
+ else:
261
+ return False # pragma: no cover
262
+
263
+ type_hints = _typing_extra.get_function_type_hints(_decorators.unwrap_wrapped_function(callable_obj))
256
264
  annotation = type_hints.get(first_param_name)
257
265
  if annotation is None:
258
- return False # pragma: no cover
266
+ return False
259
267
  return True is not sig.empty and _is_call_ctx(annotation)
260
268
 
261
269
 
pydantic_ai/_output.py CHANGED
@@ -19,6 +19,7 @@ from .output import (
19
19
  NativeOutput,
20
20
  OutputDataT,
21
21
  OutputMode,
22
+ OutputObjectDefinition,
22
23
  OutputSpec,
23
24
  OutputTypeOrFunction,
24
25
  PromptedOutput,
@@ -581,14 +582,6 @@ class ToolOrTextOutputSchema(ToolOutputSchema[OutputDataT], PlainTextOutputSchem
581
582
  return 'tool_or_text'
582
583
 
583
584
 
584
- @dataclass
585
- class OutputObjectDefinition:
586
- json_schema: ObjectJsonSchema
587
- name: str | None = None
588
- description: str | None = None
589
- strict: bool | None = None
590
-
591
-
592
585
  @dataclass(init=False)
593
586
  class BaseOutputProcessor(ABC, Generic[OutputDataT]):
594
587
  @abstractmethod
@@ -259,7 +259,8 @@ class Agent(AbstractAgent[AgentDepsT, OutputDataT]):
259
259
  name: The name of the agent, used for logging. If `None`, we try to infer the agent name from the call frame
260
260
  when the agent is first run.
261
261
  model_settings: Optional model request settings to use for this agent's runs, by default.
262
- retries: The default number of retries to allow before raising an error.
262
+ retries: The default number of retries to allow for tool calls and output validation, before raising an error.
263
+ For model request retries, see the [HTTP Request Retries](../retries.md) documentation.
263
264
  output_retries: The maximum number of retries to allow for output validation, defaults to `retries`.
264
265
  tools: Tools to register with the agent, you can also register tools via the decorators
265
266
  [`@agent.tool`][pydantic_ai.Agent.tool] and [`@agent.tool_plain`][pydantic_ai.Agent.tool_plain].
@@ -1,15 +1,17 @@
1
1
  from __future__ import annotations as _annotations
2
2
 
3
3
  from collections.abc import Iterable, Iterator, Mapping
4
- from dataclasses import asdict, dataclass, is_dataclass
4
+ from dataclasses import asdict, dataclass, field, fields, is_dataclass
5
5
  from datetime import date
6
- from typing import Any
6
+ from typing import Any, Literal
7
7
  from xml.etree import ElementTree
8
8
 
9
9
  from pydantic import BaseModel
10
10
 
11
11
  __all__ = ('format_as_xml',)
12
12
 
13
+ from pydantic.fields import ComputedFieldInfo, FieldInfo
14
+
13
15
 
14
16
  def format_as_xml(
15
17
  obj: Any,
@@ -17,6 +19,7 @@ def format_as_xml(
17
19
  item_tag: str = 'item',
18
20
  none_str: str = 'null',
19
21
  indent: str | None = ' ',
22
+ include_field_info: Literal['once'] | bool = False,
20
23
  ) -> str:
21
24
  """Format a Python object as XML.
22
25
 
@@ -33,6 +36,10 @@ def format_as_xml(
33
36
  for dataclasses and Pydantic models.
34
37
  none_str: String to use for `None` values.
35
38
  indent: Indentation string to use for pretty printing.
39
+ include_field_info: Whether to include attributes like Pydantic `Field` attributes and dataclasses `field()`
40
+ `metadata` as XML attributes. In both cases the allowed `Field` attributes and `field()` metadata keys are
41
+ `title` and `description`. If a field is repeated in the data (e.g. in a list) by setting `once`
42
+ the attributes are included only in the first occurrence of an XML element relative to the same field.
36
43
 
37
44
  Returns:
38
45
  XML representation of the object.
@@ -51,7 +58,12 @@ def format_as_xml(
51
58
  '''
52
59
  ```
53
60
  """
54
- el = _ToXml(item_tag=item_tag, none_str=none_str).to_xml(obj, root_tag)
61
+ el = _ToXml(
62
+ data=obj,
63
+ item_tag=item_tag,
64
+ none_str=none_str,
65
+ include_field_info=include_field_info,
66
+ ).to_xml(root_tag)
55
67
  if root_tag is None and el.text is None:
56
68
  join = '' if indent is None else '\n'
57
69
  return join.join(_rootless_xml_elements(el, indent))
@@ -63,11 +75,26 @@ def format_as_xml(
63
75
 
64
76
  @dataclass
65
77
  class _ToXml:
78
+ data: Any
66
79
  item_tag: str
67
80
  none_str: str
68
-
69
- def to_xml(self, value: Any, tag: str | None) -> ElementTree.Element:
70
- element = ElementTree.Element(self.item_tag if tag is None else tag)
81
+ include_field_info: Literal['once'] | bool
82
+ # a map of Pydantic and dataclasses Field paths to their metadata:
83
+ # a field unique string representation and its class
84
+ _fields_info: dict[str, tuple[str, FieldInfo | ComputedFieldInfo]] = field(default_factory=dict)
85
+ # keep track of fields we have extracted attributes from
86
+ _included_fields: set[str] = field(default_factory=set)
87
+ # keep track of class names for dataclasses and Pydantic models, that occur in lists
88
+ _element_names: dict[str, str] = field(default_factory=dict)
89
+ # flag for parsing dataclasses and Pydantic models once
90
+ _is_info_extracted: bool = False
91
+ _FIELD_ATTRIBUTES = ('title', 'description')
92
+
93
+ def to_xml(self, tag: str | None = None) -> ElementTree.Element:
94
+ return self._to_xml(value=self.data, path='', tag=tag)
95
+
96
+ def _to_xml(self, value: Any, path: str, tag: str | None = None) -> ElementTree.Element:
97
+ element = self._create_element(self.item_tag if tag is None else tag, path)
71
98
  if value is None:
72
99
  element.text = self.none_str
73
100
  elif isinstance(value, str):
@@ -79,31 +106,96 @@ class _ToXml:
79
106
  elif isinstance(value, date):
80
107
  element.text = value.isoformat()
81
108
  elif isinstance(value, Mapping):
82
- self._mapping_to_xml(element, value) # pyright: ignore[reportUnknownArgumentType]
109
+ if tag is None and path in self._element_names:
110
+ element.tag = self._element_names[path]
111
+ self._mapping_to_xml(element, value, path) # pyright: ignore[reportUnknownArgumentType]
83
112
  elif is_dataclass(value) and not isinstance(value, type):
113
+ self._init_structure_info()
84
114
  if tag is None:
85
- element = ElementTree.Element(value.__class__.__name__)
86
- dc_dict = asdict(value)
87
- self._mapping_to_xml(element, dc_dict)
115
+ element.tag = value.__class__.__name__
116
+ self._mapping_to_xml(element, asdict(value), path)
88
117
  elif isinstance(value, BaseModel):
118
+ self._init_structure_info()
89
119
  if tag is None:
90
- element = ElementTree.Element(value.__class__.__name__)
91
- self._mapping_to_xml(element, value.model_dump(mode='python'))
120
+ element.tag = value.__class__.__name__
121
+ # by dumping the model we loose all metadata in nested data structures,
122
+ # but we have collected it when called _init_structure_info
123
+ self._mapping_to_xml(element, value.model_dump(), path)
92
124
  elif isinstance(value, Iterable):
93
- for item in value: # pyright: ignore[reportUnknownVariableType]
94
- item_el = self.to_xml(item, None)
95
- element.append(item_el)
125
+ for n, item in enumerate(value): # pyright: ignore[reportUnknownVariableType,reportUnknownArgumentType]
126
+ element.append(self._to_xml(value=item, path=f'{path}.[{n}]' if path else f'[{n}]'))
96
127
  else:
97
128
  raise TypeError(f'Unsupported type for XML formatting: {type(value)}')
98
129
  return element
99
130
 
100
- def _mapping_to_xml(self, element: ElementTree.Element, mapping: Mapping[Any, Any]) -> None:
131
+ def _create_element(self, tag: str, path: str) -> ElementTree.Element:
132
+ element = ElementTree.Element(tag)
133
+ if path in self._fields_info:
134
+ field_repr, field_info = self._fields_info[path]
135
+ if self.include_field_info and self.include_field_info != 'once' or field_repr not in self._included_fields:
136
+ field_attributes = self._extract_attributes(field_info)
137
+ for k, v in field_attributes.items():
138
+ element.set(k, v)
139
+ self._included_fields.add(field_repr)
140
+ return element
141
+
142
+ def _init_structure_info(self):
143
+ """Create maps with all data information (fields info and class names), if not already created."""
144
+ if not self._is_info_extracted:
145
+ self._parse_data_structures(self.data)
146
+ self._is_info_extracted = True
147
+
148
+ def _mapping_to_xml(
149
+ self,
150
+ element: ElementTree.Element,
151
+ mapping: Mapping[Any, Any],
152
+ path: str = '',
153
+ ) -> None:
101
154
  for key, value in mapping.items():
102
155
  if isinstance(key, int):
103
156
  key = str(key)
104
157
  elif not isinstance(key, str):
105
158
  raise TypeError(f'Unsupported key type for XML formatting: {type(key)}, only str and int are allowed')
106
- element.append(self.to_xml(value, key))
159
+ element.append(self._to_xml(value=value, path=f'{path}.{key}' if path else key, tag=key))
160
+
161
+ def _parse_data_structures(
162
+ self,
163
+ value: Any,
164
+ path: str = '',
165
+ ):
166
+ """Parse data structures as dataclasses or Pydantic models to extract element names and attributes."""
167
+ if value is None or isinstance(value, (str | int | float | date | bytearray | bytes | bool)):
168
+ return
169
+ elif isinstance(value, Mapping):
170
+ for k, v in value.items(): # pyright: ignore[reportUnknownVariableType]
171
+ self._parse_data_structures(v, f'{path}.{k}' if path else f'{k}')
172
+ elif is_dataclass(value) and not isinstance(value, type):
173
+ self._element_names[path] = value.__class__.__name__
174
+ for field in fields(value):
175
+ new_path = f'{path}.{field.name}' if path else field.name
176
+ if self.include_field_info and field.metadata:
177
+ attributes = {k: v for k, v in field.metadata.items() if k in self._FIELD_ATTRIBUTES}
178
+ if attributes:
179
+ field_repr = f'{value.__class__.__name__}.{field.name}'
180
+ self._fields_info[new_path] = (field_repr, FieldInfo(**attributes))
181
+ self._parse_data_structures(getattr(value, field.name), new_path)
182
+ elif isinstance(value, BaseModel):
183
+ self._element_names[path] = value.__class__.__name__
184
+ for model_fields in (value.__class__.model_fields, value.__class__.model_computed_fields):
185
+ for field, info in model_fields.items():
186
+ new_path = f'{path}.{field}' if path else field
187
+ if self.include_field_info and (isinstance(info, ComputedFieldInfo) or not info.exclude):
188
+ field_repr = f'{value.__class__.__name__}.{field}'
189
+ self._fields_info[new_path] = (field_repr, info)
190
+ self._parse_data_structures(getattr(value, field), new_path)
191
+ elif isinstance(value, Iterable):
192
+ for n, item in enumerate(value): # pyright: ignore[reportUnknownVariableType,reportUnknownArgumentType]
193
+ new_path = f'{path}.[{n}]' if path else f'[{n}]'
194
+ self._parse_data_structures(item, new_path)
195
+
196
+ @classmethod
197
+ def _extract_attributes(cls, info: FieldInfo | ComputedFieldInfo) -> dict[str, str]:
198
+ return {attr: str(value) for attr in cls._FIELD_ATTRIBUTES if (value := getattr(info, attr, None)) is not None}
107
199
 
108
200
 
109
201
  def _rootless_xml_elements(root: ElementTree.Element, indent: str | None) -> Iterator[str]:
pydantic_ai/mcp.py CHANGED
@@ -540,7 +540,7 @@ class MCPServerStdio(MCPServer):
540
540
  f'args={self.args!r}',
541
541
  ]
542
542
  if self.id:
543
- repr_args.append(f'id={self.id!r}')
543
+ repr_args.append(f'id={self.id!r}') # pragma: lax no cover
544
544
  return f'{self.__class__.__name__}({", ".join(repr_args)})'
545
545
 
546
546
  def __eq__(self, value: object, /) -> bool:
pydantic_ai/messages.py CHANGED
@@ -126,6 +126,7 @@ class FileUrl(ABC):
126
126
 
127
127
  Supported by:
128
128
  - `GoogleModel`: `VideoUrl.vendor_metadata` is used as `video_metadata`: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing
129
+ - `OpenAIChatModel`, `OpenAIResponsesModel`: `ImageUrl.vendor_metadata['detail']` is used as `detail` setting for images
129
130
  """
130
131
 
131
132
  _media_type: Annotated[str | None, pydantic.Field(alias='media_type', default=None, exclude=True)] = field(
@@ -471,6 +472,7 @@ class BinaryContent:
471
472
 
472
473
  Supported by:
473
474
  - `GoogleModel`: `BinaryContent.vendor_metadata` is used as `video_metadata`: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing
475
+ - `OpenAIChatModel`, `OpenAIResponsesModel`: `BinaryContent.vendor_metadata['detail']` is used as `detail` setting for images
474
476
  """
475
477
 
476
478
  kind: Literal['binary'] = 'binary'
@@ -1161,11 +1163,7 @@ class ModelResponse:
1161
1163
  if settings.include_content and part.content is not None: # pragma: no branch
1162
1164
  from .models.instrumented import InstrumentedModel
1163
1165
 
1164
- return_part['result'] = (
1165
- part.content
1166
- if isinstance(part.content, str)
1167
- else {k: InstrumentedModel.serialize_any(v) for k, v in part.content.items()}
1168
- )
1166
+ return_part['result'] = InstrumentedModel.serialize_any(part.content)
1169
1167
 
1170
1168
  parts.append(return_part)
1171
1169
  return parts
@@ -65,6 +65,8 @@ KnownModelName = TypeAliasType(
65
65
  'anthropic:claude-opus-4-20250514',
66
66
  'anthropic:claude-sonnet-4-0',
67
67
  'anthropic:claude-sonnet-4-20250514',
68
+ 'anthropic:claude-sonnet-4-5',
69
+ 'anthropic:claude-sonnet-4-5-20250929',
68
70
  'bedrock:amazon.titan-tg1-large',
69
71
  'bedrock:amazon.titan-text-lite-v1',
70
72
  'bedrock:amazon.titan-text-express-v1',
@@ -121,23 +123,6 @@ KnownModelName = TypeAliasType(
121
123
  'cerebras:qwen-3-32b',
122
124
  'cerebras:qwen-3-coder-480b',
123
125
  'cerebras:qwen-3-235b-a22b-thinking-2507',
124
- 'claude-3-5-haiku-20241022',
125
- 'claude-3-5-haiku-latest',
126
- 'claude-3-5-sonnet-20240620',
127
- 'claude-3-5-sonnet-20241022',
128
- 'claude-3-5-sonnet-latest',
129
- 'claude-3-7-sonnet-20250219',
130
- 'claude-3-7-sonnet-latest',
131
- 'claude-3-haiku-20240307',
132
- 'claude-3-opus-20240229',
133
- 'claude-3-opus-latest',
134
- 'claude-4-opus-20250514',
135
- 'claude-4-sonnet-20250514',
136
- 'claude-opus-4-0',
137
- 'claude-opus-4-1-20250805',
138
- 'claude-opus-4-20250514',
139
- 'claude-sonnet-4-0',
140
- 'claude-sonnet-4-20250514',
141
126
  'cohere:c4ai-aya-expanse-32b',
142
127
  'cohere:c4ai-aya-expanse-8b',
143
128
  'cohere:command',
@@ -163,54 +148,6 @@ KnownModelName = TypeAliasType(
163
148
  'google-vertex:gemini-2.5-flash',
164
149
  'google-vertex:gemini-2.5-flash-lite',
165
150
  'google-vertex:gemini-2.5-pro',
166
- 'gpt-3.5-turbo',
167
- 'gpt-3.5-turbo-0125',
168
- 'gpt-3.5-turbo-0301',
169
- 'gpt-3.5-turbo-0613',
170
- 'gpt-3.5-turbo-1106',
171
- 'gpt-3.5-turbo-16k',
172
- 'gpt-3.5-turbo-16k-0613',
173
- 'gpt-4',
174
- 'gpt-4-0125-preview',
175
- 'gpt-4-0314',
176
- 'gpt-4-0613',
177
- 'gpt-4-1106-preview',
178
- 'gpt-4-32k',
179
- 'gpt-4-32k-0314',
180
- 'gpt-4-32k-0613',
181
- 'gpt-4-turbo',
182
- 'gpt-4-turbo-2024-04-09',
183
- 'gpt-4-turbo-preview',
184
- 'gpt-4-vision-preview',
185
- 'gpt-4.1',
186
- 'gpt-4.1-2025-04-14',
187
- 'gpt-4.1-mini',
188
- 'gpt-4.1-mini-2025-04-14',
189
- 'gpt-4.1-nano',
190
- 'gpt-4.1-nano-2025-04-14',
191
- 'gpt-4o',
192
- 'gpt-4o-2024-05-13',
193
- 'gpt-4o-2024-08-06',
194
- 'gpt-4o-2024-11-20',
195
- 'gpt-4o-audio-preview',
196
- 'gpt-4o-audio-preview-2024-10-01',
197
- 'gpt-4o-audio-preview-2024-12-17',
198
- 'gpt-4o-audio-preview-2025-06-03',
199
- 'gpt-4o-mini',
200
- 'gpt-4o-mini-2024-07-18',
201
- 'gpt-4o-mini-audio-preview',
202
- 'gpt-4o-mini-audio-preview-2024-12-17',
203
- 'gpt-4o-mini-search-preview',
204
- 'gpt-4o-mini-search-preview-2025-03-11',
205
- 'gpt-4o-search-preview',
206
- 'gpt-4o-search-preview-2025-03-11',
207
- 'gpt-5',
208
- 'gpt-5-2025-08-07',
209
- 'gpt-5-chat-latest',
210
- 'gpt-5-mini',
211
- 'gpt-5-mini-2025-08-07',
212
- 'gpt-5-nano',
213
- 'gpt-5-nano-2025-08-07',
214
151
  'grok:grok-4',
215
152
  'grok:grok-4-0709',
216
153
  'grok:grok-3',
@@ -271,22 +208,6 @@ KnownModelName = TypeAliasType(
271
208
  'moonshotai:kimi-latest',
272
209
  'moonshotai:kimi-thinking-preview',
273
210
  'moonshotai:kimi-k2-0711-preview',
274
- 'o1',
275
- 'o1-2024-12-17',
276
- 'o1-mini',
277
- 'o1-mini-2024-09-12',
278
- 'o1-preview',
279
- 'o1-preview-2024-09-12',
280
- 'o1-pro',
281
- 'o1-pro-2025-03-19',
282
- 'o3',
283
- 'o3-2025-04-16',
284
- 'o3-deep-research',
285
- 'o3-deep-research-2025-06-26',
286
- 'o3-mini',
287
- 'o3-mini-2025-01-31',
288
- 'o3-pro',
289
- 'o3-pro-2025-06-10',
290
211
  'openai:chatgpt-4o-latest',
291
212
  'openai:codex-mini-latest',
292
213
  'openai:gpt-3.5-turbo',
@@ -54,7 +54,7 @@ _FINISH_REASON_MAP: dict[BetaStopReason, FinishReason] = {
54
54
 
55
55
 
56
56
  try:
57
- from anthropic import NOT_GIVEN, APIStatusError, AsyncStream
57
+ from anthropic import NOT_GIVEN, APIStatusError, AsyncStream, omit as OMIT
58
58
  from anthropic.types.beta import (
59
59
  BetaBase64PDFBlockParam,
60
60
  BetaBase64PDFSourceParam,
@@ -265,6 +265,10 @@ class AnthropicModel(Model):
265
265
  else:
266
266
  if not model_request_parameters.allow_text_output:
267
267
  tool_choice = {'type': 'any'}
268
+ if (thinking := model_settings.get('anthropic_thinking')) and thinking.get('type') == 'enabled':
269
+ raise UserError(
270
+ 'Anthropic does not support thinking and output tools at the same time. Use `output_type=PromptedOutput(...)` instead.'
271
+ )
268
272
  else:
269
273
  tool_choice = {'type': 'auto'}
270
274
 
@@ -281,18 +285,18 @@ class AnthropicModel(Model):
281
285
 
282
286
  return await self.client.beta.messages.create(
283
287
  max_tokens=model_settings.get('max_tokens', 4096),
284
- system=system_prompt or NOT_GIVEN,
288
+ system=system_prompt or OMIT,
285
289
  messages=anthropic_messages,
286
290
  model=self._model_name,
287
- tools=tools or NOT_GIVEN,
288
- tool_choice=tool_choice or NOT_GIVEN,
291
+ tools=tools or OMIT,
292
+ tool_choice=tool_choice or OMIT,
289
293
  stream=stream,
290
- thinking=model_settings.get('anthropic_thinking', NOT_GIVEN),
291
- stop_sequences=model_settings.get('stop_sequences', NOT_GIVEN),
292
- temperature=model_settings.get('temperature', NOT_GIVEN),
293
- top_p=model_settings.get('top_p', NOT_GIVEN),
294
+ thinking=model_settings.get('anthropic_thinking', OMIT),
295
+ stop_sequences=model_settings.get('stop_sequences', OMIT),
296
+ temperature=model_settings.get('temperature', OMIT),
297
+ top_p=model_settings.get('top_p', OMIT),
294
298
  timeout=model_settings.get('timeout', NOT_GIVEN),
295
- metadata=model_settings.get('anthropic_metadata', NOT_GIVEN),
299
+ metadata=model_settings.get('anthropic_metadata', OMIT),
296
300
  extra_headers=extra_headers,
297
301
  extra_body=model_settings.get('extra_body'),
298
302
  )
@@ -759,6 +763,8 @@ def _map_server_tool_use_block(item: BetaServerToolUseBlock, provider_name: str)
759
763
  args=cast(dict[str, Any], item.input) or None,
760
764
  tool_call_id=item.id,
761
765
  )
766
+ elif item.name in ('web_fetch', 'bash_code_execution', 'text_editor_code_execution'): # pragma: no cover
767
+ raise NotImplementedError(f'Anthropic built-in tool {item.name!r} is not currently supported.')
762
768
  else:
763
769
  assert_never(item.name)
764
770
 
@@ -51,6 +51,7 @@ from . import (
51
51
  try:
52
52
  from google.genai import Client
53
53
  from google.genai.types import (
54
+ BlobDict,
54
55
  CodeExecutionResult,
55
56
  CodeExecutionResultDict,
56
57
  ContentDict,
@@ -58,6 +59,7 @@ try:
58
59
  CountTokensConfigDict,
59
60
  ExecutableCode,
60
61
  ExecutableCodeDict,
62
+ FileDataDict,
61
63
  FinishReason as GoogleFinishReason,
62
64
  FunctionCallDict,
63
65
  FunctionCallingConfigDict,
@@ -79,6 +81,7 @@ try:
79
81
  ToolDict,
80
82
  ToolListUnionDict,
81
83
  UrlContextDict,
84
+ VideoMetadataDict,
82
85
  )
83
86
 
84
87
  from ..providers.google import GoogleProvider
@@ -525,17 +528,17 @@ class GoogleModel(Model):
525
528
  if isinstance(item, str):
526
529
  content.append({'text': item})
527
530
  elif isinstance(item, BinaryContent):
528
- # NOTE: The type from Google GenAI is incorrect, it should be `str`, not `bytes`.
529
- base64_encoded = base64.b64encode(item.data).decode('utf-8')
530
- inline_data_dict = {'inline_data': {'data': base64_encoded, 'mime_type': item.media_type}}
531
+ inline_data_dict: BlobDict = {'data': item.data, 'mime_type': item.media_type}
532
+ part_dict: PartDict = {'inline_data': inline_data_dict}
531
533
  if item.vendor_metadata:
532
- inline_data_dict['video_metadata'] = item.vendor_metadata
533
- content.append(inline_data_dict) # type: ignore
534
+ part_dict['video_metadata'] = cast(VideoMetadataDict, item.vendor_metadata)
535
+ content.append(part_dict)
534
536
  elif isinstance(item, VideoUrl) and item.is_youtube:
535
- file_data_dict = {'file_data': {'file_uri': item.url, 'mime_type': item.media_type}}
537
+ file_data_dict: FileDataDict = {'file_uri': item.url, 'mime_type': item.media_type}
538
+ part_dict: PartDict = {'file_data': file_data_dict}
536
539
  if item.vendor_metadata: # pragma: no branch
537
- file_data_dict['video_metadata'] = item.vendor_metadata
538
- content.append(file_data_dict) # type: ignore
540
+ part_dict['video_metadata'] = cast(VideoMetadataDict, item.vendor_metadata)
541
+ content.append(part_dict)
539
542
  elif isinstance(item, FileUrl):
540
543
  if item.force_download or (
541
544
  # google-gla does not support passing file urls directly, except for youtube videos
@@ -543,13 +546,15 @@ class GoogleModel(Model):
543
546
  self.system == 'google-gla'
544
547
  and not item.url.startswith(r'https://generativelanguage.googleapis.com/v1beta/files')
545
548
  ):
546
- downloaded_item = await download_item(item, data_format='base64')
547
- inline_data = {'data': downloaded_item['data'], 'mime_type': downloaded_item['data_type']}
548
- content.append({'inline_data': inline_data}) # type: ignore
549
+ downloaded_item = await download_item(item, data_format='bytes')
550
+ inline_data: BlobDict = {
551
+ 'data': downloaded_item['data'],
552
+ 'mime_type': downloaded_item['data_type'],
553
+ }
554
+ content.append({'inline_data': inline_data})
549
555
  else:
550
- content.append(
551
- {'file_data': {'file_uri': item.url, 'mime_type': item.media_type}}
552
- ) # pragma: lax no cover
556
+ file_data_dict: FileDataDict = {'file_uri': item.url, 'mime_type': item.media_type}
557
+ content.append({'file_data': file_data_dict}) # pragma: lax no cover
553
558
  else:
554
559
  assert_never(item)
555
560
  return content
@@ -578,7 +583,9 @@ class GeminiStreamedResponse(StreamedResponse):
578
583
  async for chunk in self._response:
579
584
  self._usage = _metadata_as_usage(chunk)
580
585
 
581
- assert chunk.candidates is not None
586
+ if not chunk.candidates:
587
+ continue # pragma: no cover
588
+
582
589
  candidate = chunk.candidates[0]
583
590
 
584
591
  if chunk.response_id: # pragma: no branch
@@ -610,7 +617,10 @@ class GeminiStreamedResponse(StreamedResponse):
610
617
  else: # pragma: no cover
611
618
  raise UnexpectedModelBehavior('Content field missing from streaming Gemini response', str(chunk))
612
619
 
613
- parts = candidate.content.parts or []
620
+ parts = candidate.content.parts
621
+ if not parts:
622
+ continue # pragma: no cover
623
+
614
624
  for part in parts:
615
625
  if part.thought_signature:
616
626
  signature = base64.b64encode(part.thought_signature).decode('utf-8')
@@ -822,7 +832,7 @@ def _metadata_as_usage(response: GenerateContentResponse) -> usage.RequestUsage:
822
832
  if not metadata_details:
823
833
  continue
824
834
  for detail in metadata_details:
825
- if not detail.modality or not detail.token_count: # pragma: no cover
835
+ if not detail.modality or not detail.token_count:
826
836
  continue
827
837
  details[f'{detail.modality.lower()}_{prefix}_tokens'] = detail.token_count
828
838
  if detail.modality != 'AUDIO':
@@ -9,6 +9,7 @@ from dataclasses import dataclass, field
9
9
  from typing import Any, Literal, cast
10
10
  from urllib.parse import urlparse
11
11
 
12
+ from genai_prices.types import PriceCalculation
12
13
  from opentelemetry._events import (
13
14
  Event, # pyright: ignore[reportPrivateImportUsage]
14
15
  EventLogger, # pyright: ignore[reportPrivateImportUsage]
@@ -169,6 +170,11 @@ class InstrumentationSettings:
169
170
  self.tokens_histogram = self.meter.create_histogram(
170
171
  **tokens_histogram_kwargs, # pyright: ignore
171
172
  )
173
+ self.cost_histogram = self.meter.create_histogram(
174
+ 'operation.cost',
175
+ unit='{USD}',
176
+ description='Monetary cost',
177
+ )
172
178
 
173
179
  def messages_to_otel_events(self, messages: list[ModelMessage]) -> list[Event]:
174
180
  """Convert a list of model messages to OpenTelemetry events.
@@ -302,6 +308,21 @@ class InstrumentationSettings:
302
308
  }
303
309
  )
304
310
 
311
+ def record_metrics(
312
+ self,
313
+ response: ModelResponse,
314
+ price_calculation: PriceCalculation | None,
315
+ attributes: dict[str, AttributeValue],
316
+ ):
317
+ for typ in ['input', 'output']:
318
+ if not (tokens := getattr(response.usage, f'{typ}_tokens', 0)): # pragma: no cover
319
+ continue
320
+ token_attributes = {**attributes, 'gen_ai.token.type': typ}
321
+ self.tokens_histogram.record(tokens, token_attributes)
322
+ if price_calculation:
323
+ cost = float(getattr(price_calculation, f'{typ}_price'))
324
+ self.cost_histogram.record(cost, token_attributes)
325
+
305
326
 
306
327
  GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system'
307
328
  GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model'
@@ -395,6 +416,7 @@ class InstrumentedModel(WrapperModel):
395
416
  system = cast(str, attributes[GEN_AI_SYSTEM_ATTRIBUTE])
396
417
 
397
418
  response_model = response.model_name or request_model
419
+ price_calculation = None
398
420
 
399
421
  def _record_metrics():
400
422
  metric_attributes = {
@@ -403,16 +425,7 @@ class InstrumentedModel(WrapperModel):
403
425
  'gen_ai.request.model': request_model,
404
426
  'gen_ai.response.model': response_model,
405
427
  }
406
- if response.usage.input_tokens: # pragma: no branch
407
- self.instrumentation_settings.tokens_histogram.record(
408
- response.usage.input_tokens,
409
- {**metric_attributes, 'gen_ai.token.type': 'input'},
410
- )
411
- if response.usage.output_tokens: # pragma: no branch
412
- self.instrumentation_settings.tokens_histogram.record(
413
- response.usage.output_tokens,
414
- {**metric_attributes, 'gen_ai.token.type': 'output'},
415
- )
428
+ self.instrumentation_settings.record_metrics(response, price_calculation, metric_attributes)
416
429
 
417
430
  nonlocal record_metrics
418
431
  record_metrics = _record_metrics
@@ -427,7 +440,7 @@ class InstrumentedModel(WrapperModel):
427
440
  'gen_ai.response.model': response_model,
428
441
  }
429
442
  try:
430
- attributes_to_set['operation.cost'] = float(response.cost().total_price)
443
+ price_calculation = response.cost()
431
444
  except LookupError:
432
445
  # The cost of this provider/model is unknown, which is common.
433
446
  pass
@@ -435,6 +448,9 @@ class InstrumentedModel(WrapperModel):
435
448
  warnings.warn(
436
449
  f'Failed to get cost from response: {type(e).__name__}: {e}', CostCalculationFailedWarning
437
450
  )
451
+ else:
452
+ attributes_to_set['operation.cost'] = float(price_calculation.total_price)
453
+
438
454
  if response.provider_response_id is not None:
439
455
  attributes_to_set['gen_ai.response.id'] = response.provider_response_id
440
456
  if response.finish_reason is not None:
@@ -526,16 +526,20 @@ class OpenAIChatModel(Model):
526
526
 
527
527
  choice = response.choices[0]
528
528
  items: list[ModelResponsePart] = []
529
+
529
530
  # The `reasoning_content` field is only present in DeepSeek models.
530
531
  # https://api-docs.deepseek.com/guides/reasoning_model
531
532
  if reasoning_content := getattr(choice.message, 'reasoning_content', None):
532
533
  items.append(ThinkingPart(id='reasoning_content', content=reasoning_content, provider_name=self.system))
533
534
 
534
- # NOTE: We don't currently handle OpenRouter `reasoning_details`:
535
- # - https://openrouter.ai/docs/use-cases/reasoning-tokens#preserving-reasoning-blocks
536
- # NOTE: We don't currently handle OpenRouter/gpt-oss `reasoning`:
535
+ # The `reasoning` field is only present in gpt-oss via Ollama and OpenRouter.
537
536
  # - https://cookbook.openai.com/articles/gpt-oss/handle-raw-cot#chat-completions-api
538
537
  # - https://openrouter.ai/docs/use-cases/reasoning-tokens#basic-usage-with-reasoning-tokens
538
+ if reasoning := getattr(choice.message, 'reasoning', None):
539
+ items.append(ThinkingPart(id='reasoning', content=reasoning, provider_name=self.system))
540
+
541
+ # NOTE: We don't currently handle OpenRouter `reasoning_details`:
542
+ # - https://openrouter.ai/docs/use-cases/reasoning-tokens#preserving-reasoning-blocks
539
543
  # If you need this, please file an issue.
540
544
 
541
545
  vendor_details: dict[str, Any] = {}
@@ -753,12 +757,16 @@ class OpenAIChatModel(Model):
753
757
  if isinstance(item, str):
754
758
  content.append(ChatCompletionContentPartTextParam(text=item, type='text'))
755
759
  elif isinstance(item, ImageUrl):
756
- image_url = ImageURL(url=item.url)
760
+ image_url: ImageURL = {'url': item.url}
761
+ if metadata := item.vendor_metadata:
762
+ image_url['detail'] = metadata.get('detail', 'auto')
757
763
  content.append(ChatCompletionContentPartImageParam(image_url=image_url, type='image_url'))
758
764
  elif isinstance(item, BinaryContent):
759
765
  base64_encoded = base64.b64encode(item.data).decode('utf-8')
760
766
  if item.is_image:
761
- image_url = ImageURL(url=f'data:{item.media_type};base64,{base64_encoded}')
767
+ image_url: ImageURL = {'url': f'data:{item.media_type};base64,{base64_encoded}'}
768
+ if metadata := item.vendor_metadata:
769
+ image_url['detail'] = metadata.get('detail', 'auto')
762
770
  content.append(ChatCompletionContentPartImageParam(image_url=image_url, type='image_url'))
763
771
  elif item.is_audio:
764
772
  assert item.format in ('wav', 'mp3')
@@ -1383,11 +1391,17 @@ class OpenAIResponsesModel(Model):
1383
1391
  elif isinstance(item, BinaryContent):
1384
1392
  base64_encoded = base64.b64encode(item.data).decode('utf-8')
1385
1393
  if item.is_image:
1394
+ detail: Literal['auto', 'low', 'high'] = 'auto'
1395
+ if metadata := item.vendor_metadata:
1396
+ detail = cast(
1397
+ Literal['auto', 'low', 'high'],
1398
+ metadata.get('detail', 'auto'),
1399
+ )
1386
1400
  content.append(
1387
1401
  responses.ResponseInputImageParam(
1388
1402
  image_url=f'data:{item.media_type};base64,{base64_encoded}',
1389
1403
  type='input_image',
1390
- detail='auto',
1404
+ detail=detail,
1391
1405
  )
1392
1406
  )
1393
1407
  elif item.is_document:
@@ -1406,8 +1420,15 @@ class OpenAIResponsesModel(Model):
1406
1420
  else: # pragma: no cover
1407
1421
  raise RuntimeError(f'Unsupported binary content type: {item.media_type}')
1408
1422
  elif isinstance(item, ImageUrl):
1423
+ detail: Literal['auto', 'low', 'high'] = 'auto'
1424
+ if metadata := item.vendor_metadata:
1425
+ detail = cast(Literal['auto', 'low', 'high'], metadata.get('detail', 'auto'))
1409
1426
  content.append(
1410
- responses.ResponseInputImageParam(image_url=item.url, type='input_image', detail='auto')
1427
+ responses.ResponseInputImageParam(
1428
+ image_url=item.url,
1429
+ type='input_image',
1430
+ detail=detail,
1431
+ )
1411
1432
  )
1412
1433
  elif isinstance(item, AudioUrl): # pragma: no cover
1413
1434
  downloaded_item = await download_item(item, data_format='base64_uri', type_format='extension')
@@ -1492,6 +1513,17 @@ class OpenAIStreamedResponse(StreamedResponse):
1492
1513
  provider_name=self.provider_name,
1493
1514
  )
1494
1515
 
1516
+ # The `reasoning` field is only present in gpt-oss via Ollama and OpenRouter.
1517
+ # - https://cookbook.openai.com/articles/gpt-oss/handle-raw-cot#chat-completions-api
1518
+ # - https://openrouter.ai/docs/use-cases/reasoning-tokens#basic-usage-with-reasoning-tokens
1519
+ if reasoning := getattr(choice.delta, 'reasoning', None): # pragma: no cover
1520
+ yield self._parts_manager.handle_thinking_delta(
1521
+ vendor_part_id='reasoning',
1522
+ id='reasoning',
1523
+ content=reasoning,
1524
+ provider_name=self.provider_name,
1525
+ )
1526
+
1495
1527
  for dtc in choice.delta.tool_calls or []:
1496
1528
  maybe_event = self._parts_manager.handle_tool_call_delta(
1497
1529
  vendor_part_id=dtc.index,
pydantic_ai/output.py CHANGED
@@ -11,7 +11,7 @@ from typing_extensions import TypeAliasType, TypeVar, deprecated
11
11
 
12
12
  from . import _utils
13
13
  from .messages import ToolCallPart
14
- from .tools import DeferredToolRequests, RunContext, ToolDefinition
14
+ from .tools import DeferredToolRequests, ObjectJsonSchema, RunContext, ToolDefinition
15
15
 
16
16
  __all__ = (
17
17
  # classes
@@ -20,6 +20,7 @@ __all__ = (
20
20
  'PromptedOutput',
21
21
  'TextOutput',
22
22
  'StructuredDict',
23
+ 'OutputObjectDefinition',
23
24
  # types
24
25
  'OutputDataT',
25
26
  'OutputMode',
@@ -242,6 +243,16 @@ class PromptedOutput(Generic[OutputDataT]):
242
243
  self.template = template
243
244
 
244
245
 
246
+ @dataclass
247
+ class OutputObjectDefinition:
248
+ """Definition of an output object used for structured output generation."""
249
+
250
+ json_schema: ObjectJsonSchema
251
+ name: str | None = None
252
+ description: str | None = None
253
+ strict: bool | None = None
254
+
255
+
245
256
  @dataclass
246
257
  class TextOutput(Generic[OutputDataT]):
247
258
  """Marker class to use text output for an output function taking a string argument.
@@ -10,4 +10,6 @@ def harmony_model_profile(model_name: str) -> ModelProfile | None:
10
10
  See <https://cookbook.openai.com/articles/openai-harmony> for more details.
11
11
  """
12
12
  profile = openai_model_profile(model_name)
13
- return OpenAIModelProfile(openai_supports_tool_choice_required=False).update(profile)
13
+ return OpenAIModelProfile(
14
+ openai_supports_tool_choice_required=False, ignore_streamed_leading_whitespace=True
15
+ ).update(profile)
@@ -11,6 +11,7 @@ from pydantic_ai.profiles import ModelProfile
11
11
  from pydantic_ai.profiles.cohere import cohere_model_profile
12
12
  from pydantic_ai.profiles.deepseek import deepseek_model_profile
13
13
  from pydantic_ai.profiles.google import google_model_profile
14
+ from pydantic_ai.profiles.harmony import harmony_model_profile
14
15
  from pydantic_ai.profiles.meta import meta_model_profile
15
16
  from pydantic_ai.profiles.mistral import mistral_model_profile
16
17
  from pydantic_ai.profiles.openai import OpenAIJsonSchemaTransformer, OpenAIModelProfile
@@ -50,6 +51,7 @@ class OllamaProvider(Provider[AsyncOpenAI]):
50
51
  'deepseek': deepseek_model_profile,
51
52
  'mistral': mistral_model_profile,
52
53
  'command': cohere_model_profile,
54
+ 'gpt-oss': harmony_model_profile,
53
55
  }
54
56
 
55
57
  profile = None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pydantic-ai-slim
3
- Version: 1.0.9
3
+ Version: 1.0.11
4
4
  Summary: Agent Framework / shim to use Pydantic with LLMs, slim package
5
5
  Project-URL: Homepage, https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim
6
6
  Project-URL: Source, https://github.com/pydantic/pydantic-ai/tree/main/pydantic_ai_slim
@@ -29,11 +29,11 @@ Classifier: Topic :: Internet
29
29
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
30
30
  Requires-Python: >=3.10
31
31
  Requires-Dist: exceptiongroup; python_version < '3.11'
32
- Requires-Dist: genai-prices>=0.0.23
32
+ Requires-Dist: genai-prices>=0.0.28
33
33
  Requires-Dist: griffe>=1.3.2
34
34
  Requires-Dist: httpx>=0.27
35
35
  Requires-Dist: opentelemetry-api>=1.28.0
36
- Requires-Dist: pydantic-graph==1.0.9
36
+ Requires-Dist: pydantic-graph==1.0.11
37
37
  Requires-Dist: pydantic>=2.10
38
38
  Requires-Dist: typing-inspection>=0.4.0
39
39
  Provides-Extra: a2a
@@ -42,7 +42,7 @@ Provides-Extra: ag-ui
42
42
  Requires-Dist: ag-ui-protocol>=0.1.8; extra == 'ag-ui'
43
43
  Requires-Dist: starlette>=0.45.3; extra == 'ag-ui'
44
44
  Provides-Extra: anthropic
45
- Requires-Dist: anthropic>=0.61.0; extra == 'anthropic'
45
+ Requires-Dist: anthropic>=0.69.0; extra == 'anthropic'
46
46
  Provides-Extra: bedrock
47
47
  Requires-Dist: boto3>=1.39.0; extra == 'bedrock'
48
48
  Provides-Extra: cli
@@ -57,7 +57,7 @@ Requires-Dist: dbos>=1.14.0; extra == 'dbos'
57
57
  Provides-Extra: duckduckgo
58
58
  Requires-Dist: ddgs>=9.0.0; extra == 'duckduckgo'
59
59
  Provides-Extra: evals
60
- Requires-Dist: pydantic-evals==1.0.9; extra == 'evals'
60
+ Requires-Dist: pydantic-evals==1.0.11; extra == 'evals'
61
61
  Provides-Extra: google
62
62
  Requires-Dist: google-genai>=1.31.0; extra == 'google'
63
63
  Provides-Extra: groq
@@ -77,7 +77,7 @@ Requires-Dist: tenacity>=8.2.3; extra == 'retries'
77
77
  Provides-Extra: tavily
78
78
  Requires-Dist: tavily-python>=0.5.0; extra == 'tavily'
79
79
  Provides-Extra: temporal
80
- Requires-Dist: temporalio==1.17.0; extra == 'temporal'
80
+ Requires-Dist: temporalio==1.18.0; extra == 'temporal'
81
81
  Provides-Extra: vertexai
82
82
  Requires-Dist: google-auth>=2.36.0; extra == 'vertexai'
83
83
  Requires-Dist: requests>=2.32.2; extra == 'vertexai'
@@ -1,13 +1,13 @@
1
1
  pydantic_ai/__init__.py,sha256=CfqGPSjKlDl5iw1L48HbELsDuzxIzBFnFnovI_GcFWA,2083
2
2
  pydantic_ai/__main__.py,sha256=Q_zJU15DUA01YtlJ2mnaLCoId2YmgmreVEERGuQT-Y0,132
3
3
  pydantic_ai/_a2a.py,sha256=2Hopcyl6o6U91eVkd7iAbEPYA5f0hJb8A5_fwMC0UfM,12168
4
- pydantic_ai/_agent_graph.py,sha256=NAl4C6VPptiSFMSRwWYPEkSu_-NtRdNme-nVzwghrm0,52571
4
+ pydantic_ai/_agent_graph.py,sha256=c5rdUxBcCau2UgumvR_4TBXvpAMeg5wjvOi0sk3YSmo,53217
5
5
  pydantic_ai/_cli.py,sha256=n1MX7p-UKH6ZWPNwiGPZTVcXYhXG8OiJIuNMeYX5k2M,14053
6
- pydantic_ai/_function_schema.py,sha256=olbmUMQoQV5qKV4j0-cOnhcTINz4uYyeDqMyusrFRtY,11234
6
+ pydantic_ai/_function_schema.py,sha256=UnDGh7Wh5z70pEaRujXF_hKsSibQdN2ywI6lZGz3LUo,11663
7
7
  pydantic_ai/_griffe.py,sha256=BphvTL00FHxsSY56GM-bNyCOdwrpL0T3LbDQITWUK_Q,5280
8
8
  pydantic_ai/_mcp.py,sha256=PuvwnlLjv7YYOa9AZJCrklevBug99zGMhwJCBGG7BHQ,5626
9
9
  pydantic_ai/_otel_messages.py,sha256=SsMpbyI1fIISOck_wQcZJPIOei8lOmvwARkdPSCx8y8,1650
10
- pydantic_ai/_output.py,sha256=phJ9AQYUlhQhAVikL0FpPn_Vm05V_yK3VYmCUUtH778,38296
10
+ pydantic_ai/_output.py,sha256=e6KBPnzOcYj13XmMaWOH6Xm1vxVG97U1ljuwuVRQaY8,38153
11
11
  pydantic_ai/_parts_manager.py,sha256=QRfZTk21tCO6jEu8hF0qZLEsyUzvu0C6-qkiFhnbqxI,21443
12
12
  pydantic_ai/_run_context.py,sha256=142KI0Sy5uMox4VMBkkIgkBl4uCwZvI9HcXJKdnsWBU,2108
13
13
  pydantic_ai/_system_prompt.py,sha256=WdDW_DTGHujcFFaK-J7J6mA4ZDJZ0IOKpyizJA-1Y5Q,1142
@@ -18,10 +18,10 @@ pydantic_ai/ag_ui.py,sha256=X3b4P_IraypCE3r-L2ETIo8G951A1MDdP4P5TQ8Fces,32067
18
18
  pydantic_ai/builtin_tools.py,sha256=DUzhHNUtWJPhaPQ7iV4E1jNImBO0DqpSLtA_HuHLaKw,3623
19
19
  pydantic_ai/direct.py,sha256=zMsz6poVgEq7t7L_8FWM6hmKdqTzjyQYL5xzQt_59Us,14951
20
20
  pydantic_ai/exceptions.py,sha256=zsXZMKf2BJuVsfuHl1fWTkogLU37bd4yq7D6BKHAzVs,4968
21
- pydantic_ai/format_prompt.py,sha256=37imBG2Fgpn-_RfAFalOX8Xc_XpGH2gY9tnhJDvxfk8,4243
22
- pydantic_ai/mcp.py,sha256=N1X5zldNeNJmH9EHnccLxXU4Pw7tBCdxFJzzbTOVAnE,34778
23
- pydantic_ai/messages.py,sha256=f26gyrPeMKIjLpDHgUWOzEZFXJgglGYJVIyeYUE-MXA,57554
24
- pydantic_ai/output.py,sha256=wzNgVKJgxyXtSH-uNbRxIaUNLidxlQcwWYT2o1gY2hE,12037
21
+ pydantic_ai/format_prompt.py,sha256=qQ9zv6PJR9D4FTII6gD3_bSOHYymhRYVIxhPMscxeLI,9528
22
+ pydantic_ai/mcp.py,sha256=VBqPgW-Mr3QQ1gt-sY3IWeP6_XApl5NfCrJs4OL8WEI,34802
23
+ pydantic_ai/messages.py,sha256=-t5sbnQVEGeo0e-mTxNdV8wLNtFQvSlHgcpKyza05Uk,57635
24
+ pydantic_ai/output.py,sha256=esyNK-56j_r7dUiPyzsvWtPppX2N9fbboNq-1x5CQaQ,12337
25
25
  pydantic_ai/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
26
  pydantic_ai/result.py,sha256=eoQ6VJPvXVNReRhErOytK3-2tiy9FV6LIwywyh7DSzo,26247
27
27
  pydantic_ai/retries.py,sha256=QM4oDA9DG-Y2qP06fbCp8Dqq8ups40Rr4HYjAOlbNyM,14650
@@ -29,7 +29,7 @@ pydantic_ai/run.py,sha256=wHlWl4CXIHLcgo2R8PlsU3Pjn0vuMLFfP8D6Fbany-Y,15097
29
29
  pydantic_ai/settings.py,sha256=0mr6KudxKKjTG8e3nsv_8vDLxNhu_1-WvefCOzCGSYM,3565
30
30
  pydantic_ai/tools.py,sha256=dCecmJtRkF1ioqFYbfT00XGGqzGB4PPO9n6IrHCQtnc,20343
31
31
  pydantic_ai/usage.py,sha256=KuDwSvWCzV5O9fPeEy5lUg2OhPq2eZFEFk2vYCA_DwA,14060
32
- pydantic_ai/agent/__init__.py,sha256=HH0bJXzNkpfzv99MMYkHIBy8_ArpETqNF6yugkTjqu8,62542
32
+ pydantic_ai/agent/__init__.py,sha256=Ceckz-CDtBsFo7pMm4LRKKTVOQkPZF-DIwGBbZCxSdQ,62684
33
33
  pydantic_ai/agent/abstract.py,sha256=fL2nD5XgLHfmva6t-foBENpLHV_WYTUWLGBKU-l8stM,44622
34
34
  pydantic_ai/agent/wrapper.py,sha256=lx0NcM8MX_MoNm0oiPFDH2Cod78N5ONcerKcpJQeJes,9425
35
35
  pydantic_ai/common_tools/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
@@ -52,20 +52,20 @@ pydantic_ai/durable_exec/temporal/_toolset.py,sha256=bnMbmR8JmBjBeWGaAMtgWP9Kb93
52
52
  pydantic_ai/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
53
53
  pydantic_ai/ext/aci.py,sha256=sUllKDNO-LOMurbFgxwRHuzNlBkSa3aVBqXfEm-A_vo,2545
54
54
  pydantic_ai/ext/langchain.py,sha256=iLVEZv1kcLkdIHo3us2yfdi0kVqyJ6qTaCt9BoLWm4k,2335
55
- pydantic_ai/models/__init__.py,sha256=TwCSdRVEfNK2M241tMoczcZzkHjnPs0xNIy6AwxijYs,36379
56
- pydantic_ai/models/anthropic.py,sha256=yhIg2LfFYqsvwfIgGQ9T4Fy_gCqElyB2SI1Ja4P9FVE,36546
55
+ pydantic_ai/models/__init__.py,sha256=ooszfzxleH1MMY47N7P8CVVO7Saf4TtgNm7HVuni4mQ,34038
56
+ pydantic_ai/models/anthropic.py,sha256=GWrx7xa6FcgmjhDyTFH27kQPwOi2Nf8eykv0lC7sdVA,37050
57
57
  pydantic_ai/models/bedrock.py,sha256=wHo65QNEsfsb1UaUv_TpvJ0WrgFoKoegB6I3eDVnORI,33393
58
58
  pydantic_ai/models/cohere.py,sha256=uQLynz-zWciZBHuvkm8HxJyTOee1bs3pSka-x-56a98,13668
59
59
  pydantic_ai/models/fallback.py,sha256=XJ74wRxVT4dF0uewHH3is9I-zcLBK8KFIhpK3BB6mRw,5526
60
60
  pydantic_ai/models/function.py,sha256=aTaRMul7-pm__uxqoJLa2e3_73eXeq6sRVLdj1BXX88,15518
61
61
  pydantic_ai/models/gemini.py,sha256=DYEaOnwGmo9FUGVkRRrydGuQwYhnO-Cq5grTurLWgb4,39376
62
- pydantic_ai/models/google.py,sha256=jMJEPHnrsdHSFSuhobttQk92jxXu6ykIEfPC4VXA_Gg,39182
62
+ pydantic_ai/models/google.py,sha256=uVGqhjDntgoE1ALQ6DbafarjKiXKdtreR24Xi6pVeyI,39368
63
63
  pydantic_ai/models/groq.py,sha256=lQIQHuFhvzoHFubXIcA3B4DohW7DnpGrPcrN6j9yuck,29118
64
64
  pydantic_ai/models/huggingface.py,sha256=f1tZObCJkcbiUCwNoPyuiaRaGYuj0GBFmbA8yFd-tHY,21176
65
- pydantic_ai/models/instrumented.py,sha256=DCnyG7HXgV-W2EWac8oZb2A8PL8yarXeU7Rt97l4w_s,21421
65
+ pydantic_ai/models/instrumented.py,sha256=4GXBNLjzs7s9kjcN_d4S3Wn3IgotNhIpCntAqF1Rrts,21863
66
66
  pydantic_ai/models/mcp_sampling.py,sha256=qnLCO3CB5bNQ86SpWRA-CSSOVcCCLPwjHtcNFvW9wHs,3461
67
67
  pydantic_ai/models/mistral.py,sha256=ru8EHwFS0xZBN6s1tlssUdjxjQyjB9L_8kFH7qq5U_g,33654
68
- pydantic_ai/models/openai.py,sha256=JTYxqvG7YQmEJzPrxSwBVOMqDxUbEKUN4oqiUBqK4Gc,87796
68
+ pydantic_ai/models/openai.py,sha256=cKPe53DhB2ci_JkJleI-n-WemAuBJr_UNUMIKlzO6w4,89579
69
69
  pydantic_ai/models/test.py,sha256=1kBwi7pSUt9_K1U-hokOilplxJWPQ3KRKH_s8bYmt_s,19969
70
70
  pydantic_ai/models/wrapper.py,sha256=9MeHW7mXPsEK03IKL0rtjeX6QgXyZROOOzLh72GiX2k,2148
71
71
  pydantic_ai/profiles/__init__.py,sha256=V6uGAVJuIaYRuZOQjkdIyFfDKD5py18RC98njnHOFug,3293
@@ -77,7 +77,7 @@ pydantic_ai/profiles/deepseek.py,sha256=JDwfkr-0YovlB3jEKk7dNFvepxNf_YuLgLkGCtyX
77
77
  pydantic_ai/profiles/google.py,sha256=cd5zwtx0MU1Xwm8c-oqi2_OJ2-PMJ8Vy23mxvSJF7ik,4856
78
78
  pydantic_ai/profiles/grok.py,sha256=nBOxOCYCK9aiLmz2Q-esqYhotNbbBC1boAoOYIk1tVw,211
79
79
  pydantic_ai/profiles/groq.py,sha256=jD_vG6M5q_uwLmJgkPavWWhGCqo3HvT_4UYfwzC1BMU,682
80
- pydantic_ai/profiles/harmony.py,sha256=_81tOGOYGTH3Za67jjtdINvASTTM5_CTyc1Ej2KHJQw,500
80
+ pydantic_ai/profiles/harmony.py,sha256=HKOQ1QUBd9jLLabO9jMCq97d3pgAzd3Y7c_jiwPFS2s,555
81
81
  pydantic_ai/profiles/meta.py,sha256=JdZcpdRWx8PY1pU9Z2i_TYtA0Cpbg23xyFrV7eXnooY,309
82
82
  pydantic_ai/profiles/mistral.py,sha256=ll01PmcK3szwlTfbaJLQmfd0TADN8lqjov9HpPJzCMQ,217
83
83
  pydantic_ai/profiles/moonshotai.py,sha256=e1RJnbEvazE6aJAqfmYLYGNtwNwg52XQDRDkcLrv3fU,272
@@ -103,7 +103,7 @@ pydantic_ai/providers/huggingface.py,sha256=_Bvi2qdbOB8E9mhiJX3fVoUDZWPCTduCFASZ
103
103
  pydantic_ai/providers/litellm.py,sha256=3hTCjHWRG_1c4S9JSNm0BDBDi4q6BVVZ3OLSXhTndNM,5079
104
104
  pydantic_ai/providers/mistral.py,sha256=pHcWHb2Wf9ZcqQl_Lp84ZvepO0Hmyb1CiqCTbur9S-s,3083
105
105
  pydantic_ai/providers/moonshotai.py,sha256=LwasmxCZCPkq1pb1uDtZTEb_nE55bAtX3QXgLmuNlHE,3260
106
- pydantic_ai/providers/ollama.py,sha256=_bxons0p8g0RSPNV8iq3AScVS1ym27QTW4zhDqSakgY,4633
106
+ pydantic_ai/providers/ollama.py,sha256=wSwB2eh2F5oUwHhdvvN3tZkzc1I8siojKl5NI27M6AI,4742
107
107
  pydantic_ai/providers/openai.py,sha256=SKRsYRUW_zu24iKAM7KJ-6j8GQDIjjxll4AWY1uB3Vs,3410
108
108
  pydantic_ai/providers/openrouter.py,sha256=PXGgHPtlQQHKFaSnmiswWZ3dTvmT9PAg-NvfRYGjrPw,4154
109
109
  pydantic_ai/providers/together.py,sha256=Dln_NgCul1XVOQtNaYvqWrNjOWj9XzA8n4NwNMKkbLk,3450
@@ -120,8 +120,8 @@ pydantic_ai/toolsets/prefixed.py,sha256=0KwcDkW8OM36ZUsOLVP5h-Nj2tPq78L3_E2c-1Fb
120
120
  pydantic_ai/toolsets/prepared.py,sha256=Zjfz6S8In6PBVxoKFN9sKPN984zO6t0awB7Lnq5KODw,1431
121
121
  pydantic_ai/toolsets/renamed.py,sha256=JuLHpi-hYPiSPlaTpN8WiXLiGsywYK0axi2lW2Qs75k,1637
122
122
  pydantic_ai/toolsets/wrapper.py,sha256=KRzF1p8dncHbva8CE6Ud-IC5E_aygIHlwH5atXK55k4,1673
123
- pydantic_ai_slim-1.0.9.dist-info/METADATA,sha256=vsOF2zsC5Bve4LZynrAVozutKpJFxMpr2E2px588Pgc,4628
124
- pydantic_ai_slim-1.0.9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
125
- pydantic_ai_slim-1.0.9.dist-info/entry_points.txt,sha256=kbKxe2VtDCYS06hsI7P3uZGxcVC08-FPt1rxeiMpIps,50
126
- pydantic_ai_slim-1.0.9.dist-info/licenses/LICENSE,sha256=vA6Jc482lEyBBuGUfD1pYx-cM7jxvLYOxPidZ30t_PQ,1100
127
- pydantic_ai_slim-1.0.9.dist-info/RECORD,,
123
+ pydantic_ai_slim-1.0.11.dist-info/METADATA,sha256=DTxapfIdQXo-SYga_J5A8841fU5NK-7eDfwF4BQhLsU,4631
124
+ pydantic_ai_slim-1.0.11.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
125
+ pydantic_ai_slim-1.0.11.dist-info/entry_points.txt,sha256=kbKxe2VtDCYS06hsI7P3uZGxcVC08-FPt1rxeiMpIps,50
126
+ pydantic_ai_slim-1.0.11.dist-info/licenses/LICENSE,sha256=vA6Jc482lEyBBuGUfD1pYx-cM7jxvLYOxPidZ30t_PQ,1100
127
+ pydantic_ai_slim-1.0.11.dist-info/RECORD,,