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
    ModelRequestPart("ModelRequestPart<br>(Union)") --- ModelRequest
    ModelRequest("ModelRequest(parts=list[...])") --- ModelMessage
    ModelResponsePart("ModelResponsePart<br>(Union)") --- ModelResponse
    ModelResponse("ModelResponse(parts=list[...])") --- ModelMessage("ModelMessage<br>(Union)")

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@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."""

    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.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) -> Event:
        return Event(
            'gen_ai.system.message',
            body={'role': 'system', **({'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 dataclass

Bases: ABC

Abstract base class for any URL-based file.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
@dataclass(repr=False)
class FileUrl(ABC):
    """Abstract base class for any URL-based file."""

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

    force_download: bool = False
    """If the model supports it:

    * If True, the file is downloaded and the data is sent to the model as bytes.
    * If False, the URL is sent directly to the model and no download is performed.
    """

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

    @property
    @abstractmethod
    def media_type(self) -> str:
        """Return the media type of the file, based on the url."""

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

    __repr__ = _utils.dataclasses_no_defaults_repr

url instance-attribute

url: str

The URL of the file.

force_download class-attribute instance-attribute

force_download: bool = False

If the model supports it:

  • If True, the file is downloaded and the data is sent to the model as bytes.
  • If False, the URL is sent directly to the model and no download is performed.

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

media_type abstractmethod property

media_type: str

Return the media type of the file, based on the url.

format abstractmethod property

format: str

The file format.

VideoUrl dataclass

Bases: FileUrl

A URL to a video.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
122
123
124
125
126
127
128
129
130
131
132
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
167
168
169
170
@dataclass(repr=False)
class VideoUrl(FileUrl):
    """A URL to a video."""

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

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

    @property
    def media_type(self) -> VideoMediaType:
        """Return the media type of the video, based on the url."""
        if self.url.endswith('.mkv'):
            return 'video/x-matroska'
        elif self.url.endswith('.mov'):
            return 'video/quicktime'
        elif self.url.endswith('.mp4'):
            return 'video/mp4'
        elif self.url.endswith('.webm'):
            return 'video/webm'
        elif self.url.endswith('.flv'):
            return 'video/x-flv'
        elif self.url.endswith(('.mpeg', '.mpg')):
            return 'video/mpeg'
        elif self.url.endswith('.wmv'):
            return 'video/x-ms-wmv'
        elif self.url.endswith('.three_gp'):
            return 'video/3gpp'
        # 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.
        elif self.is_youtube:
            return 'video/mp4'
        else:
            raise ValueError(f'Unknown video file extension: {self.url}')

    @property
    def is_youtube(self) -> bool:
        """True if the URL has a YouTube domain."""
        return self.url.startswith(('https://youtu.be/', 'https://youtube.com/', 'https://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.

media_type property

media_type: VideoMediaType

Return the media type of the video, based on the url.

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 dataclass

Bases: FileUrl

A URL to an audio file.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
173
174
175
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
@dataclass(repr=False)
class AudioUrl(FileUrl):
    """A URL to an audio file."""

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

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

    @property
    def media_type(self) -> AudioMediaType:
        """Return the media type of the audio file, based on the url.

        References:
        - Gemini: https://ai.google.dev/gemini-api/docs/audio#supported-formats
        """
        if self.url.endswith('.mp3'):
            return 'audio/mpeg'
        if self.url.endswith('.wav'):
            return 'audio/wav'
        if self.url.endswith('.flac'):
            return 'audio/flac'
        if self.url.endswith('.oga'):
            return 'audio/ogg'
        if self.url.endswith('.aiff'):
            return 'audio/aiff'
        if self.url.endswith('.aac'):
            return 'audio/aac'

        raise ValueError(f'Unknown audio file extension: {self.url}')

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

media_type property

media_type: AudioMediaType

Return the media type of the audio file, based on the url.

References: - Gemini: https://ai.google.dev/gemini-api/docs/audio#supported-formats

format property

format: AudioFormat

The file format of the audio file.

ImageUrl dataclass

Bases: FileUrl

A URL to an image.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
@dataclass(repr=False)
class ImageUrl(FileUrl):
    """A URL to an image."""

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

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

    @property
    def media_type(self) -> ImageMediaType:
        """Return the media type of the image, based on the url."""
        if self.url.endswith(('.jpg', '.jpeg')):
            return 'image/jpeg'
        elif self.url.endswith('.png'):
            return 'image/png'
        elif self.url.endswith('.gif'):
            return 'image/gif'
        elif self.url.endswith('.webp'):
            return 'image/webp'
        else:
            raise ValueError(f'Unknown image file extension: {self.url}')

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

media_type property

media_type: ImageMediaType

Return the media type of the image, based on the url.

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 dataclass

Bases: FileUrl

The URL of the document.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
@dataclass(repr=False)
class DocumentUrl(FileUrl):
    """The URL of the document."""

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

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

    @property
    def media_type(self) -> str:
        """Return the media type of the document, based on the url."""
        type_, _ = guess_type(self.url)
        if type_ is None:
            raise ValueError(f'Unknown document file extension: {self.url}')
        return 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.

media_type property

media_type: str

Return the media type of the document, based on the url.

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 dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
@dataclass(repr=False)
class BinaryContent:
    """Binary content, e.g. an audio or image file."""

    data: bytes
    """The binary data."""

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

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

    @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 data.

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

kind class-attribute instance-attribute

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

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

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.

ToolReturn dataclass

A structured return value for tools that need to provide both a return value and custom content to the model.

This class allows tools to return complex responses that include: - A return value for actual tool return - Custom content (including multi-modal content) to be sent to the model as a UserPromptPart - Optional metadata for application use

Source code in pydantic_ai_slim/pydantic_ai/messages.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@dataclass(repr=False)
class ToolReturn:
    """A structured return value for tools that need to provide both a return value and custom content to the model.

    This class allows tools to return complex responses that include:
    - A return value for actual tool return
    - Custom content (including multi-modal content) to be sent to the model as a UserPromptPart
    - Optional metadata for application use
    """

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

    content: Sequence[UserContent] | None = None
    """The content sequence to be sent to the model as a UserPromptPart."""

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

    __repr__ = _utils.dataclasses_no_defaults_repr

return_value instance-attribute

return_value: Any

The return value to be used in the tool response.

content class-attribute instance-attribute

content: Sequence[UserContent] | None = None

The content sequence to be sent to the model as a UserPromptPart.

metadata class-attribute instance-attribute

metadata: Any = None

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

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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
@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.run],
    [`Agent.run_sync`][pydantic_ai.Agent.run_sync], and [`Agent.run_stream`][pydantic_ai.Agent.run_stream].
    """

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

    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) -> Event:
        content: str | list[dict[str, Any] | str]
        if isinstance(self.content, str):
            content = self.content
        else:
            content = []
            for part in self.content:
                if isinstance(part, str):
                    content.append(part if settings.include_content else {'kind': 'text'})
                elif isinstance(part, (ImageUrl, AudioUrl, DocumentUrl, VideoUrl)):
                    content.append({'kind': part.kind, **({'url': part.url} if settings.include_content else {})})
                elif isinstance(part, BinaryContent):
                    converted_part = {'kind': part.kind, 'media_type': part.media_type}
                    if settings.include_content and settings.include_binary_content:
                        converted_part['binary_content'] = base64.b64encode(part.data).decode()
                    content.append(converted_part)
                else:
                    content.append({'kind': part.kind})  # pragma: no cover
        return Event('gen_ai.user.message', body={'content': content, 'role': 'user'})

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

