Skip to content

pydantic_ai.messages

The structure of ModelMessage can be shown as a graph:

graph RL
    SystemPromptPart(SystemPromptPart) --- ModelRequestPart
    UserPromptPart(UserPromptPart) --- ModelRequestPart
    ToolReturnPart(ToolReturnPart) --- ModelRequestPart
    RetryPromptPart(RetryPromptPart) --- ModelRequestPart
    TextPart(TextPart) --- ModelResponsePart
    ToolCallPart(ToolCallPart) --- ModelResponsePart
    ThinkingPart(ThinkingPart) --- ModelResponsePart
    ModelRequestPart("ModelRequestPart<br>(Union)") --- ModelRequest
    ModelRequest("ModelRequest(parts=list[...])") --- ModelMessage
    ModelResponsePart("ModelResponsePart<br>(Union)") --- ModelResponse
    ModelResponse("ModelResponse(parts=list[...])") --- ModelMessage("ModelMessage<br>(Union)")

FinishReason module-attribute

FinishReason: TypeAlias = Literal[
    "stop", "length", "content_filter", "tool_call", "error"
]

Reason the model finished generating the response, normalized to OpenTelemetry values.

ModelResponseState module-attribute

ModelResponseState: TypeAlias = Literal[
    "complete", "incomplete", "interrupted"
]

Lifecycle state of a model response.

  • 'complete': the response has been fully received from the model.
  • 'incomplete': the response is still being streamed and may receive more parts. Yielded by [AgentStream.response][pydantic_ai.result.AgentStream.response] and StreamedRunResult.stream_response while iteration is in flight.
  • 'interrupted': streaming was explicitly stopped via StreamedRunResult.cancel() before the model finished generating.

ModelRequestState module-attribute

ModelRequestState: TypeAlias = Literal[
    "complete", "interrupted"
]

Lifecycle state of a model request.

ForceDownloadMode module-attribute

ForceDownloadMode: TypeAlias = bool | Literal["allow-local"]

Type for the force_download parameter on FileUrl subclasses.

  • False: The URL is sent directly to providers that support it. For providers that don't, the file is downloaded with SSRF protection (blocks private IPs and cloud metadata).
  • True: The file is always downloaded with SSRF protection (blocks private IPs and cloud metadata).
  • 'allow-local': The file is always downloaded, allowing private IPs but still blocking cloud metadata.

ProviderDetailsDelta module-attribute

ProviderDetailsDelta: TypeAlias = (
    dict[str, Any]
    | Callable[[dict[str, Any] | None], dict[str, Any]]
    | None
)

Type for provider_details input: can be a static dict, a callback to update existing details, or None.

SystemPromptPart dataclass

A system prompt, generally written by the application developer.

This gives the model context and guidance on how to respond.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
@dataclass(repr=False)
class SystemPromptPart:
    """A system prompt, generally written by the application developer.

    This gives the model context and guidance on how to respond.
    """

    content: str
    """The content of the prompt."""

    _: KW_ONLY

    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp of the prompt."""

    dynamic_ref: str | None = None
    """The ref of the dynamic system prompt function that generated this part.

    Only set if system prompt is dynamic, see [`system_prompt`][pydantic_ai.agent.Agent.system_prompt] for more information.
    """

    part_kind: Literal['system-prompt'] = 'system-prompt'
    """Part type identifier, this is available on all parts as a discriminator."""

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        return [_otel_messages.TextPart(type='text', **{'content': self.content} if settings.include_content else {})]

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str

The content of the prompt.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp of the prompt.

dynamic_ref class-attribute instance-attribute

dynamic_ref: str | None = None

The ref of the dynamic system prompt function that generated this part.

Only set if system prompt is dynamic, see system_prompt for more information.

part_kind class-attribute instance-attribute

part_kind: Literal['system-prompt'] = 'system-prompt'

Part type identifier, this is available on all parts as a discriminator.

FileUrl

Bases: ABC

Abstract base class for any URL-based file.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class FileUrl(ABC):
    """Abstract base class for any URL-based file."""

    url: str
    """The URL of the file."""

    _: KW_ONLY

    force_download: ForceDownloadMode = False
    """Controls whether the file is downloaded and how SSRF protection is applied:

    * If `False`, the URL is sent directly to providers that support it. For providers that don't,
      the file is downloaded with SSRF protection (blocks private IPs and cloud metadata).
    * If `True`, the file is always downloaded with SSRF protection (blocks private IPs and cloud metadata).
    * If `'allow-local'`, the file is always downloaded, allowing private IPs but still blocking cloud metadata.
    """

    vendor_metadata: dict[str, Any] | None = None
    """Vendor-specific metadata for the file.

    Supported by:
    - `GoogleModel`: `VideoUrl.vendor_metadata` is used as `video_metadata`: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing
    - `OpenAIChatModel`, `OpenAIResponsesModel`: `ImageUrl.vendor_metadata['detail']` is used as `detail` setting for images
    - `XaiModel`: `ImageUrl.vendor_metadata['detail']` is used as `detail` setting for images
    """

    _media_type: Annotated[str | None, pydantic.Field(alias='media_type', default=None, exclude=True)] = field(
        compare=False, default=None
    )

    _identifier: Annotated[str | None, pydantic.Field(alias='identifier', default=None, exclude=True)] = field(
        compare=False, default=None
    )

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the `media_type` and `identifier` aliases.
    def __init__(
        self,
        url: str,
        *,
        media_type: str | None = None,
        identifier: str | None = None,
        force_download: ForceDownloadMode = False,
        vendor_metadata: dict[str, Any] | None = None,
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    @pydantic.computed_field
    @property
    def media_type(self) -> str:
        """Return the media type of the file, based on the URL or the provided `media_type`."""
        return self._media_type or self._infer_media_type()

    @pydantic.computed_field
    @property
    def identifier(self) -> str:
        """The identifier of the file, such as a unique ID.

        This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument,
        and the tool can look up the file in question by iterating over the message history and finding the matching `FileUrl`.

        This identifier is only automatically passed to the model when the `FileUrl` is returned by a tool.
        If you're passing the `FileUrl` as a user message, it's up to you to include a separate text part with the identifier,
        e.g. "This is file <identifier>:" preceding the `FileUrl`.

        It's also included in inline-text delimiters for providers that require inlining text documents, so the model can
        distinguish multiple files.
        """
        return self._identifier or _multi_modal_content_identifier(self.url)

    @abstractmethod
    def _infer_media_type(self) -> str:
        """Infer the media type of the file based on the URL."""
        raise NotImplementedError

    @property
    @abstractmethod
    def format(self) -> str:
        """The file format."""
        raise NotImplementedError

    __repr__ = _utils.dataclasses_no_defaults_repr

url instance-attribute

url: str

The URL of the file.

force_download class-attribute instance-attribute

force_download: ForceDownloadMode = False

Controls whether the file is downloaded and how SSRF protection is applied:

  • If False, the URL is sent directly to providers that support it. For providers that don't, the file is downloaded with SSRF protection (blocks private IPs and cloud metadata).
  • If True, the file is always downloaded with SSRF protection (blocks private IPs and cloud metadata).
  • If 'allow-local', the file is always downloaded, allowing private IPs but still blocking cloud metadata.

vendor_metadata class-attribute instance-attribute

vendor_metadata: dict[str, Any] | None = None

Vendor-specific metadata for the file.

Supported by: - GoogleModel: VideoUrl.vendor_metadata is used as video_metadata: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing - OpenAIChatModel, OpenAIResponsesModel: ImageUrl.vendor_metadata['detail'] is used as detail setting for images - XaiModel: ImageUrl.vendor_metadata['detail'] is used as detail setting for images

media_type property

media_type: str

Return the media type of the file, based on the URL or the provided media_type.

identifier property

identifier: str

The identifier of the file, such as a unique ID.

This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument, and the tool can look up the file in question by iterating over the message history and finding the matching FileUrl.

This identifier is only automatically passed to the model when the FileUrl is returned by a tool. If you're passing the FileUrl as a user message, it's up to you to include a separate text part with the identifier, e.g. "This is file :" preceding the FileUrl.

It's also included in inline-text delimiters for providers that require inlining text documents, so the model can distinguish multiple files.

format abstractmethod property

format: str

The file format.

VideoUrl

Bases: FileUrl

A URL to a video.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class VideoUrl(FileUrl):
    """A URL to a video."""

    url: str
    """The URL of the video."""

    _: KW_ONLY

    kind: Literal['video-url'] = 'video-url'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the aliases for the `_media_type` and `_identifier` fields.
    def __init__(
        self,
        url: str,
        *,
        media_type: str | None = None,
        identifier: str | None = None,
        force_download: ForceDownloadMode = False,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['video-url'] = 'video-url',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    def _infer_media_type(self) -> str:
        """Return the media type of the video, based on the url."""
        # Assume that YouTube videos are mp4 because there would be no extension
        # to infer from. This should not be a problem, as Gemini disregards media
        # type for YouTube URLs.
        if self.is_youtube:
            return 'video/mp4'

        mime_type, _ = _mime_types.guess_type(self.url)
        if mime_type is None:
            raise ValueError(
                f'Could not infer media type from video URL: {self.url}. Explicitly provide a `media_type` instead.'
            )
        return mime_type

    @property
    def is_youtube(self) -> bool:
        """True if the URL has a YouTube domain."""
        parsed = urlparse(self.url)
        hostname = parsed.hostname
        return hostname in ('youtu.be', 'youtube.com', 'www.youtube.com')

    @property
    def format(self) -> VideoFormat:
        """The file format of the video.

        The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.
        """
        return _video_format_lookup[self.media_type]

url instance-attribute

url: str

The URL of the video.

kind class-attribute instance-attribute

kind: Literal['video-url'] = 'video-url'

Type identifier, this is available on all parts as a discriminator.

is_youtube property

is_youtube: bool

True if the URL has a YouTube domain.

format property

format: VideoFormat

The file format of the video.

The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.

AudioUrl

Bases: FileUrl

A URL to an audio file.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class AudioUrl(FileUrl):
    """A URL to an audio file."""

    url: str
    """The URL of the audio file."""

    _: KW_ONLY

    kind: Literal['audio-url'] = 'audio-url'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the aliases for the `_media_type` and `_identifier` fields.
    def __init__(
        self,
        url: str,
        *,
        media_type: str | None = None,
        identifier: str | None = None,
        force_download: ForceDownloadMode = False,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['audio-url'] = 'audio-url',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    def _infer_media_type(self) -> str:
        """Return the media type of the audio file, based on the url.

        References:
        - Gemini: https://ai.google.dev/gemini-api/docs/audio#supported-formats
        """
        mime_type, _ = _mime_types.guess_type(self.url)
        if mime_type is None:
            raise ValueError(
                f'Could not infer media type from audio URL: {self.url}. Explicitly provide a `media_type` instead.'
            )
        return mime_type

    @property
    def format(self) -> AudioFormat:
        """The file format of the audio file."""
        return _audio_format_lookup[self.media_type]

url instance-attribute

url: str

The URL of the audio file.

kind class-attribute instance-attribute

kind: Literal['audio-url'] = 'audio-url'

Type identifier, this is available on all parts as a discriminator.

format property

format: AudioFormat

The file format of the audio file.

ImageUrl

Bases: FileUrl

A URL to an image.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class ImageUrl(FileUrl):
    """A URL to an image."""

    url: str
    """The URL of the image."""

    _: KW_ONLY

    kind: Literal['image-url'] = 'image-url'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the aliases for the `_media_type` and `_identifier` fields.
    def __init__(
        self,
        url: str,
        *,
        media_type: str | None = None,
        identifier: str | None = None,
        force_download: ForceDownloadMode = False,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['image-url'] = 'image-url',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    def _infer_media_type(self) -> str:
        """Return the media type of the image, based on the url."""
        mime_type, _ = _mime_types.guess_type(self.url)
        if mime_type is None:
            raise ValueError(
                f'Could not infer media type from image URL: {self.url}. Explicitly provide a `media_type` instead.'
            )
        return mime_type

    @property
    def format(self) -> ImageFormat:
        """The file format of the image.

        The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.
        """
        return _image_format_lookup[self.media_type]

url instance-attribute

url: str

The URL of the image.

kind class-attribute instance-attribute

kind: Literal['image-url'] = 'image-url'

Type identifier, this is available on all parts as a discriminator.

format property

format: ImageFormat

The file format of the image.

The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.

DocumentUrl

Bases: FileUrl

The URL of the document.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class DocumentUrl(FileUrl):
    """The URL of the document."""

    url: str
    """The URL of the document."""

    _: KW_ONLY

    kind: Literal['document-url'] = 'document-url'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the aliases for the `_media_type` and `_identifier` fields.
    def __init__(
        self,
        url: str,
        *,
        media_type: str | None = None,
        identifier: str | None = None,
        force_download: ForceDownloadMode = False,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['document-url'] = 'document-url',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    def _infer_media_type(self) -> str:
        """Return the media type of the document, based on the url."""
        mime_type, _ = _mime_types.guess_type(self.url)
        if mime_type is None:
            raise ValueError(
                f'Could not infer media type from document URL: {self.url}. Explicitly provide a `media_type` instead.'
            )
        return mime_type

    @property
    def format(self) -> DocumentFormat:
        """The file format of the document.

        The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.
        """
        media_type = self.media_type
        try:
            return _document_format_lookup[media_type]
        except KeyError as e:
            raise ValueError(f'Unknown document media type: {media_type}') from e

url instance-attribute

url: str

The URL of the document.

kind class-attribute instance-attribute

kind: Literal['document-url'] = 'document-url'

Type identifier, this is available on all parts as a discriminator.

format property

format: DocumentFormat

The file format of the document.

The choice of supported formats were based on the Bedrock Converse API. Other APIs don't require to use a format.

TextContent dataclass

String content that is tagged with additional metadata.

This is useful for including metadata that can be accessed programmatically by the application, but is not sent to the LLM.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
@dataclass(repr=False)
class TextContent:
    """String content that is tagged with additional metadata.

    This is useful for including metadata that can be accessed programmatically by the application, but is not sent to the LLM.
    """

    content: str
    """The content that is sent to the LLM."""

    _: KW_ONLY

    metadata: Any = None
    """Additional data that can be accessed programmatically by the application but is not sent to the LLM."""

    kind: Literal['text-content'] = 'text-content'
    """Type identifier, this is available on all parts as a discriminator."""

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str

The content that is sent to the LLM.

metadata class-attribute instance-attribute

metadata: Any = None

Additional data that can be accessed programmatically by the application but is not sent to the LLM.

kind class-attribute instance-attribute

kind: Literal['text-content'] = 'text-content'

Type identifier, this is available on all parts as a discriminator.

BinaryContent

Binary content, e.g. an audio or image file.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
@pydantic_dataclass(
    repr=False,
    config=pydantic.ConfigDict(
        ser_json_bytes='base64',
        val_json_bytes='base64',
    ),
)
class BinaryContent:
    """Binary content, e.g. an audio or image file."""

    data: bytes
    """The binary file data.

    Use `.base64` to get the base64-encoded string.
    """

    _: KW_ONLY

    media_type: AudioMediaType | ImageMediaType | DocumentMediaType | str
    """The media type of the binary data."""

    vendor_metadata: dict[str, Any] | None = None
    """Vendor-specific metadata for the file.

    Supported by:
    - `GoogleModel`: `BinaryContent.vendor_metadata` is used as `video_metadata`: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing
    - `OpenAIChatModel`, `OpenAIResponsesModel`: `BinaryContent.vendor_metadata['detail']` is used as `detail` setting for images
    - `XaiModel`: `BinaryContent.vendor_metadata['detail']` is used as `detail` setting for images
    """

    _identifier: Annotated[str | None, pydantic.Field(alias='identifier', default=None, exclude=True)] = field(
        compare=False, default=None
    )

    kind: Literal['binary'] = 'binary'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the `identifier` alias for the `_identifier` field.
    def __init__(
        self,
        data: bytes,
        *,
        media_type: AudioMediaType | ImageMediaType | DocumentMediaType | str,
        identifier: str | None = None,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['binary'] = 'binary',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    @staticmethod
    def narrow_type(bc: BinaryContent) -> BinaryContent | BinaryImage:
        """Narrow the type of the `BinaryContent` to `BinaryImage` if it's an image."""
        if bc.is_image:
            return BinaryImage(
                data=bc.data,
                media_type=bc.media_type,
                identifier=bc.identifier,
                vendor_metadata=bc.vendor_metadata,
            )
        else:
            return bc

    @classmethod
    def from_data_uri(cls, data_uri: str) -> BinaryContent:
        """Create a `BinaryContent` from a data URI."""
        prefix = 'data:'
        if not data_uri.startswith(prefix):
            raise ValueError('Data URI must start with "data:"')
        media_type, data = data_uri[len(prefix) :].split(';base64,', 1)
        return cls.narrow_type(cls(data=base64.b64decode(data), media_type=media_type))

    @classmethod
    def from_path(cls, path: PathLike[str]) -> BinaryContent:
        """Create a `BinaryContent` from a path.

        Defaults to 'application/octet-stream' if the media type cannot be inferred.

        Raises:
            FileNotFoundError: if the file does not exist.
            PermissionError: if the file cannot be read.
        """
        path = Path(path)
        if not path.exists():
            raise FileNotFoundError(f'File not found: {path}')
        media_type, _ = _mime_types.guess_type(path)
        if media_type is None:
            media_type = 'application/octet-stream'

        return cls.narrow_type(cls(data=path.read_bytes(), media_type=media_type))

    @pydantic.computed_field
    @property
    def identifier(self) -> str:
        """Identifier for the binary content, such as a unique ID.

        This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument,
        and the tool can look up the file in question by iterating over the message history and finding the matching `BinaryContent`.

        This identifier is only automatically passed to the model when the `BinaryContent` is returned by a tool.
        If you're passing the `BinaryContent` as a user message, it's up to you to include a separate text part with the identifier,
        e.g. "This is file <identifier>:" preceding the `BinaryContent`.

        It's also included in inline-text delimiters for providers that require inlining text documents, so the model can
        distinguish multiple files.
        """
        return self._identifier or _multi_modal_content_identifier(self.data)

    @property
    def data_uri(self) -> str:
        """Convert the `BinaryContent` to a data URI."""
        return f'data:{self.media_type};base64,{self.base64}'

    @property
    def base64(self) -> str:
        """Return the binary data as a base64-encoded string. Default encoding is UTF-8."""
        return base64.b64encode(self.data).decode()

    @property
    def is_audio(self) -> bool:
        """Return `True` if the media type is an audio type."""
        return self.media_type.startswith('audio/')

    @property
    def is_image(self) -> bool:
        """Return `True` if the media type is an image type."""
        return self.media_type.startswith('image/')

    @property
    def is_video(self) -> bool:
        """Return `True` if the media type is a video type."""
        return self.media_type.startswith('video/')

    @property
    def is_document(self) -> bool:
        """Return `True` if the media type is a document type."""
        return self.media_type in _document_format_lookup

    @property
    def format(self) -> str:
        """The file format of the binary content."""
        try:
            if self.is_audio:
                return _audio_format_lookup[self.media_type]
            elif self.is_image:
                return _image_format_lookup[self.media_type]
            elif self.is_video:
                return _video_format_lookup[self.media_type]
            else:
                return _document_format_lookup[self.media_type]
        except KeyError as e:
            raise ValueError(f'Unknown media type: {self.media_type}') from e

    __repr__ = _utils.dataclasses_no_defaults_repr

