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.

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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@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_event(self, settings: InstrumentationSettings) -> LogRecord:
        return LogRecord(
            attributes={'event.name': 'gen_ai.system.message'},
            body={'role': 'system', **({'content': self.content} if settings.include_content else {})},
        )

    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
176
177
178
179
180
181
182
183
184
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
@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
263
264
265
266
267
268
269
270
271
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
@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
322
323
324
325
326
327
328
329
330
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
@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
369
370
371
372
373
374
375
376
377
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
@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
415
416
417
418
419
420
421
422
423
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
@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.

BinaryContent

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
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
@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
516
517
518
519
520
521
522
523
524
525
526
527
@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
529
530
531
532
533
534
535
536
@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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
@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
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
@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
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
@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 (automatically omitted for Bedrock, as it does not support explicit TTL). See https://docs.claude.com/en/docs/build-with-claude/prompt-caching#1-hour-cache-duration 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 (automatically omitted for Bedrock, as it does not support explicit TTL). See https://docs.claude.com/en/docs/build-with-claude/prompt-caching#1-hour-cache-duration for more information.

UploadedFileProviderName module-attribute

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

Provider names supported by UploadedFile.

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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
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
@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] (GLA: [Files API](https://ai.google.dev/gemini-api/docs/files) URIs, Vertex: 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 (Vertex), this must be a GCS URI (`gs://bucket/path`).
    For GoogleModel (GLA), 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 (Vertex), this must be a GCS URI (gs://bucket/path). For GoogleModel (GLA), 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
815
816
817
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

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
@dataclass(repr=False)
class ToolReturn:
    """A structured tool return that separates the tool result from additional content sent to the model."""

    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
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
@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_event(self, settings: InstrumentationSettings) -> LogRecord:
        content: Any = [{'kind': part.pop('type'), **part} for part in self.otel_message_parts(settings)]
        for part in content:
            if part['kind'] == 'binary' and 'content' in part:
                part['binary_content'] = part.pop('content')
        content = [
            part['content'] if part == {'kind': 'text', 'content': part.get('content')} else part for part in content
        ]
        if content in ([{'kind': 'text'}], [self.content]):
            content = content[0]
        return LogRecord(attributes={'event.name': 'gen_ai.user.message'}, body={'content': content, 'role': 'user'})

    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):
                parts.append(
                    _otel_messages.TextPart(type='text', **({'content': part} 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().

BaseToolReturnPart dataclass

Base class for tool return parts.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
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
@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

    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_event(self, settings: InstrumentationSettings) -> LogRecord:
        body: AnyValue = {
            'role': 'tool',
            'id': self.tool_call_id,
            'name': self.tool_name,
        }
        if settings.include_content:
            body['content'] = self.content  # pyright: ignore[reportArgumentType]

        return LogRecord(
            body=body,
            attributes={'event.name': 'gen_ai.tool.message'},
        )

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        from .models.instrumented import InstrumentedModel

        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'] = InstrumentedModel.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.

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
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
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
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
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
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
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
1224
1225
1226
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
1231
1232
1233
1234
1235
1236
1237
1238
@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."""

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.

BuiltinToolReturnPart dataclass

Bases: BaseToolReturnPart

A tool return message from a built-in tool.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
@dataclass(repr=False)
class BuiltinToolReturnPart(BaseToolReturnPart):
    """A tool return message from a built-in tool."""

    _: 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."""

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.

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
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
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
1317
1318
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
@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:
            json_errors = error_details_ta.dump_json(self.content, exclude={'__all__': {'ctx'}}, 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_event(self, settings: InstrumentationSettings) -> LogRecord:
        if self.tool_name is None:
            return LogRecord(
                attributes={'event.name': 'gen_ai.user.message'},
                body={'content': self.model_response(), 'role': 'user'},
            )
        else:
            return LogRecord(
                attributes={'event.name': 'gen_ai.tool.message'},
                body={
                    **({'content': self.model_response()} if settings.include_content else {}),
                    'role': 'tool',
                    'id': self.tool_call_id,
                    'name': self.tool_name,
                },
            )

    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
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
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:
        json_errors = error_details_ta.dump_json(self.content, exclude={'__all__': {'ctx'}}, 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.'

ModelRequestPart module-attribute

A message part sent by Pydantic AI to a model.

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
1362
1363
1364
1365
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
@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 for the model."""

    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."""

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

    @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 for the model.

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.

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.

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
1388
1389
1390
1391
@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
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
@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
1427
1428
1429
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
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
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
@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
1479
1480
1481
def has_content(self) -> bool:
    """Return `True` if the thinking 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
1486
1487
1488
1489
1490
1491
1492
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
@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
1517
1518
1519
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
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
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
1578
1579
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
@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

    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.

    Builtin 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 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.

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.

Builtin 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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
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
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
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
1603
1604
1605
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
1610
1611
1612
1613
1614
1615
1616
1617
@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`."""

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.

BuiltinToolCallPart dataclass

Bases: BaseToolCallPart

A tool call to a built-in tool.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1620
1621
1622
1623
1624
1625
1626
1627
@dataclass(repr=False)
class BuiltinToolCallPart(BaseToolCallPart):
    """A tool call to a built-in tool."""

    _: KW_ONLY

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

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.

ModelResponsePart module-attribute

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
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
1681
1682
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
1719
1720
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
1819
1820
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
1846
1847
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
@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."""

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

    @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 builtin_tool_calls(self) -> list[tuple[BuiltinToolCallPart, BuiltinToolReturnPart]]:
        """Get the builtin tool calls and results in the response."""
        calls = [part for part in self.parts if isinstance(part, BuiltinToolCallPart)]
        if not calls:
            return []
        returns_by_id = {part.tool_call_id: part for part in self.parts if isinstance(part, BuiltinToolReturnPart)}
        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
        ]

    @deprecated('`price` is deprecated, use `cost` instead')
    def price(self) -> genai_types.PriceCalculation:  # pragma: no cover
        return self.cost()

    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_events(self, settings: InstrumentationSettings) -> list[LogRecord]:
        """Return OpenTelemetry events for the response."""
        result: list[LogRecord] = []

        def new_event_body():
            new_body: dict[str, Any] = {'role': 'assistant'}
            ev = LogRecord(attributes={'event.name': 'gen_ai.assistant.message'}, body=new_body)
            result.append(ev)
            return new_body

        body = new_event_body()
        for part in self.parts:
            if isinstance(part, ToolCallPart):
                body.setdefault('tool_calls', []).append(
                    {
                        'id': part.tool_call_id,
                        'type': 'function',
                        'function': {
                            'name': part.tool_name,
                            **({'arguments': part.args} if settings.include_content else {}),
                        },
                    }
                )
            elif isinstance(part, TextPart | ThinkingPart):
                kind = part.part_kind
                body.setdefault('content', []).append(
                    {'kind': kind, **({'text': part.content} if settings.include_content else {})}
                )
            elif isinstance(part, FilePart):
                body.setdefault('content', []).append(
                    {
                        'kind': 'binary',
                        'media_type': part.content.media_type,
                        **(
                            {'binary_content': part.content.base64}
                            if settings.include_content and settings.include_binary_content
                            else {}
                        ),
                    }
                )

        if content := body.get('content'):
            text_content = content[0].get('text')
            if content == [{'kind': 'text', 'text': text_content}]:
                body['content'] = text_content

        return result

    def otel_message_parts(self, settings: InstrumentationSettings) -> list[_otel_messages.MessagePart]:
        from .models.instrumented import InstrumentedModel

        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, BuiltinToolCallPart):
                    call_part['builtin'] = True
                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: InstrumentedModel.serialize_any(v) for k, v in part.args.items()}

                parts.append(call_part)
            elif isinstance(part, BuiltinToolReturnPart):
                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'] = InstrumentedModel.serialize_any(part.content)

                parts.append(return_part)
        return parts

    @property
    @deprecated('`vendor_details` is deprecated, use `provider_details` instead')
    def vendor_details(self) -> dict[str, Any] | None:
        return self.provider_details

    @property
    @deprecated('`vendor_id` is deprecated, use `provider_response_id` instead')
    def vendor_id(self) -> str | None:
        return self.provider_response_id

    @property
    @deprecated('`provider_request_id` is deprecated, use `provider_response_id` instead')
    def provider_request_id(self) -> str | None:
        return self.provider_response_id

    __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.

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.

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.

builtin_tool_calls property

Get the builtin tool calls and results in the response.

price deprecated

price() -> PriceCalculation
Deprecated

price is deprecated, use cost instead

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1749
1750
1751
@deprecated('`price` is deprecated, use `cost` instead')
def price(self) -> genai_types.PriceCalculation:  # pragma: no cover
    return self.cost()

cost

cost() -> PriceCalculation

Calculate the cost of the usage.

Uses genai-prices.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
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,
    )

otel_events

otel_events(
    settings: InstrumentationSettings,
) -> list[LogRecord]

Return OpenTelemetry events for the response.

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
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
def otel_events(self, settings: InstrumentationSettings) -> list[LogRecord]:
    """Return OpenTelemetry events for the response."""
    result: list[LogRecord] = []

    def new_event_body():
        new_body: dict[str, Any] = {'role': 'assistant'}
        ev = LogRecord(attributes={'event.name': 'gen_ai.assistant.message'}, body=new_body)
        result.append(ev)
        return new_body

    body = new_event_body()
    for part in self.parts:
        if isinstance(part, ToolCallPart):
            body.setdefault('tool_calls', []).append(
                {
                    'id': part.tool_call_id,
                    'type': 'function',
                    'function': {
                        'name': part.tool_name,
                        **({'arguments': part.args} if settings.include_content else {}),
                    },
                }
            )
        elif isinstance(part, TextPart | ThinkingPart):
            kind = part.part_kind
            body.setdefault('content', []).append(
                {'kind': kind, **({'text': part.content} if settings.include_content else {})}
            )
        elif isinstance(part, FilePart):
            body.setdefault('content', []).append(
                {
                    'kind': 'binary',
                    'media_type': part.content.media_type,
                    **(
                        {'binary_content': part.content.base64}
                        if settings.include_content and settings.include_binary_content
                        else {}
                    ),
                }
            )

    if content := body.get('content'):
        text_content = content[0].get('text')
        if content == [{'kind': 'text', 'text': text_content}]:
            body['content'] = text_content

    return result

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
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
@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
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
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
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
@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
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
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
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
@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 | BuiltinToolCallPart: ...

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

    def apply(
        self, part: ModelResponsePart | ToolCallPartDelta
    ) -> ToolCallPart | BuiltinToolCallPart | 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 `BuiltinToolCallPart`, or an updated `ToolCallPartDelta`.

        Raises:
            ValueError: If `part` is neither a `ToolCallPart`, `BuiltinToolCallPart`, nor a `ToolCallPartDelta`.
            UnexpectedModelBehavior: If applying JSON deltas to dict arguments or vice versa.
        """
        if isinstance(part, ToolCallPart | BuiltinToolCallPart):
            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, BuiltinToolCallParts, or ToolCallPartDeltas, not {part}'
        )

    def _apply_to_delta(self, delta: ToolCallPartDelta) -> ToolCallPart | BuiltinToolCallPart | 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 | BuiltinToolCallPart) -> ToolCallPart | BuiltinToolCallPart:
        """Internal helper to apply this delta directly to a `ToolCallPart` or `BuiltinToolCallPart`."""
        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
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
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 | BuiltinToolCallPart | ToolCallPartDelta

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

Raises:

Type Description
ValueError

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

UnexpectedModelBehavior

If applying JSON deltas to dict arguments or vice versa.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
def apply(
    self, part: ModelResponsePart | ToolCallPartDelta
) -> ToolCallPart | BuiltinToolCallPart | 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 `BuiltinToolCallPart`, or an updated `ToolCallPartDelta`.

    Raises:
        ValueError: If `part` is neither a `ToolCallPart`, `BuiltinToolCallPart`, nor a `ToolCallPartDelta`.
        UnexpectedModelBehavior: If applying JSON deltas to dict arguments or vice versa.
    """
    if isinstance(part, ToolCallPart | BuiltinToolCallPart):
        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, BuiltinToolCallParts, 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
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
@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', '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",
        "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
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
@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
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
@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', '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",
        "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
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
@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.

FunctionToolCallEvent dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
@dataclass(repr=False)
class FunctionToolCallEvent:
    """An event indicating the start to a call to a function tool."""

    part: ToolCallPart
    """The (function) 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.
    """

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

    @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

    @property
    @deprecated('`call_id` is deprecated, use `tool_call_id` instead.')
    def call_id(self) -> str:
        """An ID used for matching details about the call to its result."""
        return self.part.tool_call_id  # pragma: no cover

    __repr__ = _utils.dataclasses_no_defaults_repr

part instance-attribute

The (function) 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.

event_kind class-attribute instance-attribute

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

Event type identifier, used as a discriminator.

tool_call_id property

tool_call_id: str

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

call_id property

call_id: str

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

FunctionToolResultEvent dataclass

An event indicating the result of a function tool call.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
@dataclass(repr=False)
class FunctionToolResultEvent:
    """An event indicating the result of a function tool call."""

    result: ToolReturnPart | RetryPromptPart
    """The result of the call to the function tool."""

    _: 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."""

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

    __repr__ = _utils.dataclasses_no_defaults_repr

result instance-attribute

The result of the call to the function tool.

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.

tool_call_id property

tool_call_id: str

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

BuiltinToolCallEvent dataclass deprecated

Deprecated

BuiltinToolCallEvent is deprecated, look for PartStartEvent and PartDeltaEvent with BuiltinToolCallPart instead.

An event indicating the start to a call to a built-in tool.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
@deprecated(
    '`BuiltinToolCallEvent` is deprecated, look for `PartStartEvent` and `PartDeltaEvent` with `BuiltinToolCallPart` instead.'
)
@dataclass(repr=False)
class BuiltinToolCallEvent:
    """An event indicating the start to a call to a built-in tool."""

    part: BuiltinToolCallPart
    """The built-in tool call to make."""

    _: KW_ONLY

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

part instance-attribute

The built-in tool call to make.

event_kind class-attribute instance-attribute

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

Event type identifier, used as a discriminator.

BuiltinToolResultEvent dataclass deprecated

Deprecated

BuiltinToolResultEvent is deprecated, look for PartStartEvent and PartDeltaEvent with BuiltinToolReturnPart instead.

An event indicating the result of a built-in tool call.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
@deprecated(
    '`BuiltinToolResultEvent` is deprecated, look for `PartStartEvent` and `PartDeltaEvent` with `BuiltinToolReturnPart` instead.'
)
@dataclass(repr=False)
class BuiltinToolResultEvent:
    """An event indicating the result of a built-in tool call."""

    result: BuiltinToolReturnPart
    """The result of the call to the built-in tool."""

    _: KW_ONLY

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

result instance-attribute

The result of the call to the built-in tool.

event_kind class-attribute instance-attribute

event_kind: Literal["builtin_tool_result"] = (
    "builtin_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.