ToolReturnPart dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@dataclass(repr=False)
class ToolReturnPart:
    """A tool return message, this encodes the result of running a tool."""

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

    content: Any
    """The return value."""

    tool_call_id: str
    """The tool call identifier, this is used by some models including OpenAI."""

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

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

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

    def model_response_str(self) -> str:
        """Return a string representation of the content for the model."""
        if isinstance(self.content, str):
            return self.content
        else:
            return tool_return_ta.dump_json(self.content).decode()

    def model_response_object(self) -> dict[str, Any]:
        """Return a dictionary representation of the content, wrapping non-dict types appropriately."""
        # gemini supports JSON dict return values, but no other JSON types, hence we wrap anything else in a dict
        if isinstance(self.content, dict):
            return tool_return_ta.dump_python(self.content, mode='json')  # pyright: ignore[reportUnknownMemberType]
        else:
            return {'return_value': tool_return_ta.dump_python(self.content, mode='json')}

    def otel_event(self, settings: InstrumentationSettings) -> Event:
        return Event(
            'gen_ai.tool.message',
            body={
                **({'content': self.content} if settings.include_content else {}),
                'role': 'tool',
                'id': self.tool_call_id,
                'name': self.tool_name,
            },
        )

    __repr__ = _utils.dataclasses_no_defaults_repr

tool_name instance-attribute

tool_name: str

The name of the "tool" was called.

content instance-attribute

content: Any

The return value.

tool_call_id instance-attribute

tool_call_id: str

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

metadata class-attribute instance-attribute

metadata: Any = None

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

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp, when the tool returned.

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.

model_response_str

model_response_str() -> str