data instance-attribute

data: bytes

The binary file data.

Use .base64 to get the base64-encoded string.

media_type instance-attribute

media_type: (
    AudioMediaType
    | ImageMediaType
    | DocumentMediaType
    | str
)

The media type of the binary data.

vendor_metadata class-attribute instance-attribute

vendor_metadata: dict[str, Any] | None = None

Vendor-specific metadata for the file.

Supported by: - GoogleModel: BinaryContent.vendor_metadata is used as video_metadata: https://ai.google.dev/gemini-api/docs/video-understanding#customize-video-processing - OpenAIChatModel, OpenAIResponsesModel: BinaryContent.vendor_metadata['detail'] is used as detail setting for images - XaiModel: BinaryContent.vendor_metadata['detail'] is used as detail setting for images

kind class-attribute instance-attribute

kind: Literal['binary'] = 'binary'

Type identifier, this is available on all parts as a discriminator.

narrow_type staticmethod

narrow_type(
    bc: BinaryContent,
) -> BinaryContent | BinaryImage

Narrow the type of the BinaryContent to BinaryImage if it's an image.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
546
547
548
549
550
551
552
553
554
555
556
557
@staticmethod
def narrow_type(bc: BinaryContent) -> BinaryContent | BinaryImage:
    """Narrow the type of the `BinaryContent` to `BinaryImage` if it's an image."""
    if bc.is_image:
        return BinaryImage(
            data=bc.data,
            media_type=bc.media_type,
            identifier=bc.identifier,
            vendor_metadata=bc.vendor_metadata,
        )
    else:
        return bc

from_data_uri classmethod

from_data_uri(data_uri: str) -> BinaryContent

Create a BinaryContent from a data URI.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
559
560
561
562
563
564
565
566
@classmethod
def from_data_uri(cls, data_uri: str) -> BinaryContent:
    """Create a `BinaryContent` from a data URI."""
    prefix = 'data:'
    if not data_uri.startswith(prefix):
        raise ValueError('Data URI must start with "data:"')
    media_type, data = data_uri[len(prefix) :].split(';base64,', 1)
    return cls.narrow_type(cls(data=base64.b64decode(data), media_type=media_type))

from_path classmethod

from_path(path: PathLike[str]) -> BinaryContent

Create a BinaryContent from a path.

Defaults to 'application/octet-stream' if the media type cannot be inferred.

Raises:

Type Description
FileNotFoundError

if the file does not exist.

PermissionError

if the file cannot be read.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
@classmethod
def from_path(cls, path: PathLike[str]) -> BinaryContent:
    """Create a `BinaryContent` from a path.

    Defaults to 'application/octet-stream' if the media type cannot be inferred.

    Raises:
        FileNotFoundError: if the file does not exist.
        PermissionError: if the file cannot be read.
    """
    path = Path(path)
    if not path.exists():
        raise FileNotFoundError(f'File not found: {path}')
    media_type, _ = _mime_types.guess_type(path)
    if media_type is None:
        media_type = 'application/octet-stream'

    return cls.narrow_type(cls(data=path.read_bytes(), media_type=media_type))

identifier property

identifier: str

Identifier for the binary content, such as a unique ID.

This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument, and the tool can look up the file in question by iterating over the message history and finding the matching BinaryContent.

This identifier is only automatically passed to the model when the BinaryContent is returned by a tool. If you're passing the BinaryContent as a user message, it's up to you to include a separate text part with the identifier, e.g. "This is file :" preceding the BinaryContent.

It's also included in inline-text delimiters for providers that require inlining text documents, so the model can distinguish multiple files.

data_uri property

data_uri: str

Convert the BinaryContent to a data URI.

base64 property

base64: str

Return the binary data as a base64-encoded string. Default encoding is UTF-8.

is_audio property

is_audio: bool

Return True if the media type is an audio type.

is_image property

is_image: bool

Return True if the media type is an image type.

is_video property

is_video: bool

Return True if the media type is a video type.

is_document property

is_document: bool

Return True if the media type is a document type.

format property

format: str

The file format of the binary content.

BinaryImage

Bases: BinaryContent