Return a string representation of the content for the model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
461
462
463
464
465
466
def model_response_str(self) -> str:
    """Return a string representation of the content for the model."""
    if isinstance(self.content, str):
        return self.content
    else:
        return tool_return_ta.dump_json(self.content).decode()

model_response_object

model_response_object() -> dict[str, Any]

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
468
469
470
471
472
473
474
def model_response_object(self) -> dict[str, Any]:
    """Return a dictionary representation of the content, wrapping non-dict types appropriately."""
    # gemini supports JSON dict return values, but no other JSON types, hence we wrap anything else in a dict
    if isinstance(self.content, dict):
        return tool_return_ta.dump_python(self.content, mode='json')  # pyright: ignore[reportUnknownMemberType]
    else:
        return {'return_value': tool_return_ta.dump_python(self.content, mode='json')}

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

    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, PydanticAI 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)
            description = f'{len(self.content)} validation errors: {json_errors.decode()}'
        return f'{description}\n\nFix the errors and try again.'

    def otel_event(self, settings: InstrumentationSettings) -> Event:
        if self.tool_name is None:
            return Event('gen_ai.user.message', body={'content': self.model_response(), 'role': 'user'})
        else:
            return Event(
                '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,
                },
            )

    __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, PydanticAI 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
531
532
533
534
535
536
537
538
539
540
541
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)
        description = f'{len(self.content)} validation errors: {json_errors.decode()}'
    return f'{description}\n\nFix the errors and try again.'

ModelRequestPart module-attribute

A message part sent by PydanticAI to a model.

ModelRequest dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
@dataclass(repr=False)
class ModelRequest:
    """A request generated by PydanticAI and sent to a model, e.g. a message from the PydanticAI app to the model."""

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

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

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

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.

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
579
580
581
582
@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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
@dataclass(repr=False)
class TextPart:
    """A plain text response from a model."""

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

    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.

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
597
598
599
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
@dataclass(repr=False)
class ThinkingPart:
    """A thinking response from a model."""

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

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

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

    The signature is only available on the Anthropic models.
    """

    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)  # pragma: no cover

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

signature class-attribute instance-attribute

signature: str | None = None

The signature of the thinking.

The signature is only available on the Anthropic models.

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
623
624
625
def has_content(self) -> bool:
    """Return `True` if the thinking content is non-empty."""
    return bool(self.content)  # pragma: no cover

ToolCallPart dataclass

A tool call from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
@dataclass(repr=False)
class ToolCallPart:
    """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, PydanticAI will generate a random one.
    """

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

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

        This is just for convenience with models that require dicts as input.
        """
        if not self.args:
            return {}
        if isinstance(self.args, dict):
            return self.args
        args = pydantic_core.from_json(self.args)
        assert isinstance(args, dict), 'args should be a dict'
        return cast(dict[str, Any], 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 arguments contain any data."""
        if isinstance(self.args, dict):
            # TODO: This should probably return True if you have the value False, or 0, etc.
            #   It makes sense to me to ignore empty strings, but not sure about empty lists or dicts
            return any(self.args.values())
        else:
            return bool(self.args)

    __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, PydanticAI will generate a random one.

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.

args_as_dict

args_as_dict() -> dict[str, Any]

Return the arguments as a Python dictionary.

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
652
653
654
655
656
657
658
659
660
661
662
663
def args_as_dict(self) -> dict[str, Any]:
    """Return the arguments as a Python dictionary.

    This is just for convenience with models that require dicts as input.
    """
    if not self.args:
        return {}
    if isinstance(self.args, dict):
        return self.args
    args = pydantic_core.from_json(self.args)
    assert isinstance(args, dict), 'args should be a dict'
    return cast(dict[str, Any], 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
665
666
667
668
669
670
671
672
673
674
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 arguments contain any data.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
676
677
678
679
680
681
682
683
def has_content(self) -> bool:
    """Return `True` if the arguments contain any data."""
    if isinstance(self.args, dict):
        # TODO: This should probably return True if you have the value False, or 0, etc.
        #   It makes sense to me to ignore empty strings, but not sure about empty lists or dicts
        return any(self.args.values())
    else:
        return bool(self.args)

ModelResponsePart module-attribute

ModelResponsePart = Annotated[
    Union[TextPart, ToolCallPart, ThinkingPart],
    Discriminator("part_kind"),
]

A message part returned by a model.

ModelResponse dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
@dataclass(repr=False)
class ModelResponse:
    """A response from a model, e.g. a message from the model to the PydanticAI app."""

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

    usage: Usage = field(default_factory=Usage)
    """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 of the response.

    If the model provides a timestamp in the response (as OpenAI does) that will be used.
    """

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

    vendor_details: dict[str, Any] | None = field(default=None)
    """Additional vendor-specific details in a serializable format.

    This allows storing selected vendor-specific data that isn't mapped to standard ModelResponse fields.
    For OpenAI models, this may include 'logprobs', 'finish_reason', etc.
    """

    vendor_id: str | None = None
    """Vendor ID as specified by the model provider. This can be used to track the specific request to the model."""

    def otel_events(self, settings: InstrumentationSettings) -> list[Event]:
        """Return OpenTelemetry events for the response."""
        result: list[Event] = []

        def new_event_body():
            new_body: dict[str, Any] = {'role': 'assistant'}
            ev = Event('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',  # TODO https://github.com/pydantic/pydantic-ai/issues/888
                        'function': {
                            'name': part.tool_name,
                            'arguments': part.args,
                        },
                    }
                )
            elif isinstance(part, TextPart):
                if body.get('content'):
                    body = new_event_body()
                if settings.include_content:
                    body['content'] = part.content

        return result

    __repr__ = _utils.dataclasses_no_defaults_repr

parts instance-attribute

The parts of the model message.

usage class-attribute instance-attribute

usage: Usage = field(default_factory=Usage)

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 of the response.

If the model provides a timestamp in the response (as OpenAI does) that will be used.

kind class-attribute instance-attribute

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

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

vendor_details class-attribute instance-attribute

vendor_details: dict[str, Any] | None = field(default=None)

Additional vendor-specific details in a serializable format.

This allows storing selected vendor-specific data that isn't mapped to standard ModelResponse fields. For OpenAI models, this may include 'logprobs', 'finish_reason', etc.

vendor_id class-attribute instance-attribute

vendor_id: str | None = None

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

otel_events

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

Return OpenTelemetry events for the response.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
def otel_events(self, settings: InstrumentationSettings) -> list[Event]:
    """Return OpenTelemetry events for the response."""
    result: list[Event] = []

    def new_event_body():
        new_body: dict[str, Any] = {'role': 'assistant'}
        ev = Event('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',  # TODO https://github.com/pydantic/pydantic-ai/issues/888
                    'function': {
                        'name': part.tool_name,
                        'arguments': part.args,
                    },
                }
            )
        elif isinstance(part, TextPart):
            if body.get('content'):
                body = new_event_body()
            if settings.include_content:
                body['content'] = part.content

    return result

ModelMessage module-attribute

ModelMessage = Annotated[
    Union[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
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
@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."""

    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)

    __repr__ = _utils.dataclasses_no_defaults_repr