Binary content that's guaranteed to be an image.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
@pydantic_dataclass(
    repr=False,
    config=pydantic.ConfigDict(
        ser_json_bytes='base64',
        val_json_bytes='base64',
    ),
)
class BinaryImage(BinaryContent):
    """Binary content that's guaranteed to be an image."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the `identifier` alias for the `_identifier` field.
    def __init__(
        self,
        data: bytes,
        *,
        media_type: ImageMediaType | str,
        identifier: str | None = None,
        vendor_metadata: dict[str, Any] | None = None,
        kind: Literal['binary'] = 'binary',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    def __post_init__(self):
        if not self.is_image:
            raise ValueError('`BinaryImage` must have a media type that starts with "image/"')

CachePoint dataclass

A cache point marker for prompt caching.

Can be inserted into UserPromptPart.content to mark cache boundaries. Models that don't support caching will filter these out.

Supported by:

  • Anthropic
  • Amazon Bedrock (Converse API)
Source code in pydantic_ai_slim/pydantic_ai/messages.py
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
@dataclass
class CachePoint:
    """A cache point marker for prompt caching.

    Can be inserted into UserPromptPart.content to mark cache boundaries.
    Models that don't support caching will filter these out.

    Supported by:

    - Anthropic
    - Amazon Bedrock (Converse API)
    """

    kind: Literal['cache-point'] = 'cache-point'
    """Type identifier, this is available on all parts as a discriminator."""

    ttl: Literal['5m', '1h'] = '5m'
    """The cache time-to-live, either "5m" (5 minutes) or "1h" (1 hour).

    Supported by:

    * Anthropic — see https://docs.claude.com/en/docs/build-with-claude/prompt-caching#1-hour-cache-duration for more information.
    * Amazon Bedrock (Converse API) — see https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html for more information.
    """

kind class-attribute instance-attribute

kind: Literal['cache-point'] = 'cache-point'

Type identifier, this is available on all parts as a discriminator.

ttl class-attribute instance-attribute

ttl: Literal['5m', '1h'] = '5m'

The cache time-to-live, either "5m" (5 minutes) or "1h" (1 hour).

Supported by:

  • Anthropic — see https://docs.claude.com/en/docs/build-with-claude/prompt-caching#1-hour-cache-duration for more information.
  • Amazon Bedrock (Converse API) — see https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html for more information.

UploadedFileProviderName module-attribute

UploadedFileProviderName: TypeAlias = Literal[
    "anthropic",
    "openai",
    "google",
    "google-cloud",
    "google-gla",
    "google-vertex",
    "bedrock",
    "xai",
]

Provider names supported by UploadedFile.

The 'google-gla' and 'google-vertex' values are retained for backward compatibility with message history captured before the v2 provider rename — current code emits 'google' and 'google-cloud' respectively.

UploadedFile

A reference to a file uploaded to a provider's file storage by ID.

This allows referencing files that have been uploaded via provider-specific file APIs rather than providing the file content directly.

Supported by:

Source code in pydantic_ai_slim/pydantic_ai/messages.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
@pydantic_dataclass(repr=False, config=pydantic.ConfigDict(validate_by_name=True))
class UploadedFile:
    """A reference to a file uploaded to a provider's file storage by ID.

    This allows referencing files that have been uploaded via provider-specific file APIs
    rather than providing the file content directly.

    Supported by:

    - [`AnthropicModel`][pydantic_ai.models.anthropic.AnthropicModel]
    - [`OpenAIChatModel`][pydantic_ai.models.openai.OpenAIChatModel]
    - [`OpenAIResponsesModel`][pydantic_ai.models.openai.OpenAIResponsesModel]
    - [`BedrockConverseModel`][pydantic_ai.models.bedrock.BedrockConverseModel]
    - [`GoogleModel`][pydantic_ai.models.google.GoogleModel] (Gemini API: [Files API](https://ai.google.dev/gemini-api/docs/files) URIs, Google Cloud: GCS `gs://` URIs)
    - [`XaiModel`][pydantic_ai.models.xai.XaiModel]
    """

    file_id: str
    """The provider-specific file identifier.

    For most providers, this is the file ID returned by the provider's upload API.
    For GoogleModel (Google Cloud), this must be a GCS URI (`gs://bucket/path`).
    For GoogleModel (Gemini API), this must be a Google Files API URI (`https://generativelanguage.googleapis.com/...`).
    For BedrockConverseModel, this must be an S3 URI (`s3://bucket/key`).
    """

    provider_name: UploadedFileProviderName
    """The provider this file belongs to.

    This is required because file IDs are not portable across providers, and using a file ID
    with the wrong provider will always result in an error.

    Tip: Use `model.system` to get the provider name dynamically.
    """

    _: KW_ONLY

    vendor_metadata: dict[str, Any] | None = None
    """Vendor-specific metadata for the file.

    The expected shape of this dictionary depends on the provider:

    Supported by:
    - `GoogleModel`: used as `video_metadata` for video files
    """

    _media_type: Annotated[str | None, pydantic.Field(alias='media_type', default=None, exclude=True)] = field(
        compare=False, default=None
    )

    _identifier: Annotated[str | None, pydantic.Field(alias='identifier', default=None, exclude=True)] = field(
        compare=False, default=None
    )

    kind: Literal['uploaded-file'] = 'uploaded-file'
    """Type identifier, this is available on all parts as a discriminator."""

    # `pydantic_dataclass` replaces `__init__` so this method is never used.
    # The signature is kept so that pyright/IDE hints recognize the `media_type` and `identifier` aliases.
    def __init__(
        self,
        file_id: str,
        provider_name: UploadedFileProviderName,
        *,
        media_type: str | None = None,
        vendor_metadata: dict[str, Any] | None = None,
        identifier: str | None = None,
        kind: Literal['uploaded-file'] = 'uploaded-file',
        # Required for inline-snapshot which expects all dataclass `__init__` methods to take all field names as kwargs.
        _media_type: str | None = None,
        _identifier: str | None = None,
    ) -> None: ...  # pragma: no cover

    @pydantic.computed_field
    @property
    def media_type(self) -> str:
        """Return the media type of the file, inferred from `file_id` if not explicitly provided.

        Note: Inference relies on the file extension in `file_id`.
        For opaque file IDs (e.g., `'file-abc123'`), the media type will default to `'application/octet-stream'`.
        Inference relies on Python's `mimetypes` module, whose results may vary across platforms.

        Required by some providers (e.g., Bedrock) for certain file types.
        """
        if self._media_type is not None:
            return self._media_type
        parsed = urlparse(self.file_id)
        mime_type, _ = _mime_types.guess_type(parsed.path)
        return mime_type or 'application/octet-stream'

    @pydantic.computed_field
    @property
    def identifier(self) -> str:
        """The identifier of the file, such as a unique ID.

        This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument,
        and the tool can look up the file in question by iterating over the message history and finding the matching `UploadedFile`.

        This identifier is only automatically passed to the model when the `UploadedFile` is returned by a tool.
        If you're passing the `UploadedFile` as a user message, it's up to you to include a separate text part with the identifier,
        e.g. "This is file <identifier>:" preceding the `UploadedFile`.
        """
        return self._identifier or _multi_modal_content_identifier(self.file_id)

    @property
    def format(self) -> str:
        """A general-purpose media-type-to-format mapping.

        Maps media types to format strings (e.g. `'image/png'` -> `'png'`). Covers image, video,
        audio, and document types. Currently used by Bedrock, which requires explicit format strings.
        """
        media_type = self.media_type
        try:
            if media_type.startswith('image/'):
                return _image_format_lookup[media_type]
            elif media_type.startswith('video/'):
                return _video_format_lookup[media_type]
            elif media_type.startswith('audio/'):
                return _audio_format_lookup[media_type]
            else:
                return _document_format_lookup[media_type]
        except KeyError as e:
            raise ValueError(f'Unknown media type: {media_type}') from e

    __repr__ = _utils.dataclasses_no_defaults_repr

file_id instance-attribute

file_id: str

The provider-specific file identifier.

For most providers, this is the file ID returned by the provider's upload API. For GoogleModel (Google Cloud), this must be a GCS URI (gs://bucket/path). For GoogleModel (Gemini API), this must be a Google Files API URI (https://generativelanguage.googleapis.com/...). For BedrockConverseModel, this must be an S3 URI (s3://bucket/key).

provider_name instance-attribute

provider_name: UploadedFileProviderName

The provider this file belongs to.

This is required because file IDs are not portable across providers, and using a file ID with the wrong provider will always result in an error.

Tip: Use model.system to get the provider name dynamically.

vendor_metadata class-attribute instance-attribute

vendor_metadata: dict[str, Any] | None = None

Vendor-specific metadata for the file.

The expected shape of this dictionary depends on the provider:

Supported by: - GoogleModel: used as video_metadata for video files

kind class-attribute instance-attribute

kind: Literal['uploaded-file'] = 'uploaded-file'

Type identifier, this is available on all parts as a discriminator.

media_type property

media_type: str

Return the media type of the file, inferred from file_id if not explicitly provided.

Note: Inference relies on the file extension in file_id. For opaque file IDs (e.g., 'file-abc123'), the media type will default to 'application/octet-stream'. Inference relies on Python's mimetypes module, whose results may vary across platforms.

Required by some providers (e.g., Bedrock) for certain file types.

identifier property

identifier: str

The identifier of the file, such as a unique ID.

This identifier can be provided to the model in a message to allow it to refer to this file in a tool call argument, and the tool can look up the file in question by iterating over the message history and finding the matching UploadedFile.

This identifier is only automatically passed to the model when the UploadedFile is returned by a tool. If you're passing the UploadedFile as a user message, it's up to you to include a separate text part with the identifier, e.g. "This is file :" preceding the UploadedFile.

format property

format: str

A general-purpose media-type-to-format mapping.

Maps media types to format strings (e.g. 'image/png' -> 'png'). Covers image, video, audio, and document types. Currently used by Bedrock, which requires explicit format strings.

MultiModalContent module-attribute

Union of all multi-modal content types with a discriminator for Pydantic validation.

is_multi_modal_content

is_multi_modal_content(
    obj: Any,
) -> TypeGuard[MultiModalContent]

Check if obj is a MultiModalContent type, enabling type narrowing.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
861
862
863
def is_multi_modal_content(obj: Any) -> TypeGuard[MultiModalContent]:
    """Check if obj is a MultiModalContent type, enabling type narrowing."""
    return isinstance(obj, MULTI_MODAL_CONTENT_TYPES)

ToolReturn dataclass

Bases: Generic[_ToolReturnValueT]

A structured tool return that separates the tool result from additional content sent to the model.

Can be parameterized with a type to enable return schema generation: - ToolReturn[User] — generates a return schema for User - ToolReturn (bare) — no return schema generated

Source code in pydantic_ai_slim/pydantic_ai/messages.py
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
@dataclass(repr=False)
class ToolReturn(Generic[_ToolReturnValueT]):
    """A structured tool return that separates the tool result from additional content sent to the model.

    Can be parameterized with a type to enable return schema generation:
    - `ToolReturn[User]` — generates a return schema for `User`
    - `ToolReturn` (bare) — no return schema generated
    """

    return_value: ToolReturnContent
    """The return value to be used in the tool response."""

    _: KW_ONLY

    content: str | Sequence[UserContent] | None = None
    """Content sent to the model as a separate `UserPromptPart`.

    Use this when you want content to appear outside the tool result message.
    For multimodal content that should be sent natively in the tool result,
    return it directly from the tool function or include it in `return_value`.
    """

    metadata: Any = None
    """Additional data accessible by the application but not sent to the LLM."""

    kind: Literal['tool-return'] = 'tool-return'

    __repr__ = _utils.dataclasses_no_defaults_repr

return_value instance-attribute

return_value: ToolReturnContent

The return value to be used in the tool response.

content class-attribute instance-attribute

content: str | Sequence[UserContent] | None = None

Content sent to the model as a separate UserPromptPart.

Use this when you want content to appear outside the tool result message. For multimodal content that should be sent natively in the tool result, return it directly from the tool function or include it in return_value.

metadata class-attribute instance-attribute

metadata: Any = None

Additional data accessible by the application but not sent to the LLM.

UserPromptPart dataclass

A user prompt, generally written by the end user.

Content comes from the user_prompt parameter of Agent.run, Agent.run_sync, and Agent.run_stream.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
@dataclass(repr=False)
class UserPromptPart:
    """A user prompt, generally written by the end user.

    Content comes from the `user_prompt` parameter of [`Agent.run`][pydantic_ai.agent.AbstractAgent.run],
    [`Agent.run_sync`][pydantic_ai.agent.AbstractAgent.run_sync], and [`Agent.run_stream`][pydantic_ai.agent.AbstractAgent.run_stream].
    """

    content: str | Sequence[UserContent]
    """The content of the prompt."""

    _: KW_ONLY

    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp of the prompt."""

    part_kind: Literal['user-prompt'] = 'user-prompt'
    """Part type identifier, this is available on all parts as a discriminator."""

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        parts: list[_otel_messages.MessagePart] = []
        content: Sequence[UserContent] = [self.content] if isinstance(self.content, str) else self.content
        for part in content:
            if isinstance(part, str | TextContent):
                content_str = part if isinstance(part, str) else part.content
                parts.append(
                    _otel_messages.TextPart(
                        type='text', **({'content': content_str} if settings.include_content else {})
                    )
                )
            elif isinstance(part, ImageUrl | AudioUrl | DocumentUrl | VideoUrl):
                if settings.version >= 4:
                    uri_part = _otel_messages.UriPart(type='uri')
                    modality = _kind_to_modality_lookup.get(part.kind)
                    if modality is not None:
                        uri_part['modality'] = modality
                    try:  # don't fail the whole message if media type can't be inferred for some reason, just omit it
                        uri_part['mime_type'] = part.media_type
                    except ValueError:
                        pass
                    if settings.include_content:
                        uri_part['uri'] = part.url
                    parts.append(uri_part)
                else:
                    parts.append(
                        _otel_messages.MediaUrlPart(
                            type=part.kind,
                            **{'url': part.url} if settings.include_content else {},
                        )
                    )
            elif isinstance(part, BinaryContent):
                parts.append(_convert_binary_to_otel_part(part.media_type, lambda p=part: p.base64, settings))
            elif isinstance(part, UploadedFile):
                # UploadedFile references provider-hosted files by file_id (OTel GenAI spec FilePart)
                # Infer modality from media_type - OTel spec defines: image, video, audio (or any string)
                category = part.media_type.split('/', 1)[0]
                if category in ('image', 'audio', 'video'):
                    modality = category
                else:
                    modality = 'document'  # default for PDFs, text, etc.
                file_part = _otel_messages.FilePart(type='file', modality=modality, mime_type=part.media_type)
                if settings.include_content:
                    file_part['file_id'] = part.file_id
                parts.append(file_part)
            elif isinstance(part, CachePoint):
                # CachePoint is a marker, not actual content - skip it for otel
                pass
            else:
                parts.append({'type': part.kind})  # pragma: no cover
        return parts

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str | Sequence[UserContent]

The content of the prompt.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp of the prompt.

part_kind class-attribute instance-attribute

part_kind: Literal['user-prompt'] = 'user-prompt'

Part type identifier, this is available on all parts as a discriminator.

RETURN_VALUE_KEY module-attribute

RETURN_VALUE_KEY = 'return_value'

Key used to wrap non-dict tool return values in model_response_object().

ToolPartKind module-attribute

ToolPartKind: TypeAlias = Literal['tool-search']

Discriminator value for the typed call/return-part subclass associated with a tool.

Set on BaseToolCallPart.tool_kind, BaseToolReturnPart.tool_kind, and ToolDefinition.tool_kind. Extended as new typed-part families (e.g. web search) gain dedicated subclasses.

Distinct from ToolKind (invocation semantics — 'function', 'output', 'external', 'unapproved').

BaseToolReturnPart dataclass

Base class for tool return parts.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
@dataclass(repr=False)
class BaseToolReturnPart:
    """Base class for tool return parts."""

    tool_name: str
    """The name of the tool that was called."""

    content: ToolReturnContent
    """The tool return content, which may include multimodal files."""

    tool_call_id: str = field(default_factory=_generate_tool_call_id)
    """The tool call identifier, this is used by some models including OpenAI.

    In case the tool call id is not provided by the model, Pydantic AI will generate a random one.
    """

    _: KW_ONLY

    tool_kind: ToolPartKind | None = None
    """Discriminator for the typed subclass of this part (e.g. `'tool-search'`).

    `None` for any part without a typed subclass — including all user-defined tools and all
    native tools without a dedicated typed call/return shape. Subclasses that pin this to a
    [`ToolPartKind`][pydantic_ai.messages.ToolPartKind] literal:

    * [`ToolSearchCallPart`][pydantic_ai.messages.ToolSearchCallPart] /
      [`ToolSearchReturnPart`][pydantic_ai.messages.ToolSearchReturnPart] — `'tool-search'`
    * [`NativeToolSearchCallPart`][pydantic_ai.messages.NativeToolSearchCallPart] /
      [`NativeToolSearchReturnPart`][pydantic_ai.messages.NativeToolSearchReturnPart] — `'tool-search'`
    """

    metadata: Any = None
    """Additional data accessible by the application but not sent to the LLM."""

    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp, when the tool returned."""

    outcome: Literal['success', 'failed', 'denied'] = 'success'
    """The outcome of the tool call.

    - `'success'`: The tool executed successfully.
    - `'failed'`: The tool raised an error during execution.
    - `'denied'`: The tool call was denied by the approval mechanism.
    """

    def _split_content(self) -> tuple[list[Any], list[MultiModalContent], bool]:
        """Split content into non-file and file parts.

        Returns:
            A 3-tuple of (`data_parts`, `file_parts`, `was_list`) where `was_list` indicates
            whether the original content was a list.
        """
        if is_multi_modal_content(self.content):
            return [], [self.content], False
        elif isinstance(self.content, list):
            non_files: list[Any] = []
            files: list[MultiModalContent] = []
            # ToolReturnContent uses a recursive TypeAliasType at runtime (for Pydantic validation)
            # but a simpler union at type-check time, so pyright can't infer `p`'s type from the list.
            for p in self.content:  # pyright: ignore[reportUnknownVariableType, reportUnknownMemberType]
                if is_multi_modal_content(p):
                    files.append(p)
                else:
                    non_files.append(p)
            return non_files, files, True
        return [self.content], [], False

    def _unwrap_data(self) -> tuple[Any, list[MultiModalContent]]:
        """Split content and unwrap single-item data lists.

        Returns the unwrapped data value (or None if empty) and the file parts.
        Single-item lists are unwrapped when content was scalar or when files were filtered out.
        """
        data, files, was_list = self._split_content()
        if not data:
            return None, files
        # Unwrap single-item data: either content was originally scalar (!was_list)
        # or extracting files reduced a multi-item list to one element.
        if len(data) == 1 and (not was_list or bool(files)):
            return data[0], files
        return data, files

    @property
    def files(self) -> list[MultiModalContent]:
        """The multimodal file parts from `content` (`ImageUrl`, `AudioUrl`, `DocumentUrl`, `VideoUrl`, `BinaryContent`)."""
        _, files, _ = self._split_content()
        return files

    @overload
    def content_items(self, *, mode: Literal['raw'] = 'raw') -> list[ToolReturnContent]: ...

    @overload
    def content_items(self, *, mode: Literal['str']) -> list[str | MultiModalContent]: ...

    @overload
    def content_items(self, *, mode: Literal['jsonable']) -> list[Any | MultiModalContent]: ...

    def content_items(
        self, *, mode: Literal['raw', 'str', 'jsonable'] = 'raw'
    ) -> list[ToolReturnContent] | list[str | MultiModalContent] | list[Any | MultiModalContent]:
        """Return content as a flat list for iteration, with optional serialization.

        Args:
            mode: Controls serialization of non-file items:
                - `'raw'`: No serialization. Returns items as-is.
                - `'str'`: Non-file items are serialized to strings via `tool_return_ta`.
                  File items (`MultiModalContent`) pass through unchanged.
                - `'jsonable'`: Non-file items are serialized to JSON-compatible Python objects
                  via `tool_return_ta`. File items pass through unchanged.
        """
        items: list[ToolReturnContent]
        if isinstance(self.content, list):
            items = self.content  # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
        else:
            items = [self.content]

        if mode == 'raw':
            return items

        result: list[str | MultiModalContent] | list[Any | MultiModalContent] = []
        for item in items:
            if is_multi_modal_content(item):
                result.append(item)
            elif isinstance(item, str):
                result.append(item)
            elif mode == 'str':
                result.append(tool_return_ta.dump_json(item).decode())
            else:
                result.append(tool_return_ta.dump_python(item, mode='json'))
        return result

    def model_response_str(self) -> str:
        """Return a string representation of the data content for the model.

        This excludes multimodal files - use `.files` to get those separately.
        """
        value, _ = self._unwrap_data()
        if value is None:
            return ''
        if isinstance(value, str):
            return value
        return tool_return_ta.dump_json(value).decode()

    def model_response_object(self) -> dict[str, Any]:
        """Return a dictionary representation of the data content, wrapping non-dict types appropriately.

        This excludes multimodal files - use `.files` to get those separately.
        Gemini supports JSON dict return values, but no other JSON types, hence we wrap anything else in a dict.
        """
        value, _ = self._unwrap_data()
        if value is None:
            return {}
        json_content = tool_return_ta.dump_python(value, mode='json')
        if _utils.is_str_dict(json_content):
            return json_content
        else:
            return {RETURN_VALUE_KEY: json_content}

    def model_response_str_and_user_content(self) -> tuple[str, list[UserContent]]:
        """Build a text-only tool result with multimodal files extracted for a trailing user message.

        For providers whose tool result API only accepts text. Multimodal files are referenced
        by identifier in the tool result text ('See file {id}.') and included in full in the
        returned file content list ('This is file {id}:' followed by the file).
        """
        _, files, was_list = self._split_content()
        if not files:
            return self.model_response_str(), []

        tool_content_parts: list[str] = []
        file_content: list[UserContent] = []

        for item in self.content_items(mode='str'):
            if is_multi_modal_content(item):
                tool_content_parts.append(f'See file {item.identifier}.')
                file_content.append(f'This is file {item.identifier}:')
                file_content.append(item)
            elif isinstance(item, str):  # pragma: no branch
                tool_content_parts.append(item)

        if was_list:
            return tool_return_ta.dump_json(tool_content_parts).decode(), file_content
        # Safe: when was_list is False, content is either scalar data (→ str item) or a single
        # MultiModalContent (→ 'See file ...' placeholder), so tool_content_parts always has one entry.
        return tool_content_parts[0], file_content

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        part = _otel_messages.ToolCallResponsePart(
            type='tool_call_response',
            id=self.tool_call_id,
            name=self.tool_name,
        )

        if settings.include_content and self.content is not None:
            part['result'] = serialize_any(self.content)

        return [part]

    def has_content(self) -> bool:
        """Return `True` if the tool return has content."""
        return self.content is not None  # pragma: no cover

    __repr__ = _utils.dataclasses_no_defaults_repr

tool_name instance-attribute

tool_name: str

The name of the tool that was called.

content instance-attribute

content: ToolReturnContent

The tool return content, which may include multimodal files.

tool_call_id class-attribute instance-attribute

tool_call_id: str = field(
    default_factory=generate_tool_call_id
)

The tool call identifier, this is used by some models including OpenAI.

In case the tool call id is not provided by the model, Pydantic AI will generate a random one.

tool_kind class-attribute instance-attribute

tool_kind: ToolPartKind | None = None

Discriminator for the typed subclass of this part (e.g. 'tool-search').

None for any part without a typed subclass — including all user-defined tools and all native tools without a dedicated typed call/return shape. Subclasses that pin this to a ToolPartKind literal:

  • [ToolSearchCallPart][pydantic_ai.messages.ToolSearchCallPart] / [ToolSearchReturnPart][pydantic_ai.messages.ToolSearchReturnPart] — 'tool-search'
  • [NativeToolSearchCallPart][pydantic_ai.messages.NativeToolSearchCallPart] / [NativeToolSearchReturnPart][pydantic_ai.messages.NativeToolSearchReturnPart] — 'tool-search'

metadata class-attribute instance-attribute

metadata: Any = None

Additional data accessible by the application but not sent to the LLM.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp, when the tool returned.

outcome class-attribute instance-attribute

outcome: Literal['success', 'failed', 'denied'] = 'success'

The outcome of the tool call.

  • 'success': The tool executed successfully.
  • 'failed': The tool raised an error during execution.
  • 'denied': The tool call was denied by the approval mechanism.

files property

The multimodal file parts from content (ImageUrl, AudioUrl, DocumentUrl, VideoUrl, BinaryContent).

content_items

content_items(
    *, mode: Literal["raw"] = "raw"
) -> list[ToolReturnContent]
content_items(
    *, mode: Literal["str"]
) -> list[str | MultiModalContent]
content_items(
    *, mode: Literal["jsonable"]
) -> list[Any | MultiModalContent]
content_items(
    *, mode: Literal["raw", "str", "jsonable"] = "raw"
) -> (
    list[ToolReturnContent]
    | list[str | MultiModalContent]
    | list[Any | MultiModalContent]
)

Return content as a flat list for iteration, with optional serialization.

Parameters:

Name Type Description Default
mode Literal['raw', 'str', 'jsonable']

Controls serialization of non-file items: - 'raw': No serialization. Returns items as-is. - 'str': Non-file items are serialized to strings via tool_return_ta. File items (MultiModalContent) pass through unchanged. - 'jsonable': Non-file items are serialized to JSON-compatible Python objects via tool_return_ta. File items pass through unchanged.

'raw'
Source code in pydantic_ai_slim/pydantic_ai/messages.py
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def content_items(
    self, *, mode: Literal['raw', 'str', 'jsonable'] = 'raw'
) -> list[ToolReturnContent] | list[str | MultiModalContent] | list[Any | MultiModalContent]:
    """Return content as a flat list for iteration, with optional serialization.

    Args:
        mode: Controls serialization of non-file items:
            - `'raw'`: No serialization. Returns items as-is.
            - `'str'`: Non-file items are serialized to strings via `tool_return_ta`.
              File items (`MultiModalContent`) pass through unchanged.
            - `'jsonable'`: Non-file items are serialized to JSON-compatible Python objects
              via `tool_return_ta`. File items pass through unchanged.
    """
    items: list[ToolReturnContent]
    if isinstance(self.content, list):
        items = self.content  # pyright: ignore[reportUnknownVariableType,reportUnknownMemberType]
    else:
        items = [self.content]

    if mode == 'raw':
        return items

    result: list[str | MultiModalContent] | list[Any | MultiModalContent] = []
    for item in items:
        if is_multi_modal_content(item):
            result.append(item)
        elif isinstance(item, str):
            result.append(item)
        elif mode == 'str':
            result.append(tool_return_ta.dump_json(item).decode())
        else:
            result.append(tool_return_ta.dump_python(item, mode='json'))
    return result

model_response_str

model_response_str() -> str

Return a string representation of the data content for the model.

This excludes multimodal files - use .files to get those separately.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
def model_response_str(self) -> str:
    """Return a string representation of the data content for the model.

    This excludes multimodal files - use `.files` to get those separately.
    """
    value, _ = self._unwrap_data()
    if value is None:
        return ''
    if isinstance(value, str):
        return value
    return tool_return_ta.dump_json(value).decode()

model_response_object

model_response_object() -> dict[str, Any]

Return a dictionary representation of the data content, wrapping non-dict types appropriately.

This excludes multimodal files - use .files to get those separately. Gemini supports JSON dict return values, but no other JSON types, hence we wrap anything else in a dict.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
def model_response_object(self) -> dict[str, Any]:
    """Return a dictionary representation of the data content, wrapping non-dict types appropriately.

    This excludes multimodal files - use `.files` to get those separately.
    Gemini supports JSON dict return values, but no other JSON types, hence we wrap anything else in a dict.
    """
    value, _ = self._unwrap_data()
    if value is None:
        return {}
    json_content = tool_return_ta.dump_python(value, mode='json')
    if _utils.is_str_dict(json_content):
        return json_content
    else:
        return {RETURN_VALUE_KEY: json_content}

model_response_str_and_user_content

model_response_str_and_user_content() -> (
    tuple[str, list[UserContent]]
)

Build a text-only tool result with multimodal files extracted for a trailing user message.

For providers whose tool result API only accepts text. Multimodal files are referenced by identifier in the tool result text ('See file {id}.') and included in full in the returned file content list ('This is file {id}:' followed by the file).

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
def model_response_str_and_user_content(self) -> tuple[str, list[UserContent]]:
    """Build a text-only tool result with multimodal files extracted for a trailing user message.

    For providers whose tool result API only accepts text. Multimodal files are referenced
    by identifier in the tool result text ('See file {id}.') and included in full in the
    returned file content list ('This is file {id}:' followed by the file).
    """
    _, files, was_list = self._split_content()
    if not files:
        return self.model_response_str(), []

    tool_content_parts: list[str] = []
    file_content: list[UserContent] = []

    for item in self.content_items(mode='str'):
        if is_multi_modal_content(item):
            tool_content_parts.append(f'See file {item.identifier}.')
            file_content.append(f'This is file {item.identifier}:')
            file_content.append(item)
        elif isinstance(item, str):  # pragma: no branch
            tool_content_parts.append(item)

    if was_list:
        return tool_return_ta.dump_json(tool_content_parts).decode(), file_content
    # Safe: when was_list is False, content is either scalar data (→ str item) or a single
    # MultiModalContent (→ 'See file ...' placeholder), so tool_content_parts always has one entry.
    return tool_content_parts[0], file_content

has_content

has_content() -> bool

Return True if the tool return has content.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1285
1286
1287
def has_content(self) -> bool:
    """Return `True` if the tool return has content."""
    return self.content is not None  # pragma: no cover

ToolReturnPart dataclass

Bases: BaseToolReturnPart

A tool return message, this encodes the result of running a tool.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
@dataclass(repr=False)
class ToolReturnPart(BaseToolReturnPart):
    """A tool return message, this encodes the result of running a tool."""

    _: KW_ONLY

    part_kind: Literal['tool-return'] = 'tool-return'
    """Part type identifier, this is available on all parts as a discriminator."""

    @staticmethod
    def narrow_type(part: ToolReturnPart, *, tool_kind: ToolPartKind | None = None) -> ToolReturnPart:
        """Promote a base `ToolReturnPart` to its typed subclass when its `tool_kind` is registered.

        Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
        to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
        applies it as part of its single dataclass clone, dropping the need for an upstream
        `replace(part, tool_kind=...)`. Use this on direct construction; Pydantic deserialization
        promotes automatically via the discriminated-union dispatch on
        [`ModelRequestPart`][pydantic_ai.messages.ModelRequestPart].
        """
        kind = tool_kind if tool_kind is not None else part.tool_kind
        if kind is None:
            return part
        narrower = _TOOL_RETURN_NARROWERS.get(kind)
        return narrower(part) if narrower else part

part_kind class-attribute instance-attribute

part_kind: Literal['tool-return'] = 'tool-return'

Part type identifier, this is available on all parts as a discriminator.

narrow_type staticmethod

narrow_type(
    part: ToolReturnPart,
    *,
    tool_kind: ToolPartKind | None = None
) -> ToolReturnPart

Promote a base ToolReturnPart to its typed subclass when its tool_kind is registered.

Returns the input unchanged when neither the tool_kind kwarg nor part.tool_kind resolves to a registered subclass. Pass tool_kind to inject the discriminator inline — the narrower applies it as part of its single dataclass clone, dropping the need for an upstream replace(part, tool_kind=...). Use this on direct construction; Pydantic deserialization promotes automatically via the discriminated-union dispatch on ModelRequestPart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
@staticmethod
def narrow_type(part: ToolReturnPart, *, tool_kind: ToolPartKind | None = None) -> ToolReturnPart:
    """Promote a base `ToolReturnPart` to its typed subclass when its `tool_kind` is registered.

    Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
    to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
    applies it as part of its single dataclass clone, dropping the need for an upstream
    `replace(part, tool_kind=...)`. Use this on direct construction; Pydantic deserialization
    promotes automatically via the discriminated-union dispatch on
    [`ModelRequestPart`][pydantic_ai.messages.ModelRequestPart].
    """
    kind = tool_kind if tool_kind is not None else part.tool_kind
    if kind is None:
        return part
    narrower = _TOOL_RETURN_NARROWERS.get(kind)
    return narrower(part) if narrower else part

NativeToolReturnPart dataclass

Bases: BaseToolReturnPart

A tool return message from a native tool.

For native tools with a stable cross-provider shape (currently tool_search), a NativeToolReturnPart may be promoted to a typed subclass like [NativeToolSearchReturnPart][pydantic_ai.messages.NativeToolSearchReturnPart] with a narrowed content TypedDict. See NativeToolCallPart for the pattern.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
@dataclass(repr=False)
class NativeToolReturnPart(BaseToolReturnPart):
    """A tool return message from a native tool.

    For native tools with a stable cross-provider shape (currently `tool_search`), a
    `NativeToolReturnPart` may be promoted to a typed subclass like
    [`NativeToolSearchReturnPart`][pydantic_ai.messages.NativeToolSearchReturnPart]
    with a narrowed `content` `TypedDict`. See `NativeToolCallPart` for the pattern.
    """

    _: KW_ONLY

    provider_name: str | None = None
    """The name of the provider that generated the response.

    Required to be set when `provider_details` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.
    When this field is set, `provider_name` is required to identify the provider that generated this data."""

    part_kind: Literal['builtin-tool-return'] = 'builtin-tool-return'
    """Part type identifier, this is available on all parts as a discriminator."""

    @staticmethod
    def narrow_type(part: NativeToolReturnPart, *, tool_kind: ToolPartKind | None = None) -> NativeToolReturnPart:
        """Promote a base `NativeToolReturnPart` to its typed subclass when its `tool_kind` is registered.

        Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
        to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
        applies it as part of its single dataclass clone. Use this on direct construction; Pydantic
        deserialization promotes automatically via the discriminated-union dispatch on
        [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
        """
        kind = tool_kind if tool_kind is not None else part.tool_kind
        if kind is None:
            return part
        narrower = _NATIVE_RETURN_NARROWERS.get(kind)
        return narrower(part) if narrower else part

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

Required to be set when provider_details is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically. When this field is set, provider_name is required to identify the provider that generated this data.

part_kind class-attribute instance-attribute

part_kind: Literal["builtin-tool-return"] = (
    "builtin-tool-return"
)

Part type identifier, this is available on all parts as a discriminator.

narrow_type staticmethod

narrow_type(
    part: NativeToolReturnPart,
    *,
    tool_kind: ToolPartKind | None = None
) -> NativeToolReturnPart

Promote a base NativeToolReturnPart to its typed subclass when its tool_kind is registered.

Returns the input unchanged when neither the tool_kind kwarg nor part.tool_kind resolves to a registered subclass. Pass tool_kind to inject the discriminator inline — the narrower applies it as part of its single dataclass clone. Use this on direct construction; Pydantic deserialization promotes automatically via the discriminated-union dispatch on ModelResponsePart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
@staticmethod
def narrow_type(part: NativeToolReturnPart, *, tool_kind: ToolPartKind | None = None) -> NativeToolReturnPart:
    """Promote a base `NativeToolReturnPart` to its typed subclass when its `tool_kind` is registered.

    Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
    to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
    applies it as part of its single dataclass clone. Use this on direct construction; Pydantic
    deserialization promotes automatically via the discriminated-union dispatch on
    [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
    """
    kind = tool_kind if tool_kind is not None else part.tool_kind
    if kind is None:
        return part
    narrower = _NATIVE_RETURN_NARROWERS.get(kind)
    return narrower(part) if narrower else part

RetryPromptPart dataclass

A message back to a model asking it to try again.

This can be sent for a number of reasons:

  • Pydantic validation of tool arguments failed, here content is derived from a Pydantic ValidationError
  • a tool raised a ModelRetry exception
  • no tool was found for the tool name
  • the model returned plain text when a structured response was expected
  • Pydantic validation of a structured response failed, here content is derived from a Pydantic ValidationError
  • an output validator raised a ModelRetry exception
Source code in pydantic_ai_slim/pydantic_ai/messages.py
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
@dataclass(repr=False)
class RetryPromptPart:
    """A message back to a model asking it to try again.

    This can be sent for a number of reasons:

    * Pydantic validation of tool arguments failed, here content is derived from a Pydantic
      [`ValidationError`][pydantic_core.ValidationError]
    * a tool raised a [`ModelRetry`][pydantic_ai.exceptions.ModelRetry] exception
    * no tool was found for the tool name
    * the model returned plain text when a structured response was expected
    * Pydantic validation of a structured response failed, here content is derived from a Pydantic
      [`ValidationError`][pydantic_core.ValidationError]
    * an output validator raised a [`ModelRetry`][pydantic_ai.exceptions.ModelRetry] exception
    """

    content: list[pydantic_core.ErrorDetails] | str
    """Details of why and how the model should retry.

    If the retry was triggered by a [`ValidationError`][pydantic_core.ValidationError], this will be a list of
    error details.
    """

    _: KW_ONLY

    tool_name: str | None = None
    """The name of the tool that was called, if any."""

    tool_call_id: str = field(default_factory=_generate_tool_call_id)
    """The tool call identifier, this is used by some models including OpenAI.

    In case the tool call id is not provided by the model, Pydantic AI will generate a random one.
    """

    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp, when the retry was triggered."""

    part_kind: Literal['retry-prompt'] = 'retry-prompt'
    """Part type identifier, this is available on all parts as a discriminator."""

    def model_response(self) -> str:
        """Return a string message describing why the retry is requested."""
        if isinstance(self.content, str):
            if self.tool_name is None:
                description = f'Validation feedback:\n{self.content}'
            else:
                description = self.content
        else:
            # For NativeOutput retries (no `tool_name`) the generated JSON is already in the model's
            # context, so top-level errors' `input` just duplicates it. Tool-call retries keep `input`
            # so the model sees what arguments it sent alongside the error.
            if self.tool_name is None:
                exclude = {
                    i: {'ctx', 'input'} if len(e.get('loc', ())) <= 1 else {'ctx'} for i, e in enumerate(self.content)
                }
            else:
                exclude = {'__all__': {'ctx'}}
            json_errors = error_details_ta.dump_json(self.content, exclude=exclude, indent=2)
            plural = isinstance(self.content, list) and len(self.content) != 1
            description = (
                f'{len(self.content)} validation error{"s" if plural else ""}:\n```json\n{json_errors.decode()}\n```'
            )
        return f'{description}\n\nFix the errors and try again.'

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        if self.tool_name is None:
            return [_otel_messages.TextPart(type='text', content=self.model_response())]
        else:
            part = _otel_messages.ToolCallResponsePart(
                type='tool_call_response',
                id=self.tool_call_id,
                name=self.tool_name,
            )

            if settings.include_content:
                part['result'] = self.model_response()

            return [part]

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: list[ErrorDetails] | str

Details of why and how the model should retry.

If the retry was triggered by a ValidationError, this will be a list of error details.

tool_name class-attribute instance-attribute

tool_name: str | None = None

The name of the tool that was called, if any.

tool_call_id class-attribute instance-attribute

tool_call_id: str = field(
    default_factory=generate_tool_call_id
)

The tool call identifier, this is used by some models including OpenAI.

In case the tool call id is not provided by the model, Pydantic AI will generate a random one.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp, when the retry was triggered.

part_kind class-attribute instance-attribute

part_kind: Literal['retry-prompt'] = 'retry-prompt'

Part type identifier, this is available on all parts as a discriminator.

model_response

model_response() -> str

Return a string message describing why the retry is requested.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
def model_response(self) -> str:
    """Return a string message describing why the retry is requested."""
    if isinstance(self.content, str):
        if self.tool_name is None:
            description = f'Validation feedback:\n{self.content}'
        else:
            description = self.content
    else:
        # For NativeOutput retries (no `tool_name`) the generated JSON is already in the model's
        # context, so top-level errors' `input` just duplicates it. Tool-call retries keep `input`
        # so the model sees what arguments it sent alongside the error.
        if self.tool_name is None:
            exclude = {
                i: {'ctx', 'input'} if len(e.get('loc', ())) <= 1 else {'ctx'} for i, e in enumerate(self.content)
            }
        else:
            exclude = {'__all__': {'ctx'}}
        json_errors = error_details_ta.dump_json(self.content, exclude=exclude, indent=2)
        plural = isinstance(self.content, list) and len(self.content) != 1
        description = (
            f'{len(self.content)} validation error{"s" if plural else ""}:\n```json\n{json_errors.decode()}\n```'
        )
    return f'{description}\n\nFix the errors and try again.'

InstructionPart dataclass

A single instruction block with metadata about its origin.

Instructions are composed of one or more parts, each of which can be static (from a literal string) or dynamic (from a function, template, or toolset). This distinction allows model implementations to make intelligent caching decisions — e.g. Anthropic's prompt caching can cache the static prefix while leaving dynamic instructions uncached.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
@dataclass(repr=False)
class InstructionPart:
    """A single instruction block with metadata about its origin.

    Instructions are composed of one or more parts, each of which can be static (from a literal string)
    or dynamic (from a function, template, or toolset). This distinction allows model implementations
    to make intelligent caching decisions — e.g. Anthropic's prompt caching can cache the static prefix
    while leaving dynamic instructions uncached.
    """

    content: str
    """The text content of this instruction block."""

    _: KW_ONLY

    dynamic: bool = False
    """Whether this instruction came from a dynamic source (function, template, or toolset).

    Static instructions (`dynamic=False`) come from literal strings passed to `Agent(instructions=...)`.
    Dynamic instructions (`dynamic=True`) come from `@agent.instructions` functions, `TemplateStr`,
    or toolset `get_instructions()` methods.
    """

    part_kind: Literal['instruction'] = 'instruction'
    """Part type identifier, used as a discriminator for deserialization."""

    @staticmethod
    def join(parts: Sequence[InstructionPart]) -> str | None:
        """Join instruction parts into a single string, separated by double newlines."""
        return '\n\n'.join(p.content for p in parts).strip() or None

    @staticmethod
    def sorted(parts: Sequence[InstructionPart]) -> list[InstructionPart]:
        """Sort instruction parts with static (`dynamic=False`) before dynamic, preserving relative order."""
        return sorted(parts, key=lambda p: p.dynamic)

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str

The text content of this instruction block.

dynamic class-attribute instance-attribute

dynamic: bool = False

Whether this instruction came from a dynamic source (function, template, or toolset).

Static instructions (dynamic=False) come from literal strings passed to Agent(instructions=...). Dynamic instructions (dynamic=True) come from @agent.instructions functions, TemplateStr, or toolset get_instructions() methods.

part_kind class-attribute instance-attribute

part_kind: Literal['instruction'] = 'instruction'

Part type identifier, used as a discriminator for deserialization.

join staticmethod

join(parts: Sequence[InstructionPart]) -> str | None

Join instruction parts into a single string, separated by double newlines.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1480
1481
1482
1483
@staticmethod
def join(parts: Sequence[InstructionPart]) -> str | None:
    """Join instruction parts into a single string, separated by double newlines."""
    return '\n\n'.join(p.content for p in parts).strip() or None

sorted staticmethod

Sort instruction parts with static (dynamic=False) before dynamic, preserving relative order.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1485
1486
1487
1488
@staticmethod
def sorted(parts: Sequence[InstructionPart]) -> list[InstructionPart]:
    """Sort instruction parts with static (`dynamic=False`) before dynamic, preserving relative order."""
    return sorted(parts, key=lambda p: p.dynamic)

ModelRequest dataclass

A request generated by Pydantic AI and sent to a model, e.g. a message from the Pydantic AI app to the model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
@dataclass(repr=False)
class ModelRequest:
    """A request generated by Pydantic AI and sent to a model, e.g. a message from the Pydantic AI app to the model."""

    parts: Sequence[ModelRequestPart]
    """The parts of the user message."""

    _: KW_ONLY

    # Default is None for backwards compatibility with old serialized messages that don't have this field.
    # Using a default_factory would incorrectly fill in the current time for deserialized historical messages.
    timestamp: datetime | None = None
    """The timestamp when the request was sent to the model."""

    instructions: str | None = None
    """The instructions string for this request, rendered from structured instruction parts."""

    kind: Literal['request'] = 'request'
    """Message type identifier, this is available on all parts as a discriminator."""

    run_id: str | None = None
    """The unique identifier of the agent run in which this message originated."""

    conversation_id: str | None = None
    """The unique identifier of the conversation this message belongs to.

    A conversation spans potentially multiple agent runs that share message history.
    Emitted as the `gen_ai.conversation.id` OpenTelemetry span attribute on the agent run.
    """

    metadata: dict[str, Any] | None = None
    """Additional data that can be accessed programmatically by the application but is not sent to the LLM."""

    state: ModelRequestState = 'complete'
    """Lifecycle state of the request.

    Set to `'interrupted'` when the request was being assembled (e.g. collecting tool returns) and
    the run was abnormally terminated by an exception or cancellation before the request was sent to the model.
    Appears in [`capture_run_messages`][pydantic_ai.capture_run_messages] output so consumers can detect partial state.
    """

    @classmethod
    def user_text_prompt(cls, user_prompt: str, *, instructions: str | None = None) -> ModelRequest:
        """Create a `ModelRequest` with a single user prompt as text."""
        return cls(parts=[UserPromptPart(user_prompt)], instructions=instructions)

    __repr__ = _utils.dataclasses_no_defaults_repr

parts instance-attribute

The parts of the user message.

timestamp class-attribute instance-attribute

timestamp: datetime | None = None

The timestamp when the request was sent to the model.

instructions class-attribute instance-attribute

instructions: str | None = None

The instructions string for this request, rendered from structured instruction parts.

kind class-attribute instance-attribute

kind: Literal['request'] = 'request'

Message type identifier, this is available on all parts as a discriminator.

run_id class-attribute instance-attribute

run_id: str | None = None

The unique identifier of the agent run in which this message originated.

conversation_id class-attribute instance-attribute

conversation_id: str | None = None

The unique identifier of the conversation this message belongs to.

A conversation spans potentially multiple agent runs that share message history. Emitted as the gen_ai.conversation.id OpenTelemetry span attribute on the agent run.

metadata class-attribute instance-attribute

metadata: dict[str, Any] | None = None

Additional data that can be accessed programmatically by the application but is not sent to the LLM.

state class-attribute instance-attribute

state: ModelRequestState = 'complete'

Lifecycle state of the request.

Set to 'interrupted' when the request was being assembled (e.g. collecting tool returns) and the run was abnormally terminated by an exception or cancellation before the request was sent to the model. Appears in capture_run_messages output so consumers can detect partial state.

user_text_prompt classmethod

user_text_prompt(
    user_prompt: str, *, instructions: str | None = None
) -> ModelRequest

Create a ModelRequest with a single user prompt as text.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1534
1535
1536
1537
@classmethod
def user_text_prompt(cls, user_prompt: str, *, instructions: str | None = None) -> ModelRequest:
    """Create a `ModelRequest` with a single user prompt as text."""
    return cls(parts=[UserPromptPart(user_prompt)], instructions=instructions)

TextPart dataclass

A plain text response from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
@dataclass(repr=False)
class TextPart:
    """A plain text response from a model."""

    content: str
    """The text content of the response."""

    _: KW_ONLY

    id: str | None = None
    """An optional identifier of the text part.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    provider_name: str | None = None
    """The name of the provider that generated the response.

    Required to be set when `provider_details` or `id` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_kind: Literal['text'] = 'text'
    """Part type identifier, this is available on all parts as a discriminator."""

    def has_content(self) -> bool:
        """Return `True` if the text content is non-empty."""
        return bool(self.content)

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str

The text content of the response.

id class-attribute instance-attribute

id: str | None = None

An optional identifier of the text part.

When this field is set, provider_name is required to identify the provider that generated this data.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

Required to be set when provider_details or id is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically. When this field is set, provider_name is required to identify the provider that generated this data.

part_kind class-attribute instance-attribute

part_kind: Literal['text'] = 'text'

Part type identifier, this is available on all parts as a discriminator.

has_content

has_content() -> bool

Return True if the text content is non-empty.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1573
1574
1575
def has_content(self) -> bool:
    """Return `True` if the text content is non-empty."""
    return bool(self.content)

ThinkingPart dataclass

A thinking response from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
@dataclass(repr=False)
class ThinkingPart:
    """A thinking response from a model."""

    content: str
    """The thinking content of the response."""

    _: KW_ONLY

    id: str | None = None
    """The identifier of the thinking part.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    signature: str | None = None
    """The signature of the thinking.

    Supported by:

    * Anthropic (corresponds to the `signature` field)
    * Bedrock (corresponds to the `signature` field)
    * Google (corresponds to the `thought_signature` field)
    * OpenAI (corresponds to the `encrypted_content` field)

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    provider_name: str | None = None
    """The name of the provider that generated the response.

    Signatures are only sent back to the same provider.
    Required to be set when `provider_details`, `id` or `signature` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_kind: Literal['thinking'] = 'thinking'
    """Part type identifier, this is available on all parts as a discriminator."""

    def has_content(self) -> bool:
        """Return `True` if the thinking content is non-empty."""
        return bool(self.content)

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

content: str

The thinking content of the response.

id class-attribute instance-attribute

id: str | None = None

The identifier of the thinking part.

When this field is set, provider_name is required to identify the provider that generated this data.

signature class-attribute instance-attribute

signature: str | None = None

The signature of the thinking.

Supported by:

  • Anthropic (corresponds to the signature field)
  • Bedrock (corresponds to the signature field)
  • Google (corresponds to the thought_signature field)
  • OpenAI (corresponds to the encrypted_content field)

When this field is set, provider_name is required to identify the provider that generated this data.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

Signatures are only sent back to the same provider. Required to be set when provider_details, id or signature is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically. When this field is set, provider_name is required to identify the provider that generated this data.

part_kind class-attribute instance-attribute

part_kind: Literal['thinking'] = 'thinking'

Part type identifier, this is available on all parts as a discriminator.

has_content

has_content() -> bool

Return True if the thinking content is non-empty.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1625
1626
1627
def has_content(self) -> bool:
    """Return `True` if the thinking content is non-empty."""
    return bool(self.content)

CompactionPart dataclass

A compaction part that summarizes previous conversation history.

Compaction parts contain an opaque or readable summary of prior messages, produced by provider-specific compaction mechanisms. They must be round-tripped back to the same provider in subsequent requests.

For Anthropic, content contains a readable text summary. For OpenAI, content is None and the encrypted data is stored in provider_details.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
@dataclass(repr=False)
class CompactionPart:
    """A compaction part that summarizes previous conversation history.

    Compaction parts contain an opaque or readable summary of prior messages,
    produced by provider-specific compaction mechanisms. They must be round-tripped
    back to the same provider in subsequent requests.

    For Anthropic, `content` contains a readable text summary.
    For OpenAI, `content` is `None` and the encrypted data is stored in `provider_details`.
    """

    content: str | None = None
    """The compaction summary text, if available.

    For Anthropic: a readable text summary of compacted messages.
    For OpenAI: `None` (the compacted content is encrypted and stored in `provider_details`).
    """

    _: KW_ONLY

    id: str | None = None
    """The identifier of the compaction part.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    provider_name: str | None = None
    """The name of the provider that generated the compaction.

    Compaction data is only sent back to the same provider.
    Required to be set when `provider_details` or `id` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    For OpenAI: contains `encrypted_content` and other fields from `ResponseCompactionItem`.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_kind: Literal['compaction'] = 'compaction'
    """Part type identifier, this is available on all parts as a discriminator."""

    def has_content(self) -> bool:
        """Return `True` if the compaction content is non-empty."""
        return bool(self.content)

    __repr__ = _utils.dataclasses_no_defaults_repr

content class-attribute instance-attribute

content: str | None = None

The compaction summary text, if available.

For Anthropic: a readable text summary of compacted messages. For OpenAI: None (the compacted content is encrypted and stored in provider_details).

id class-attribute instance-attribute

id: str | None = None

The identifier of the compaction part.

When this field is set, provider_name is required to identify the provider that generated this data.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the compaction.

Compaction data is only sent back to the same provider. Required to be set when provider_details or id is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

For OpenAI: contains encrypted_content and other fields from ResponseCompactionItem. When this field is set, provider_name is required to identify the provider that generated this data.

part_kind class-attribute instance-attribute

part_kind: Literal['compaction'] = 'compaction'

Part type identifier, this is available on all parts as a discriminator.

has_content

has_content() -> bool

Return True if the compaction content is non-empty.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1676
1677
1678
def has_content(self) -> bool:
    """Return `True` if the compaction content is non-empty."""
    return bool(self.content)

FilePart dataclass

A file response from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
@dataclass(repr=False)
class FilePart:
    """A file response from a model."""

    content: Annotated[BinaryContent, pydantic.AfterValidator(BinaryImage.narrow_type)]
    """The file content of the response."""

    _: KW_ONLY

    id: str | None = None
    """The identifier of the file part.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    provider_name: str | None = None
    """The name of the provider that generated the response.

    Required to be set when `provider_details` or `id` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_kind: Literal['file'] = 'file'
    """Part type identifier, this is available on all parts as a discriminator."""

    def has_content(self) -> bool:
        """Return `True` if the file content is non-empty."""
        return bool(self.content.data)

    __repr__ = _utils.dataclasses_no_defaults_repr

content instance-attribute

The file content of the response.

id class-attribute instance-attribute

id: str | None = None

The identifier of the file part.

When this field is set, provider_name is required to identify the provider that generated this data.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

Required to be set when provider_details or id is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically. When this field is set, provider_name is required to identify the provider that generated this data.

part_kind class-attribute instance-attribute

part_kind: Literal['file'] = 'file'

Part type identifier, this is available on all parts as a discriminator.

has_content

has_content() -> bool

Return True if the file content is non-empty.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1714
1715
1716
def has_content(self) -> bool:
    """Return `True` if the file content is non-empty."""
    return bool(self.content.data)

BaseToolCallPart dataclass

A tool call from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
@dataclass(repr=False)
class BaseToolCallPart:
    """A tool call from a model."""

    tool_name: str
    """The name of the tool to call."""

    args: str | dict[str, Any] | None = None
    """The arguments to pass to the tool.

    This is stored either as a JSON string or a Python dictionary depending on how data was received.
    """

    tool_call_id: str = field(default_factory=_generate_tool_call_id)
    """The tool call identifier, this is used by some models including OpenAI.

    In case the tool call id is not provided by the model, Pydantic AI will generate a random one.
    """

    _: KW_ONLY

    tool_kind: ToolPartKind | None = None
    """Discriminator for the typed subclass of this part (e.g. `'tool-search'`).

    See [`BaseToolReturnPart.tool_kind`][pydantic_ai.messages.BaseToolReturnPart.tool_kind] for
    the full semantics.
    """

    id: str | None = None
    """An optional identifier of the tool call part, separate from the tool call ID.

    This is used by some APIs like OpenAI Responses.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    provider_name: str | None = None
    """The name of the provider that generated the response.

    Native tool calls are only sent back to the same provider.
    Required to be set when `provider_details` or `id` is set.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.
    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    def __post_init__(self) -> None:
        # Per-instance attribute populated by the instrumentation layer from
        # `ToolDefinition.metadata` to drive OTel rendering hints (e.g. syntax highlighting).
        # Declared here rather than as a dataclass field so it stays out of `__init__`,
        # equality, repr, Pydantic JSON schema, and serialization.
        self.otel_metadata: _otel_messages.ToolCallPartOtelMetadata | None = None

    def args_as_dict(self, *, raise_if_invalid: bool = False) -> dict[str, Any]:
        """Return the arguments as a Python dictionary.

        This is just for convenience with models that require dicts as input.

        Args:
            raise_if_invalid: If `True`, a `ValueError` or `AssertionError`
                caused by malformed JSON in `args` will be re-raised.  When
                `False` (the default), malformed JSON is handled gracefully by
                returning `{'INVALID_JSON': '<raw args>'}` so that the value
                can still be sent to a model API (e.g. during a retry flow)
                without crashing.
        """
        if not self.args:
            return {}
        if isinstance(self.args, dict):
            return self.args
        try:
            args = pydantic_core.from_json(self.args)
            assert isinstance(args, dict), 'args should be a dict'
            return cast(dict[str, Any], args)
        except (ValueError, AssertionError):
            if raise_if_invalid:
                raise
            return {INVALID_JSON_KEY: self.args}

    def args_as_json_str(self) -> str:
        """Return the arguments as a JSON string.

        This is just for convenience with models that require JSON strings as input.
        """
        if not self.args:
            return '{}'
        if isinstance(self.args, str):
            return self.args
        return pydantic_core.to_json(self.args).decode()

    def has_content(self) -> bool:
        """Return `True` if the tool call has content."""
        return self.args not in ('', {}, None)

    __repr__ = _utils.dataclasses_no_defaults_repr

tool_name instance-attribute

tool_name: str

The name of the tool to call.

args class-attribute instance-attribute

args: str | dict[str, Any] | None = None

The arguments to pass to the tool.

This is stored either as a JSON string or a Python dictionary depending on how data was received.

tool_call_id class-attribute instance-attribute

tool_call_id: str = field(
    default_factory=generate_tool_call_id
)

The tool call identifier, this is used by some models including OpenAI.

In case the tool call id is not provided by the model, Pydantic AI will generate a random one.

tool_kind class-attribute instance-attribute

tool_kind: ToolPartKind | None = None

Discriminator for the typed subclass of this part (e.g. 'tool-search').

See BaseToolReturnPart.tool_kind for the full semantics.

id class-attribute instance-attribute

id: str | None = None

An optional identifier of the tool call part, separate from the tool call ID.

This is used by some APIs like OpenAI Responses. When this field is set, provider_name is required to identify the provider that generated this data.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

Native tool calls are only sent back to the same provider. Required to be set when provider_details or id is set.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically. When this field is set, provider_name is required to identify the provider that generated this data.

args_as_dict

args_as_dict(
    *, raise_if_invalid: bool = False
) -> dict[str, Any]

Return the arguments as a Python dictionary.

This is just for convenience with models that require dicts as input.

Parameters:

Name Type Description Default
raise_if_invalid bool

If True, a ValueError or AssertionError caused by malformed JSON in args will be re-raised. When False (the default), malformed JSON is handled gracefully by returning {'INVALID_JSON': '<raw args>'} so that the value can still be sent to a model API (e.g. during a retry flow) without crashing.

False
Source code in pydantic_ai_slim/pydantic_ai/messages.py
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
def args_as_dict(self, *, raise_if_invalid: bool = False) -> dict[str, Any]:
    """Return the arguments as a Python dictionary.

    This is just for convenience with models that require dicts as input.

    Args:
        raise_if_invalid: If `True`, a `ValueError` or `AssertionError`
            caused by malformed JSON in `args` will be re-raised.  When
            `False` (the default), malformed JSON is handled gracefully by
            returning `{'INVALID_JSON': '<raw args>'}` so that the value
            can still be sent to a model API (e.g. during a retry flow)
            without crashing.
    """
    if not self.args:
        return {}
    if isinstance(self.args, dict):
        return self.args
    try:
        args = pydantic_core.from_json(self.args)
        assert isinstance(args, dict), 'args should be a dict'
        return cast(dict[str, Any], args)
    except (ValueError, AssertionError):
        if raise_if_invalid:
            raise
        return {INVALID_JSON_KEY: self.args}

args_as_json_str

args_as_json_str() -> str

Return the arguments as a JSON string.

This is just for convenience with models that require JSON strings as input.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
def args_as_json_str(self) -> str:
    """Return the arguments as a JSON string.

    This is just for convenience with models that require JSON strings as input.
    """
    if not self.args:
        return '{}'
    if isinstance(self.args, str):
        return self.args
    return pydantic_core.to_json(self.args).decode()

has_content

has_content() -> bool

Return True if the tool call has content.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1814
1815
1816
def has_content(self) -> bool:
    """Return `True` if the tool call has content."""
    return self.args not in ('', {}, None)

ToolCallPart dataclass

Bases: BaseToolCallPart

A tool call from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
@dataclass(repr=False)
class ToolCallPart(BaseToolCallPart):
    """A tool call from a model."""

    _: KW_ONLY

    part_kind: Literal['tool-call'] = 'tool-call'
    """Part type identifier, this is available on all parts as a discriminator. Note that this is different from `ToolCallPartDelta.part_delta_kind`."""

    @staticmethod
    def narrow_type(part: ToolCallPart, *, tool_kind: ToolPartKind | None = None) -> ToolCallPart:
        """Promote a base `ToolCallPart` to its typed subclass when its `tool_kind` is registered.

        Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
        to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
        applies it as part of its single dataclass clone, dropping the need for an upstream
        `replace(part, tool_kind=...)`. Use this on direct construction; Pydantic deserialization
        promotes automatically via the discriminated-union dispatch on
        [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
        """
        kind = tool_kind if tool_kind is not None else part.tool_kind
        if kind is None:
            return part
        narrower = _TOOL_CALL_NARROWERS.get(kind)
        return narrower(part) if narrower else part

part_kind class-attribute instance-attribute

part_kind: Literal['tool-call'] = 'tool-call'

Part type identifier, this is available on all parts as a discriminator. Note that this is different from ToolCallPartDelta.part_delta_kind.

narrow_type staticmethod

narrow_type(
    part: ToolCallPart,
    *,
    tool_kind: ToolPartKind | None = None
) -> ToolCallPart

Promote a base ToolCallPart to its typed subclass when its tool_kind is registered.

Returns the input unchanged when neither the tool_kind kwarg nor part.tool_kind resolves to a registered subclass. Pass tool_kind to inject the discriminator inline — the narrower applies it as part of its single dataclass clone, dropping the need for an upstream replace(part, tool_kind=...). Use this on direct construction; Pydantic deserialization promotes automatically via the discriminated-union dispatch on ModelResponsePart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
@staticmethod
def narrow_type(part: ToolCallPart, *, tool_kind: ToolPartKind | None = None) -> ToolCallPart:
    """Promote a base `ToolCallPart` to its typed subclass when its `tool_kind` is registered.

    Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
    to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
    applies it as part of its single dataclass clone, dropping the need for an upstream
    `replace(part, tool_kind=...)`. Use this on direct construction; Pydantic deserialization
    promotes automatically via the discriminated-union dispatch on
    [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
    """
    kind = tool_kind if tool_kind is not None else part.tool_kind
    if kind is None:
        return part
    narrower = _TOOL_CALL_NARROWERS.get(kind)
    return narrower(part) if narrower else part

NativeToolCallPart dataclass

Bases: BaseToolCallPart

A tool call to a native tool.

For native tools with a stable cross-provider shape (currently tool_search), this base class can be promoted to a typed subclass with a narrowed args TypedDict. See [NativeToolSearchCallPart][pydantic_ai.messages.NativeToolSearchCallPart] for the canonical example.

Adding a typed subclass for a future native tool (see pydantic_ai._tool_search for a worked example):

  1. Add a sibling pydantic_ai/_<name>.py module that defines the cross-provider TypedDicts, the NativeToolCallPart / NativeToolReturnPart subclasses, and registers their narrowers into _NATIVE_CALL_NARROWERS / _NATIVE_RETURN_NARROWERS keyed by tool_kind. Subclass overrides tool_kind: Literal['<emitter>'] to match the emitting AbstractNativeTool.kind, and shadows args / content with a narrower type.
  2. Late-import the new module from this file (alongside the existing tool-search import) so registration runs whenever pydantic_ai.messages is imported.
  3. Add the subclass to ModelResponsePart's discriminated union and to _model_response_part_discriminator so Pydantic deserialization auto-promotes on model_validate / model_validate_json.

Dispatch is by tool_kind, not tool_name. This protects users whose tools happen to share a name with one of ours from accidentally getting their parts promoted (and failing shape validation against the typed args/content).

The provider_details field carries genuinely non-portable provider extras (e.g. Anthropic's strategy: 'bm25' | 'regex' for tool search). Promote a field to a typed slot in args / content only when at least two of OpenAI, Anthropic, and Google support it (cf. issue #3885).

MCP server tools land here with tool_kind='mcp_server' (label stays in tool_name='mcp_server:<label>'); typed-subclass work for MCP is tracked by issue #3561.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
@dataclass(repr=False)
class NativeToolCallPart(BaseToolCallPart):
    """A tool call to a native tool.

    For native tools with a stable cross-provider shape (currently `tool_search`), this base
    class can be promoted to a typed subclass with a narrowed `args` `TypedDict`. See
    [`NativeToolSearchCallPart`][pydantic_ai.messages.NativeToolSearchCallPart] for the
    canonical example.

    Adding a typed subclass for a future native tool (see `pydantic_ai._tool_search` for
    a worked example):

    1. Add a sibling `pydantic_ai/_<name>.py` module that defines the cross-provider
       `TypedDict`s, the `NativeToolCallPart` / `NativeToolReturnPart` subclasses,
       and registers their narrowers into `_NATIVE_CALL_NARROWERS` /
       `_NATIVE_RETURN_NARROWERS` keyed by `tool_kind`. Subclass overrides
       `tool_kind: Literal['<emitter>']` to match the emitting
       [`AbstractNativeTool.kind`][pydantic_ai.native_tools.AbstractNativeTool.kind],
       and shadows `args` / `content` with a narrower type.
    2. Late-import the new module from this file (alongside the existing tool-search
       import) so registration runs whenever `pydantic_ai.messages` is imported.
    3. Add the subclass to `ModelResponsePart`'s discriminated union and to
       `_model_response_part_discriminator` so Pydantic deserialization auto-promotes
       on `model_validate` / `model_validate_json`.

    Dispatch is by `tool_kind`, not `tool_name`. This protects users whose tools happen to
    share a name with one of ours from accidentally getting their parts promoted (and
    failing shape validation against the typed `args`/`content`).

    The `provider_details` field carries genuinely non-portable provider extras
    (e.g. Anthropic's `strategy: 'bm25' | 'regex'` for tool search). Promote a field
    to a typed slot in `args` / `content` only when at least two of OpenAI, Anthropic,
    and Google support it (cf. [issue #3885](https://github.com/pydantic/pydantic-ai/issues/3885)).

    MCP server tools land here with `tool_kind='mcp_server'` (label stays in
    `tool_name='mcp_server:<label>'`); typed-subclass work for MCP is tracked by
    [issue #3561](https://github.com/pydantic/pydantic-ai/issues/3561).
    """

    _: KW_ONLY

    part_kind: Literal['builtin-tool-call'] = 'builtin-tool-call'
    """Part type identifier, this is available on all parts as a discriminator."""

    @staticmethod
    def narrow_type(part: NativeToolCallPart, *, tool_kind: ToolPartKind | None = None) -> NativeToolCallPart:
        """Promote a base `NativeToolCallPart` to its typed subclass when its `tool_kind` is registered.

        Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
        to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
        applies it as part of its single dataclass clone. Use this on direct construction; Pydantic
        deserialization promotes automatically via the discriminated-union dispatch on
        [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
        """
        kind = tool_kind if tool_kind is not None else part.tool_kind
        if kind is None:
            return part
        narrower = _NATIVE_CALL_NARROWERS.get(kind)
        return narrower(part) if narrower else part

part_kind class-attribute instance-attribute

part_kind: Literal["builtin-tool-call"] = (
    "builtin-tool-call"
)

Part type identifier, this is available on all parts as a discriminator.

narrow_type staticmethod

narrow_type(
    part: NativeToolCallPart,
    *,
    tool_kind: ToolPartKind | None = None
) -> NativeToolCallPart

Promote a base NativeToolCallPart to its typed subclass when its tool_kind is registered.

Returns the input unchanged when neither the tool_kind kwarg nor part.tool_kind resolves to a registered subclass. Pass tool_kind to inject the discriminator inline — the narrower applies it as part of its single dataclass clone. Use this on direct construction; Pydantic deserialization promotes automatically via the discriminated-union dispatch on ModelResponsePart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
@staticmethod
def narrow_type(part: NativeToolCallPart, *, tool_kind: ToolPartKind | None = None) -> NativeToolCallPart:
    """Promote a base `NativeToolCallPart` to its typed subclass when its `tool_kind` is registered.

    Returns the input unchanged when neither the `tool_kind` kwarg nor `part.tool_kind` resolves
    to a registered subclass. Pass `tool_kind` to inject the discriminator inline — the narrower
    applies it as part of its single dataclass clone. Use this on direct construction; Pydantic
    deserialization promotes automatically via the discriminated-union dispatch on
    [`ModelResponsePart`][pydantic_ai.messages.ModelResponsePart].
    """
    kind = tool_kind if tool_kind is not None else part.tool_kind
    if kind is None:
        return part
    narrower = _NATIVE_CALL_NARROWERS.get(kind)
    return narrower(part) if narrower else part

ModelRequestPart module-attribute

ModelRequestPart = Annotated[
    Annotated[SystemPromptPart, Tag("system-prompt")]
    | Annotated[UserPromptPart, Tag("user-prompt")]
    | Annotated[
        ToolSearchReturnPart, Tag("tool-search-return")
    ]
    | Annotated[ToolReturnPart, Tag("tool-return")]
    | Annotated[RetryPromptPart, Tag("retry-prompt")],
    Discriminator(_model_request_part_discriminator),
]

A message part sent by Pydantic AI to a model.

ModelResponsePart module-attribute

ModelResponsePart = Annotated[
    Annotated[TextPart, Tag("text")]
    | Annotated[ToolSearchCallPart, Tag("tool-search-call")]
    | Annotated[ToolCallPart, Tag("tool-call")]
    | Annotated[
        NativeToolSearchCallPart,
        Tag("builtin-tool-search-call"),
    ]
    | Annotated[
        NativeToolCallPart, Tag("builtin-tool-call")
    ]
    | Annotated[
        NativeToolSearchReturnPart,
        Tag("builtin-tool-search-return"),
    ]
    | Annotated[
        NativeToolReturnPart, Tag("builtin-tool-return")
    ]
    | Annotated[ThinkingPart, Tag("thinking")]
    | Annotated[CompactionPart, Tag("compaction")]
    | Annotated[FilePart, Tag("file")],
    Discriminator(_model_response_part_discriminator),
]

A message part returned by a model.

ModelResponse dataclass

A response from a model, e.g. a message from the model to the Pydantic AI app.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
@dataclass(repr=False)
class ModelResponse:
    """A response from a model, e.g. a message from the model to the Pydantic AI app."""

    parts: Sequence[ModelResponsePart]
    """The parts of the model message."""

    _: KW_ONLY

    usage: RequestUsage = field(default_factory=RequestUsage)
    """Usage information for the request.

    This has a default to make tests easier, and to support loading old messages where usage will be missing.
    """

    model_name: str | None = None
    """The name of the model that generated the response."""

    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp when the response was received locally.

    This is always a high-precision local datetime. Provider-specific timestamps
    (if available) are stored in `provider_details['timestamp']`.
    """

    kind: Literal['response'] = 'response'
    """Message type identifier, this is available on all parts as a discriminator."""

    provider_name: str | None = None
    """The name of the LLM provider that generated the response."""

    provider_url: str | None = None
    """The base URL of the LLM provider that generated the response."""

    provider_details: Annotated[
        dict[str, Any] | None,
        # `vendor_details` is deprecated, but we still want to support deserializing model responses stored in a DB before the name was changed
        pydantic.Field(validation_alias=pydantic.AliasChoices('provider_details', 'vendor_details')),
    ] = None
    """Additional data returned by the provider that can't be mapped to standard fields."""

    provider_response_id: Annotated[
        str | None,
        # `vendor_id` is deprecated, but we still want to support deserializing model responses stored in a DB before the name was changed
        pydantic.Field(validation_alias=pydantic.AliasChoices('provider_response_id', 'vendor_id')),
    ] = None
    """request ID as specified by the model provider. This can be used to track the specific request to the model."""

    finish_reason: FinishReason | None = None
    """Reason the model finished generating the response, normalized to OpenTelemetry values."""

    run_id: str | None = None
    """The unique identifier of the agent run in which this message originated."""

    conversation_id: str | None = None
    """The unique identifier of the conversation this message belongs to.

    A conversation spans potentially multiple agent runs that share message history.
    Emitted as the `gen_ai.conversation.id` OpenTelemetry span attribute on the agent run.
    """

    metadata: dict[str, Any] | None = None
    """Additional data that can be accessed programmatically by the application but is not sent to the LLM."""

    state: ModelResponseState = 'complete'
    """Lifecycle state of the response. See [`ModelResponseState`][pydantic_ai.messages.ModelResponseState]."""

    @property
    def text(self) -> str | None:
        """Get the text in the response."""
        texts: list[str] = []
        last_part: ModelResponsePart | None = None
        for part in self.parts:
            if isinstance(part, TextPart):
                # Adjacent text parts should be joined together, but if there are parts in between
                # (like built-in tool calls) they should have newlines between them
                if isinstance(last_part, TextPart):
                    texts[-1] += part.content
                else:
                    texts.append(part.content)
            last_part = part
        if not texts:
            return None

        return '\n\n'.join(texts)

    @property
    def thinking(self) -> str | None:
        """Get the thinking in the response."""
        thinking_parts = [part.content for part in self.parts if isinstance(part, ThinkingPart)]
        if not thinking_parts:
            return None
        return '\n\n'.join(thinking_parts)

    @property
    def files(self) -> list[BinaryContent]:
        """Get the files in the response."""
        return [part.content for part in self.parts if isinstance(part, FilePart)]

    @property
    def images(self) -> list[BinaryImage]:
        """Get the images in the response."""
        return [file for file in self.files if isinstance(file, BinaryImage)]

    @property
    def tool_calls(self) -> list[ToolCallPart]:
        """Get the tool calls in the response."""
        return [part for part in self.parts if isinstance(part, ToolCallPart)]

    @property
    def native_tool_calls(self) -> list[tuple[NativeToolCallPart, NativeToolReturnPart]]:
        """Get the native tool calls and results in the response."""
        calls = [part for part in self.parts if isinstance(part, NativeToolCallPart)]
        if not calls:
            return []
        returns_by_id = {part.tool_call_id: part for part in self.parts if isinstance(part, NativeToolReturnPart)}
        return [
            (call_part, returns_by_id[call_part.tool_call_id])
            for call_part in calls
            if call_part.tool_call_id in returns_by_id
        ]

    def cost(self) -> genai_types.PriceCalculation:
        """Calculate the cost of the usage.

        Uses [`genai-prices`](https://github.com/pydantic/genai-prices).
        """
        assert self.model_name, 'Model name is required to calculate price'
        # Try matching on provider_api_url first as this is more specific, then fall back to provider_id.
        if self.provider_url:
            try:
                return calc_price(
                    self.usage,
                    self.model_name,
                    provider_api_url=self.provider_url,
                    genai_request_timestamp=self.timestamp,
                )
            except LookupError:
                pass
        return calc_price(
            self.usage,
            self.model_name,
            provider_id=self.provider_name,
            genai_request_timestamp=self.timestamp,
        )

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        parts: list[_otel_messages.MessagePart] = []
        for part in self.parts:
            if isinstance(part, TextPart):
                parts.append(
                    _otel_messages.TextPart(
                        type='text',
                        **({'content': part.content} if settings.include_content else {}),
                    )
                )
            elif isinstance(part, ThinkingPart):
                parts.append(
                    _otel_messages.ThinkingPart(
                        type='thinking',
                        **({'content': part.content} if settings.include_content else {}),
                    )
                )
            elif isinstance(part, FilePart):
                parts.append(
                    _convert_binary_to_otel_part(part.content.media_type, lambda p=part: p.content.base64, settings)
                )
            elif isinstance(part, BaseToolCallPart):
                call_part = _otel_messages.ToolCallPart(type='tool_call', id=part.tool_call_id, name=part.tool_name)
                if isinstance(part, NativeToolCallPart):
                    call_part['builtin'] = True
                if part.otel_metadata:
                    if code_arg_name := part.otel_metadata.get('code_arg_name'):
                        call_part['code_arg_name'] = code_arg_name
                    if code_arg_language := part.otel_metadata.get('code_arg_language'):
                        call_part['code_arg_language'] = code_arg_language
                if settings.include_content and part.args is not None:
                    if isinstance(part.args, str):
                        call_part['arguments'] = part.args
                    else:
                        call_part['arguments'] = {k: serialize_any(v) for k, v in part.args.items()}

                parts.append(call_part)
            elif isinstance(part, NativeToolReturnPart):
                return_part = _otel_messages.ToolCallResponsePart(
                    type='tool_call_response',
                    id=part.tool_call_id,
                    name=part.tool_name,
                    builtin=True,
                )
                if settings.include_content and part.content is not None:  # pragma: no branch
                    return_part['result'] = serialize_any(part.content)

                parts.append(return_part)
            elif isinstance(part, CompactionPart):
                # Compaction parts don't map to standard OTel message part types
                pass
        return parts

    __repr__ = _utils.dataclasses_no_defaults_repr

parts instance-attribute

The parts of the model message.

usage class-attribute instance-attribute

usage: RequestUsage = field(default_factory=RequestUsage)

Usage information for the request.

This has a default to make tests easier, and to support loading old messages where usage will be missing.

model_name class-attribute instance-attribute

model_name: str | None = None

The name of the model that generated the response.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp when the response was received locally.

This is always a high-precision local datetime. Provider-specific timestamps (if available) are stored in provider_details['timestamp'].

kind class-attribute instance-attribute

kind: Literal['response'] = 'response'

Message type identifier, this is available on all parts as a discriminator.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the LLM provider that generated the response.

provider_url class-attribute instance-attribute

provider_url: str | None = None

The base URL of the LLM provider that generated the response.

provider_details class-attribute instance-attribute

provider_details: Annotated[
    dict[str, Any] | None,
    Field(
        validation_alias=AliasChoices(
            provider_details, vendor_details
        )
    ),
] = None

Additional data returned by the provider that can't be mapped to standard fields.

provider_response_id class-attribute instance-attribute

provider_response_id: Annotated[
    str | None,
    Field(
        validation_alias=AliasChoices(
            provider_response_id, vendor_id
        )
    ),
] = None

request ID as specified by the model provider. This can be used to track the specific request to the model.

finish_reason class-attribute instance-attribute

finish_reason: FinishReason | None = None

Reason the model finished generating the response, normalized to OpenTelemetry values.

run_id class-attribute instance-attribute

run_id: str | None = None

The unique identifier of the agent run in which this message originated.

conversation_id class-attribute instance-attribute

conversation_id: str | None = None

The unique identifier of the conversation this message belongs to.

A conversation spans potentially multiple agent runs that share message history. Emitted as the gen_ai.conversation.id OpenTelemetry span attribute on the agent run.

metadata class-attribute instance-attribute

metadata: dict[str, Any] | None = None

Additional data that can be accessed programmatically by the application but is not sent to the LLM.

state class-attribute instance-attribute

state: ModelResponseState = 'complete'

Lifecycle state of the response. See ModelResponseState.

text property

text: str | None

Get the text in the response.

thinking property

thinking: str | None

Get the thinking in the response.

files property

Get the files in the response.

images property

images: list[BinaryImage]

Get the images in the response.

tool_calls property

tool_calls: list[ToolCallPart]

Get the tool calls in the response.

native_tool_calls property

Get the native tool calls and results in the response.

cost

cost() -> PriceCalculation

Calculate the cost of the usage.

Uses genai-prices.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
def cost(self) -> genai_types.PriceCalculation:
    """Calculate the cost of the usage.

    Uses [`genai-prices`](https://github.com/pydantic/genai-prices).
    """
    assert self.model_name, 'Model name is required to calculate price'
    # Try matching on provider_api_url first as this is more specific, then fall back to provider_id.
    if self.provider_url:
        try:
            return calc_price(
                self.usage,
                self.model_name,
                provider_api_url=self.provider_url,
                genai_request_timestamp=self.timestamp,
            )
        except LookupError:
            pass
    return calc_price(
        self.usage,
        self.model_name,
        provider_id=self.provider_name,
        genai_request_timestamp=self.timestamp,
    )

ModelMessage module-attribute

ModelMessage = Annotated[
    ModelRequest | ModelResponse, Discriminator("kind")
]

Any message sent to or returned by a model.

ModelMessagesTypeAdapter module-attribute

ModelMessagesTypeAdapter = TypeAdapter(
    list[ModelMessage],
    config=ConfigDict(
        defer_build=True,
        ser_json_bytes="base64",
        val_json_bytes="base64",
    ),
)

Pydantic TypeAdapter for (de)serializing messages.

TextPartDelta dataclass

A partial update (delta) for a TextPart to append new text content.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
@dataclass(repr=False)
class TextPartDelta:
    """A partial update (delta) for a `TextPart` to append new text content."""

    content_delta: str
    """The incremental text content to add to the existing `TextPart` content."""

    _: KW_ONLY

    provider_name: str | None = None
    """The name of the provider that generated the response.

    This is required to be set when `provider_details` is set and the initial TextPart does not have a `provider_name` or it has changed.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_delta_kind: Literal['text'] = 'text'
    """Part delta type identifier, used as a discriminator."""

    def apply(self, part: ModelResponsePart) -> TextPart:
        """Apply this text delta to an existing `TextPart`.

        Args:
            part: The existing model response part, which must be a `TextPart`.

        Returns:
            A new `TextPart` with updated text content.

        Raises:
            ValueError: If `part` is not a `TextPart`.
        """
        if not isinstance(part, TextPart):
            raise ValueError('Cannot apply TextPartDeltas to non-TextParts')  # pragma: no cover
        return replace(
            part,
            content=part.content + self.content_delta,
            provider_name=self.provider_name or part.provider_name,
            provider_details={**(part.provider_details or {}), **(self.provider_details or {})} or None,
        )

    __repr__ = _utils.dataclasses_no_defaults_repr

content_delta instance-attribute

content_delta: str

The incremental text content to add to the existing TextPart content.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

This is required to be set when provider_details is set and the initial TextPart does not have a provider_name or it has changed.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

When this field is set, provider_name is required to identify the provider that generated this data.

part_delta_kind class-attribute instance-attribute

part_delta_kind: Literal['text'] = 'text'

Part delta type identifier, used as a discriminator.

apply

apply(part: ModelResponsePart) -> TextPart

Apply this text delta to an existing TextPart.

Parameters:

Name Type Description Default
part ModelResponsePart

The existing model response part, which must be a TextPart.

required

Returns:

Type Description
TextPart

A new TextPart with updated text content.

Raises:

Type Description
ValueError

If part is not a TextPart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
def apply(self, part: ModelResponsePart) -> TextPart:
    """Apply this text delta to an existing `TextPart`.

    Args:
        part: The existing model response part, which must be a `TextPart`.

    Returns:
        A new `TextPart` with updated text content.

    Raises:
        ValueError: If `part` is not a `TextPart`.
    """
    if not isinstance(part, TextPart):
        raise ValueError('Cannot apply TextPartDeltas to non-TextParts')  # pragma: no cover
    return replace(
        part,
        content=part.content + self.content_delta,
        provider_name=self.provider_name or part.provider_name,
        provider_details={**(part.provider_details or {}), **(self.provider_details or {})} or None,
    )

ThinkingPartDelta dataclass

A partial update (delta) for a ThinkingPart to append new thinking content.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
@dataclass(repr=False, kw_only=True)
class ThinkingPartDelta:
    """A partial update (delta) for a `ThinkingPart` to append new thinking content."""

    content_delta: str | None = None
    """The incremental thinking content to add to the existing `ThinkingPart` content."""

    signature_delta: str | None = None
    """Optional signature delta.

    Note this is never treated as a delta — it can replace None.
    """

    provider_name: str | None = None
    """Optional provider name for the thinking part.

    Signatures are only sent back to the same provider.
    Required to be set when `provider_details` is set and the initial ThinkingPart does not have a `provider_name` or it has changed.
    """

    provider_details: ProviderDetailsDelta = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    Can be a dict to merge with existing details, or a callable that takes
    the existing details and returns updated details.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

    When this field is set, `provider_name` is required to identify the provider that generated this data."""

    part_delta_kind: Literal['thinking'] = 'thinking'
    """Part delta type identifier, used as a discriminator."""

    @overload
    def apply(self, part: ModelResponsePart) -> ThinkingPart: ...

    @overload
    def apply(self, part: ModelResponsePart | ThinkingPartDelta) -> ThinkingPart | ThinkingPartDelta: ...

    def apply(self, part: ModelResponsePart | ThinkingPartDelta) -> ThinkingPart | ThinkingPartDelta:
        """Apply this thinking delta to an existing `ThinkingPart`.

        Args:
            part: The existing model response part, which must be a `ThinkingPart`.

        Returns:
            A new `ThinkingPart` with updated thinking content.

        Raises:
            ValueError: If `part` is not a `ThinkingPart`.
        """
        if isinstance(part, ThinkingPart):
            new_content = part.content + self.content_delta if self.content_delta else part.content
            new_signature = self.signature_delta if self.signature_delta is not None else part.signature
            new_provider_name = self.provider_name if self.provider_name is not None else part.provider_name
            # Resolve callable provider_details if needed
            resolved_details = (
                self.provider_details(part.provider_details)
                if callable(self.provider_details)
                else self.provider_details
            )
            new_provider_details = {**(part.provider_details or {}), **(resolved_details or {})} or None
            return replace(
                part,
                content=new_content,
                signature=new_signature,
                provider_name=new_provider_name,
                provider_details=new_provider_details,
            )
        elif isinstance(part, ThinkingPartDelta):
            if self.content_delta is None and self.signature_delta is None:
                raise ValueError('Cannot apply ThinkingPartDelta with no content or signature')
            if self.content_delta is not None:
                part = replace(part, content_delta=(part.content_delta or '') + self.content_delta)
            if self.signature_delta is not None:
                part = replace(part, signature_delta=self.signature_delta)
            if self.provider_name is not None:
                part = replace(part, provider_name=self.provider_name)
            if self.provider_details is not None:
                if callable(self.provider_details):
                    if callable(part.provider_details):
                        existing_fn = part.provider_details
                        new_fn = self.provider_details

                        def chained_both(d: dict[str, Any] | None) -> dict[str, Any]:
                            return new_fn(existing_fn(d))

                        part = replace(part, provider_details=chained_both)
                    else:
                        part = replace(part, provider_details=self.provider_details)  # pragma: no cover
                elif callable(part.provider_details):
                    existing_fn = part.provider_details
                    new_dict = self.provider_details

                    def chained_dict(d: dict[str, Any] | None) -> dict[str, Any]:
                        return {**existing_fn(d), **new_dict}

                    part = replace(part, provider_details=chained_dict)
                else:
                    existing = part.provider_details if isinstance(part.provider_details, dict) else {}
                    part = replace(part, provider_details={**existing, **self.provider_details})
            return part
        raise ValueError(  # pragma: no cover
            f'Cannot apply ThinkingPartDeltas to non-ThinkingParts or non-ThinkingPartDeltas ({part=}, {self=})'
        )

    __repr__ = _utils.dataclasses_no_defaults_repr

content_delta class-attribute instance-attribute

content_delta: str | None = None

The incremental thinking content to add to the existing ThinkingPart content.

signature_delta class-attribute instance-attribute

signature_delta: str | None = None

Optional signature delta.

Note this is never treated as a delta — it can replace None.

provider_name class-attribute instance-attribute

provider_name: str | None = None

Optional provider name for the thinking part.

Signatures are only sent back to the same provider. Required to be set when provider_details is set and the initial ThinkingPart does not have a provider_name or it has changed.

provider_details class-attribute instance-attribute

provider_details: ProviderDetailsDelta = None

Additional data returned by the provider that can't be mapped to standard fields.

Can be a dict to merge with existing details, or a callable that takes the existing details and returns updated details.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

When this field is set, provider_name is required to identify the provider that generated this data.

part_delta_kind class-attribute instance-attribute

part_delta_kind: Literal['thinking'] = 'thinking'

Part delta type identifier, used as a discriminator.

apply

Apply this thinking delta to an existing ThinkingPart.

Parameters:

Name Type Description Default
part ModelResponsePart | ThinkingPartDelta

The existing model response part, which must be a ThinkingPart.

required

Returns:

Type Description
ThinkingPart | ThinkingPartDelta

A new ThinkingPart with updated thinking content.

Raises:

Type Description
ValueError

If part is not a ThinkingPart.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
def apply(self, part: ModelResponsePart | ThinkingPartDelta) -> ThinkingPart | ThinkingPartDelta:
    """Apply this thinking delta to an existing `ThinkingPart`.

    Args:
        part: The existing model response part, which must be a `ThinkingPart`.

    Returns:
        A new `ThinkingPart` with updated thinking content.

    Raises:
        ValueError: If `part` is not a `ThinkingPart`.
    """
    if isinstance(part, ThinkingPart):
        new_content = part.content + self.content_delta if self.content_delta else part.content
        new_signature = self.signature_delta if self.signature_delta is not None else part.signature
        new_provider_name = self.provider_name if self.provider_name is not None else part.provider_name
        # Resolve callable provider_details if needed
        resolved_details = (
            self.provider_details(part.provider_details)
            if callable(self.provider_details)
            else self.provider_details
        )
        new_provider_details = {**(part.provider_details or {}), **(resolved_details or {})} or None
        return replace(
            part,
            content=new_content,
            signature=new_signature,
            provider_name=new_provider_name,
            provider_details=new_provider_details,
        )
    elif isinstance(part, ThinkingPartDelta):
        if self.content_delta is None and self.signature_delta is None:
            raise ValueError('Cannot apply ThinkingPartDelta with no content or signature')
        if self.content_delta is not None:
            part = replace(part, content_delta=(part.content_delta or '') + self.content_delta)
        if self.signature_delta is not None:
            part = replace(part, signature_delta=self.signature_delta)
        if self.provider_name is not None:
            part = replace(part, provider_name=self.provider_name)
        if self.provider_details is not None:
            if callable(self.provider_details):
                if callable(part.provider_details):
                    existing_fn = part.provider_details
                    new_fn = self.provider_details

                    def chained_both(d: dict[str, Any] | None) -> dict[str, Any]:
                        return new_fn(existing_fn(d))

                    part = replace(part, provider_details=chained_both)
                else:
                    part = replace(part, provider_details=self.provider_details)  # pragma: no cover
            elif callable(part.provider_details):
                existing_fn = part.provider_details
                new_dict = self.provider_details

                def chained_dict(d: dict[str, Any] | None) -> dict[str, Any]:
                    return {**existing_fn(d), **new_dict}

                part = replace(part, provider_details=chained_dict)
            else:
                existing = part.provider_details if isinstance(part.provider_details, dict) else {}
                part = replace(part, provider_details={**existing, **self.provider_details})
        return part
    raise ValueError(  # pragma: no cover
        f'Cannot apply ThinkingPartDeltas to non-ThinkingParts or non-ThinkingPartDeltas ({part=}, {self=})'
    )

ToolCallPartDelta dataclass

A partial update (delta) for a ToolCallPart to modify tool name, arguments, or tool call ID.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
@dataclass(repr=False, kw_only=True)
class ToolCallPartDelta:
    """A partial update (delta) for a `ToolCallPart` to modify tool name, arguments, or tool call ID."""

    tool_name_delta: str | None = None
    """Incremental text to add to the existing tool name, if any."""

    args_delta: str | dict[str, Any] | None = None
    """Incremental data to add to the tool arguments.

    If this is a string, it will be appended to existing JSON arguments.
    If this is a dict, it will be merged with existing dict arguments.
    """

    tool_call_id: str | None = None
    """Optional tool call identifier, this is used by some models including OpenAI.

    Note this is never treated as a delta — it can replace None, but otherwise if a
    non-matching value is provided an error will be raised."""

    provider_name: str | None = None
    """The name of the provider that generated the response.

    This is required to be set when `provider_details` is set and the initial ToolCallPart does not have a `provider_name` or it has changed.
    """

    provider_details: dict[str, Any] | None = None
    """Additional data returned by the provider that can't be mapped to standard fields.

    This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

    When this field is set, `provider_name` is required to identify the provider that generated this data.
    """

    part_delta_kind: Literal['tool_call'] = 'tool_call'
    """Part delta type identifier, used as a discriminator. Note that this is different from `ToolCallPart.part_kind`."""

    def as_part(self) -> ToolCallPart | None:
        """Convert this delta to a fully formed `ToolCallPart` if possible, otherwise return `None`.

        Returns:
            A `ToolCallPart` if `tool_name_delta` is set, otherwise `None`.
        """
        if self.tool_name_delta is None:
            return None

        return ToolCallPart(
            self.tool_name_delta,
            self.args_delta,
            self.tool_call_id or _generate_tool_call_id(),
            provider_name=self.provider_name,
            provider_details=self.provider_details,
        )

    @overload
    def apply(self, part: ModelResponsePart) -> ToolCallPart | NativeToolCallPart: ...

    @overload
    def apply(
        self, part: ModelResponsePart | ToolCallPartDelta
    ) -> ToolCallPart | NativeToolCallPart | ToolCallPartDelta: ...

    def apply(
        self, part: ModelResponsePart | ToolCallPartDelta
    ) -> ToolCallPart | NativeToolCallPart | ToolCallPartDelta:
        """Apply this delta to a part or delta, returning a new part or delta with the changes applied.

        Args:
            part: The existing model response part or delta to update.

        Returns:
            Either a new `ToolCallPart` or `NativeToolCallPart`, or an updated `ToolCallPartDelta`.

        Raises:
            ValueError: If `part` is neither a `ToolCallPart`, `NativeToolCallPart`, nor a `ToolCallPartDelta`.
            UnexpectedModelBehavior: If applying JSON deltas to dict arguments or vice versa.
        """
        if isinstance(part, ToolCallPart | NativeToolCallPart):
            return self._apply_to_part(part)

        if isinstance(part, ToolCallPartDelta):
            return self._apply_to_delta(part)

        raise ValueError(  # pragma: no cover
            f'Can only apply ToolCallPartDeltas to ToolCallParts, NativeToolCallParts, or ToolCallPartDeltas, not {part}'
        )

    def _apply_to_delta(self, delta: ToolCallPartDelta) -> ToolCallPart | NativeToolCallPart | ToolCallPartDelta:
        """Internal helper to apply this delta to another delta."""
        if self.tool_name_delta:
            # Append incremental text to the existing tool_name_delta
            updated_tool_name_delta = (delta.tool_name_delta or '') + self.tool_name_delta
            delta = replace(delta, tool_name_delta=updated_tool_name_delta)

        if isinstance(self.args_delta, str):
            if isinstance(delta.args_delta, dict):
                raise UnexpectedModelBehavior(
                    f'Cannot apply JSON deltas to non-JSON tool arguments ({delta=}, {self=})'
                )
            updated_args_delta = (delta.args_delta or '') + self.args_delta
            delta = replace(delta, args_delta=updated_args_delta)
        elif isinstance(self.args_delta, dict):
            if isinstance(delta.args_delta, str):
                raise UnexpectedModelBehavior(
                    f'Cannot apply dict deltas to non-dict tool arguments ({delta=}, {self=})'
                )
            updated_args_delta = {**(delta.args_delta or {}), **self.args_delta}
            delta = replace(delta, args_delta=updated_args_delta)

        if self.tool_call_id:
            delta = replace(delta, tool_call_id=self.tool_call_id)

        if self.provider_name:
            delta = replace(delta, provider_name=self.provider_name)

        if self.provider_details:
            merged_provider_details = {**(delta.provider_details or {}), **self.provider_details}
            delta = replace(delta, provider_details=merged_provider_details)

        # If we now have enough data to create a full ToolCallPart, do so
        if delta.tool_name_delta is not None:
            return ToolCallPart(
                delta.tool_name_delta,
                delta.args_delta,
                delta.tool_call_id or _generate_tool_call_id(),
                provider_name=delta.provider_name,
                provider_details=delta.provider_details,
            )

        return delta

    def _apply_to_part(self, part: ToolCallPart | NativeToolCallPart) -> ToolCallPart | NativeToolCallPart:
        """Internal helper to apply this delta directly to a `ToolCallPart` or `NativeToolCallPart`."""
        if self.tool_name_delta:
            # Append incremental text to the existing tool_name
            tool_name = part.tool_name + self.tool_name_delta
            part = replace(part, tool_name=tool_name)

        if isinstance(self.args_delta, str):
            if isinstance(part.args, dict):
                raise UnexpectedModelBehavior(f'Cannot apply JSON deltas to non-JSON tool arguments ({part=}, {self=})')
            updated_json = (part.args or '') + self.args_delta
            part = replace(part, args=updated_json)
        elif isinstance(self.args_delta, dict):
            if isinstance(part.args, str):
                raise UnexpectedModelBehavior(f'Cannot apply dict deltas to non-dict tool arguments ({part=}, {self=})')
            updated_dict = {**(part.args or {}), **self.args_delta}
            part = replace(part, args=updated_dict)

        if self.tool_call_id:
            part = replace(part, tool_call_id=self.tool_call_id)

        if self.provider_name:
            part = replace(part, provider_name=self.provider_name)

        if self.provider_details:
            merged_provider_details = {**(part.provider_details or {}), **self.provider_details}
            part = replace(part, provider_details=merged_provider_details)

        return part

    __repr__ = _utils.dataclasses_no_defaults_repr

tool_name_delta class-attribute instance-attribute

tool_name_delta: str | None = None

Incremental text to add to the existing tool name, if any.

args_delta class-attribute instance-attribute

args_delta: str | dict[str, Any] | None = None

Incremental data to add to the tool arguments.

If this is a string, it will be appended to existing JSON arguments. If this is a dict, it will be merged with existing dict arguments.

tool_call_id class-attribute instance-attribute

tool_call_id: str | None = None

Optional tool call identifier, this is used by some models including OpenAI.

Note this is never treated as a delta — it can replace None, but otherwise if a non-matching value is provided an error will be raised.

provider_name class-attribute instance-attribute

provider_name: str | None = None

The name of the provider that generated the response.

This is required to be set when provider_details is set and the initial ToolCallPart does not have a provider_name or it has changed.

provider_details class-attribute instance-attribute

provider_details: dict[str, Any] | None = None

Additional data returned by the provider that can't be mapped to standard fields.

This is used for data that is required to be sent back to APIs, as well as data users may want to access programmatically.

When this field is set, provider_name is required to identify the provider that generated this data.

part_delta_kind class-attribute instance-attribute

part_delta_kind: Literal['tool_call'] = 'tool_call'

Part delta type identifier, used as a discriminator. Note that this is different from ToolCallPart.part_kind.

as_part

as_part() -> ToolCallPart | None

Convert this delta to a fully formed ToolCallPart if possible, otherwise return None.

Returns:

Type Description
ToolCallPart | None

A ToolCallPart if tool_name_delta is set, otherwise None.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
def as_part(self) -> ToolCallPart | None:
    """Convert this delta to a fully formed `ToolCallPart` if possible, otherwise return `None`.

    Returns:
        A `ToolCallPart` if `tool_name_delta` is set, otherwise `None`.
    """
    if self.tool_name_delta is None:
        return None

    return ToolCallPart(
        self.tool_name_delta,
        self.args_delta,
        self.tool_call_id or _generate_tool_call_id(),
        provider_name=self.provider_name,
        provider_details=self.provider_details,
    )

apply

Apply this delta to a part or delta, returning a new part or delta with the changes applied.

Parameters:

Name Type Description Default
part ModelResponsePart | ToolCallPartDelta

The existing model response part or delta to update.

required

Returns:

Type Description
ToolCallPart | NativeToolCallPart | ToolCallPartDelta

Either a new ToolCallPart or NativeToolCallPart, or an updated ToolCallPartDelta.

Raises:

Type Description
ValueError

If part is neither a ToolCallPart, NativeToolCallPart, nor a ToolCallPartDelta.

UnexpectedModelBehavior

If applying JSON deltas to dict arguments or vice versa.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
def apply(
    self, part: ModelResponsePart | ToolCallPartDelta
) -> ToolCallPart | NativeToolCallPart | ToolCallPartDelta:
    """Apply this delta to a part or delta, returning a new part or delta with the changes applied.

    Args:
        part: The existing model response part or delta to update.

    Returns:
        Either a new `ToolCallPart` or `NativeToolCallPart`, or an updated `ToolCallPartDelta`.

    Raises:
        ValueError: If `part` is neither a `ToolCallPart`, `NativeToolCallPart`, nor a `ToolCallPartDelta`.
        UnexpectedModelBehavior: If applying JSON deltas to dict arguments or vice versa.
    """
    if isinstance(part, ToolCallPart | NativeToolCallPart):
        return self._apply_to_part(part)

    if isinstance(part, ToolCallPartDelta):
        return self._apply_to_delta(part)

    raise ValueError(  # pragma: no cover
        f'Can only apply ToolCallPartDeltas to ToolCallParts, NativeToolCallParts, or ToolCallPartDeltas, not {part}'
    )

ModelResponsePartDelta module-attribute

ModelResponsePartDelta = Annotated[
    TextPartDelta | ThinkingPartDelta | ToolCallPartDelta,
    Discriminator("part_delta_kind"),
]

A partial update (delta) for any model response part.

PartStartEvent dataclass

An event indicating that a new part has started.

If multiple PartStartEvents are received with the same index, the new one should fully replace the old one.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
@dataclass(repr=False, kw_only=True)
class PartStartEvent:
    """An event indicating that a new part has started.

    If multiple `PartStartEvent`s are received with the same index,
    the new one should fully replace the old one.
    """

    index: int
    """The index of the part within the overall response parts list."""

    part: ModelResponsePart
    """The newly started `ModelResponsePart`."""

    previous_part_kind: (
        Literal['text', 'thinking', 'tool-call', 'builtin-tool-call', 'builtin-tool-return', 'compaction', 'file']
        | None
    ) = None
    """The kind of the previous part, if any.

    This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.
    """

    event_kind: Literal['part_start'] = 'part_start'
    """Event type identifier, used as a discriminator."""

    __repr__ = _utils.dataclasses_no_defaults_repr

index instance-attribute

index: int

The index of the part within the overall response parts list.

part instance-attribute

The newly started ModelResponsePart.

previous_part_kind class-attribute instance-attribute

previous_part_kind: (
    Literal[
        "text",
        "thinking",
        "tool-call",
        "builtin-tool-call",
        "builtin-tool-return",
        "compaction",
        "file",
    ]
    | None
) = None

The kind of the previous part, if any.

This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.

event_kind class-attribute instance-attribute

event_kind: Literal['part_start'] = 'part_start'

Event type identifier, used as a discriminator.

PartDeltaEvent dataclass

An event indicating a delta update for an existing part.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
@dataclass(repr=False, kw_only=True)
class PartDeltaEvent:
    """An event indicating a delta update for an existing part."""

    index: int
    """The index of the part within the overall response parts list."""

    delta: ModelResponsePartDelta
    """The delta to apply to the specified part."""

    event_kind: Literal['part_delta'] = 'part_delta'
    """Event type identifier, used as a discriminator."""

    __repr__ = _utils.dataclasses_no_defaults_repr

index instance-attribute

index: int

The index of the part within the overall response parts list.

delta instance-attribute

The delta to apply to the specified part.

event_kind class-attribute instance-attribute

event_kind: Literal['part_delta'] = 'part_delta'

Event type identifier, used as a discriminator.

PartEndEvent dataclass

An event indicating that a part is complete.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
@dataclass(repr=False, kw_only=True)
class PartEndEvent:
    """An event indicating that a part is complete."""

    index: int
    """The index of the part within the overall response parts list."""

    part: ModelResponsePart
    """The complete `ModelResponsePart`."""

    next_part_kind: (
        Literal['text', 'thinking', 'tool-call', 'builtin-tool-call', 'builtin-tool-return', 'compaction', 'file']
        | None
    ) = None
    """The kind of the next part, if any.

    This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.
    """

    event_kind: Literal['part_end'] = 'part_end'
    """Event type identifier, used as a discriminator."""

    __repr__ = _utils.dataclasses_no_defaults_repr

index instance-attribute

index: int

The index of the part within the overall response parts list.

part instance-attribute

The complete ModelResponsePart.

next_part_kind class-attribute instance-attribute

next_part_kind: (
    Literal[
        "text",
        "thinking",
        "tool-call",
        "builtin-tool-call",
        "builtin-tool-return",
        "compaction",
        "file",
    ]
    | None
) = None

The kind of the next part, if any.

This is useful for UI event streams to know whether to group parts of the same kind together when emitting events.

event_kind class-attribute instance-attribute

event_kind: Literal['part_end'] = 'part_end'

Event type identifier, used as a discriminator.

FinalResultEvent dataclass

An event indicating the response to the current model request matches the output schema and will produce a result.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
@dataclass(repr=False, kw_only=True)
class FinalResultEvent:
    """An event indicating the response to the current model request matches the output schema and will produce a result."""

    tool_name: str | None
    """The name of the output tool that was called. `None` if the result is from text content and not from a tool."""
    tool_call_id: str | None
    """The tool call ID, if any, that this result is associated with."""
    event_kind: Literal['final_result'] = 'final_result'
    """Event type identifier, used as a discriminator."""

    __repr__ = _utils.dataclasses_no_defaults_repr

tool_name instance-attribute

tool_name: str | None

The name of the output tool that was called. None if the result is from text content and not from a tool.

tool_call_id instance-attribute

tool_call_id: str | None

The tool call ID, if any, that this result is associated with.

event_kind class-attribute instance-attribute

event_kind: Literal['final_result'] = 'final_result'

Event type identifier, used as a discriminator.

ModelResponseStreamEvent module-attribute

ModelResponseStreamEvent = Annotated[
    PartStartEvent
    | PartDeltaEvent
    | PartEndEvent
    | FinalResultEvent,
    Discriminator("event_kind"),
]

An event in the model response stream, starting a new part, applying a delta to an existing one, indicating a part is complete, or indicating the final result.

ToolCallEvent dataclass

Base class for events emitted when a tool call is about to be invoked.

Match against this in a case to handle FunctionToolCallEvent and OutputToolCallEvent together.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
@dataclass(repr=False)
class ToolCallEvent:
    """Base class for events emitted when a tool call is about to be invoked.

    Match against this in a `case` to handle [`FunctionToolCallEvent`][pydantic_ai.messages.FunctionToolCallEvent]
    and [`OutputToolCallEvent`][pydantic_ai.messages.OutputToolCallEvent] together.
    """

    part: ToolCallPart
    """The tool call to make."""

    _: KW_ONLY

    args_valid: bool | None = None
    """Whether the tool arguments passed validation.
    See the [custom validation docs](https://ai.pydantic.dev/tools-advanced/#args-validator) for more info.

    - `True`: Schema validation and custom validation (if configured) both passed; args are guaranteed valid.
    - `False`: Validation was performed and failed.
    - `None`: Validation was not performed.
    """

    @property
    def tool_call_id(self) -> str:
        """An ID used for matching details about the call to its result."""
        return self.part.tool_call_id

    __repr__ = _utils.dataclasses_no_defaults_repr

part instance-attribute

The tool call to make.

args_valid class-attribute instance-attribute

args_valid: bool | None = None

Whether the tool arguments passed validation. See the custom validation docs for more info.

  • True: Schema validation and custom validation (if configured) both passed; args are guaranteed valid.
  • False: Validation was performed and failed.
  • None: Validation was not performed.

tool_call_id property

tool_call_id: str

An ID used for matching details about the call to its result.

FunctionToolCallEvent dataclass

Bases: ToolCallEvent

An event indicating the start to a call to a function tool.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2694
2695
2696
2697
2698
2699
@dataclass(repr=False)
class FunctionToolCallEvent(ToolCallEvent):
    """An event indicating the start to a call to a function tool."""

    event_kind: Literal['function_tool_call'] = 'function_tool_call'
    """Event type identifier, used as a discriminator."""

event_kind class-attribute instance-attribute

event_kind: Literal["function_tool_call"] = (
    "function_tool_call"
)

Event type identifier, used as a discriminator.

OutputToolCallEvent dataclass

Bases: ToolCallEvent

An event indicating the start of a call to an output tool (the model's "submit final answer" call).

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2702
2703
2704
2705
2706
2707
@dataclass(repr=False)
class OutputToolCallEvent(ToolCallEvent):
    """An event indicating the start of a call to an output tool (the model's "submit final answer" call)."""

    event_kind: Literal['output_tool_call'] = 'output_tool_call'
    """Event type identifier, used as a discriminator."""

event_kind class-attribute instance-attribute

event_kind: Literal["output_tool_call"] = "output_tool_call"

Event type identifier, used as a discriminator.

ToolResultEvent dataclass

Base class for events emitted when a tool call has been completed.

Match against this in a case to handle FunctionToolResultEvent and OutputToolResultEvent together.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
@dataclass(repr=False)
class ToolResultEvent:
    """Base class for events emitted when a tool call has been completed.

    Match against this in a `case` to handle [`FunctionToolResultEvent`][pydantic_ai.messages.FunctionToolResultEvent]
    and [`OutputToolResultEvent`][pydantic_ai.messages.OutputToolResultEvent] together.
    """

    part: ToolReturnPart | RetryPromptPart
    """The tool result part that will be sent back to the model."""

    @property
    def tool_call_id(self) -> str:
        """An ID used to match the result to its original call."""
        return self.part.tool_call_id

    __repr__ = _utils.dataclasses_no_defaults_repr

part instance-attribute

The tool result part that will be sent back to the model.

tool_call_id property

tool_call_id: str

An ID used to match the result to its original call.

FunctionToolResultEvent dataclass

Bases: ToolResultEvent

An event indicating the result of a function tool call.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
@dataclass(repr=False)
class FunctionToolResultEvent(ToolResultEvent):
    """An event indicating the result of a function tool call."""

    _: KW_ONLY

    content: str | Sequence[UserContent] | None = None
    """The content that will be sent to the model as a UserPromptPart following the result."""

    event_kind: Literal['function_tool_result'] = 'function_tool_result'
    """Event type identifier, used as a discriminator."""

content class-attribute instance-attribute

content: str | Sequence[UserContent] | None = None

The content that will be sent to the model as a UserPromptPart following the result.

event_kind class-attribute instance-attribute

event_kind: Literal["function_tool_result"] = (
    "function_tool_result"
)

Event type identifier, used as a discriminator.

OutputToolResultEvent dataclass

Bases: ToolResultEvent

An event indicating the result of an output tool call.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2742
2743
2744
2745
2746
2747
@dataclass(repr=False)
class OutputToolResultEvent(ToolResultEvent):
    """An event indicating the result of an output tool call."""

    event_kind: Literal['output_tool_result'] = 'output_tool_result'
    """Event type identifier, used as a discriminator."""

event_kind class-attribute instance-attribute

event_kind: Literal["output_tool_result"] = (
    "output_tool_result"
)

Event type identifier, used as a discriminator.

HandleResponseEvent module-attribute

An event yielded when handling a model response, indicating tool calls and results.

AgentStreamEvent module-attribute

AgentStreamEvent = Annotated[
    ModelResponseStreamEvent | HandleResponseEvent,
    Discriminator("event_kind"),
]

An event in the agent stream: model response stream events and response-handling events.