content_delta instance-attribute

content_delta: str

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

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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
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)

ThinkingPartDelta dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
@dataclass(repr=False)
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.
    """

    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
            return replace(part, content=new_content, signature=new_signature)
        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.signature_delta is not None:
                return replace(part, signature_delta=self.signature_delta)
            if self.content_delta is not None:
                return replace(part, content_delta=self.content_delta)
        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.

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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
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
        return replace(part, content=new_content, signature=new_signature)
    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.signature_delta is not None:
            return replace(part, signature_delta=self.signature_delta)
        if self.content_delta is not None:
            return replace(part, content_delta=self.content_delta)
    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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
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
@dataclass(repr=False)
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."""

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

    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())

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

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

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

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

    def _apply_to_delta(self, delta: ToolCallPartDelta) -> ToolCallPart | 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 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())

        return delta

    def _apply_to_part(self, part: ToolCallPart) -> ToolCallPart:
        """Internal helper to apply this delta directly to a `ToolCallPart`."""
        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)
        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.

part_delta_kind class-attribute instance-attribute

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

Part delta type identifier, used as a discriminator.

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
874
875
876
877
878
879
880
881
882
883
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())

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 | ToolCallPartDelta

Either a new ToolCallPart or an updated ToolCallPartDelta.

Raises:

Type Description
ValueError

If part is neither a ToolCallPart nor a ToolCallPartDelta.

UnexpectedModelBehavior

If applying JSON deltas to dict arguments or vice versa.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
def apply(self, part: ModelResponsePart | ToolCallPartDelta) -> ToolCallPart | 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 an updated `ToolCallPartDelta`.

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

ModelResponsePartDelta module-attribute

ModelResponsePartDelta = Annotated[
    Union[
        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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
@dataclass(repr=False)
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`."""

    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.

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
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
@dataclass(repr=False)
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.

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
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
@dataclass(repr=False)
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[
    Union[PartStartEvent, PartDeltaEvent],
    Discriminator("event_kind"),
]

An event in the model response stream, either starting a new part or applying a delta to an existing one.

AgentStreamEvent module-attribute

An event in the agent stream.

FunctionToolCallEvent dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
@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."""
    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.

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
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
@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."""
    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.

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.