跳过内容

pydantic_ai.messages

ModelMessage的结构可以表示为图形:

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

系统提示部分 dataclass

系统提示,一般由应用程序开发人员编写。

这为模型提供了上下文和指导,关于如何回应。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@dataclass
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."""

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

内容 instance-attribute

content: str

提示的内容。

动态引用 class-attribute instance-attribute

dynamic_ref: str | None = None

生成此部分的动态系统提示函数的引用。

仅在系统提示是动态时设置,请参见 system_prompt 以获取更多信息。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

音频网址 dataclass

一个指向音频文件的URL。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
@dataclass
class AudioUrl:
    """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."""
        if self.url.endswith('.mp3'):
            return 'audio/mpeg'
        elif self.url.endswith('.wav'):
            return 'audio/wav'
        else:
            raise ValueError(f'Unknown audio file extension: {self.url}')

网址 instance-attribute

url: str

音频文件的 URL。

类型 类属性 实例属性

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

类型标识符,这在所有部分作为区分符可用。

媒体类型 property

media_type: AudioMediaType

根据URL返回音频文件的媒体类型。

图片网址 dataclass

一个指向图像的URL。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
@dataclass
class ImageUrl:
    """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}')

网址 instance-attribute

url: str

图像的URL。

类型 类属性 实例属性

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

类型标识符,这在所有部分作为一个区分符是可用的。

媒体类型 property

media_type: ImageMediaType

根据网址返回图像的媒体类型。

二进制内容 dataclass

二进制内容,例如音频或图像文件。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
 87
 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
@dataclass
class BinaryContent:
    """Binary content, e.g. an audio or image file."""

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

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

    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 audio_format(self) -> Literal['mp3', 'wav']:
        """Return the audio format given the media type."""
        if self.media_type == 'audio/mpeg':
            return 'mp3'
        elif self.media_type == 'audio/wav':
            return 'wav'
        else:
            raise ValueError(f'Unknown audio media type: {self.media_type}')

数据 instance-attribute

data: bytes

二进制数据。

媒体类型 instance-attribute

media_type: AudioMediaType | ImageMediaType | str

二进制数据的媒体类型。

类型 类属性 实例属性

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

类型标识符,这在所有部分作为一个区分符是可用的。

is_audio property

is_audio: bool

如果媒体类型是音频类型,则返回 True

is_image property

is_image: bool

如果媒体类型是图像类型,则返回 True

音频格式 property

audio_format: Literal['mp3', 'wav']

根据媒体类型返回音频格式。

用户提示部分 dataclass

用户提示,一般由最终用户编写。

内容来自 user_prompt 参数的 Agent.run, Agent.run_sync, 和 Agent.run_stream

Source code in pydantic_ai_slim/pydantic_ai/messages.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
@dataclass
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."""

内容 instance-attribute

content: str | Sequence[UserContent]

提示的内容。

时间戳 class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

提示的时间戳。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

工具返回部分 dataclass

一个工具返回消息,这编码了运行工具的结果。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
171
172
173
174
175
176
177
@dataclass
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 | None = None
    """Optional tool call identifier, this is used by some models including OpenAI."""

    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')}

工具名称 instance-attribute

tool_name: str

“工具”的名称被调用。

内容 instance-attribute

content: Any

返回值。

工具调用ID 类属性 实例属性

tool_call_id: str | None = None

可选的工具调用标识符,这由一些模型使用,包括OpenAI。

时间戳 class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

该工具返回的时间戳。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

模型响应字符串

model_response_str() -> str

返回模型内容的字符串表示。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
164
165
166
167
168
169
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() -> dict[str, Any]

返回内容的字典表示,适当地包装非字典类型。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
171
172
173
174
175
176
177
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')}

重试提示部分 dataclass

向模型发送的消息,请求它重试。

这可以出于多种原因发送:

  • Pydantic工具参数验证失败,这里的内容源自Pydantic ValidationError
  • 一个工具引发了 ModelRetry 异常
  • 未找到该工具名称的工具
  • 模型在预期结构化响应时返回了纯文本
  • Pydantic对结构化响应的验证失败,这里的内容源自Pydantic ValidationError
  • 一个结果验证器引发了一个 ModelRetry 异常
Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
@dataclass
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]
    * a result 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 | None = None
    """Optional tool call identifier, this is used by some models including OpenAI."""

    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):
            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.'

内容 instance-attribute

content: list[ErrorDetails] | str

模型应当为什么以及如何重试的详细信息。

如果重试是由一个 ValidationError 触发的,这将是一个错误详情的列表。

工具名称 class-attribute instance-attribute

tool_name: str | None = None

被调用的工具的名称(如果有的话)。

工具调用ID 类属性 实例属性

tool_call_id: str | None = None

可选的工具调用标识符,这在一些模型中使用,包括OpenAI。

时间戳 class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

重试被触发的时间戳。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

模型响应

model_response() -> str

返回一条字符串消息,描述为什么请求重试。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
218
219
220
221
222
223
224
225
def model_response(self) -> str:
    """Return a string message describing why the retry is requested."""
    if isinstance(self.content, str):
        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.'

模型请求部分 module-attribute

PydanticAI 发送给模型的消息部分。

模型请求 dataclass

由 PydanticAI 生成并发送到模型的请求,例如,来自 PydanticAI 应用程序到模型的消息。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
234
235
236
237
238
239
240
241
242
@dataclass
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."""

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

部分 instance-attribute

用户消息的部分。

类型 类属性 实例属性

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

消息类型标识符,这在所有部分作为区分符是可用的。

文本部分 dataclass

模型的普通文本响应。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
245
246
247
248
249
250
251
252
253
254
255
256
257
@dataclass
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)

内容 instance-attribute

content: str

响应的文本内容。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

有内容

has_content() -> bool

如果文本内容不为空,则返回 True

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

工具调用部分 dataclass

来自模型的工具。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
260
261
262
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
@dataclass
class ToolCallPart:
    """A tool call from a model."""

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

    args: str | dict[str, Any]
    """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 | None = None
    """Optional tool call identifier, this is used by some models including OpenAI."""

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

工具名称 instance-attribute

tool_name: str

调用的工具名称。

参数 instance-attribute

args: str | dict[str, Any]

传递给工具的参数。

这根据数据接收的方式存储为 JSON 字符串或 Python 字典。

工具调用ID 类属性 实例属性

tool_call_id: str | None = None

可选的工具调用标识符,这在一些模型中使用,包括OpenAI。

部分类型 类属性 实例属性

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

部件类型标识符,这在所有部件中作为区分符可用。

将参数作为字典

args_as_dict() -> dict[str, Any]

将参数作为Python字典返回。

这只是为需要字典作为输入的模型提供便利。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
279
280
281
282
283
284
285
286
287
288
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 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)

作为JSON字符串的参数

args_as_json_str() -> str

将参数作为JSON字符串返回。

这只是为了方便需要JSON字符串作为输入的模型。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
290
291
292
293
294
295
296
297
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 isinstance(self.args, str):
        return self.args
    return pydantic_core.to_json(self.args).decode()

有内容

has_content() -> bool

如果参数包含任何数据,则返回 True

Source code in pydantic_ai_slim/pydantic_ai/messages.py
299
300
301
302
303
304
305
306
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)

模型响应部分 module-attribute

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

模型返回的消息部分。

模型响应 dataclass

模型的响应,例如,模型向PydanticAI应用程序发送的消息。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
@dataclass
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."""

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

部分 instance-attribute

模型消息的各个部分。

模型名称 class-attribute instance-attribute

model_name: str | None = None

生成响应的模型名称。

时间戳 class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

响应的时间戳。

如果模型在响应中提供时间戳(就像OpenAI一样),将使用该时间戳。

类型 类属性 实例属性

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

消息类型标识符,这在所有部分作为区分符是可用的。

模型消息 module-attribute

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

发送到模型或由模型返回的任何消息。

模型消息类型适配器 module-attribute

ModelMessagesTypeAdapter = TypeAdapter(
    list[ModelMessage], config=ConfigDict(defer_build=True)
)

Pydantic TypeAdapter 用于 (反)序列化消息。

文本部分增量 dataclass

TextPart进行部分更新(增量),以附加新的文本内容。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
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
@dataclass
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')
        return replace(part, content=part.content + self.content_delta)

内容增量 instance-attribute

content_delta: str

要添加到现有 TextPart 内容的增量文本。

部分增量类型 类属性 实例属性

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

部分增量类型标识符,用作区分符。

应用

apply(part: ModelResponsePart) -> TextPart

将此文本增量应用于现有的 TextPart

参数:

名称 类型 描述 默认值
part ModelResponsePart

现有的模型响应部分,必须是一个 TextPart

required

返回:

类型 描述
TextPart

一个新的 TextPart,包含更新的文本内容。

引发:

类型 描述
ValueError

如果 part 不是一个 TextPart

Source code in pydantic_ai_slim/pydantic_ai/messages.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
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')
    return replace(part, content=part.content + self.content_delta)

工具调用部分增量 dataclass

ToolCallPart的部分更新(增量),以修改工具名称、参数或工具调用ID。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
367
368
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
413
414
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
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
488
489
490
491
492
493
494
495
496
497
@dataclass
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 both `tool_name_delta` and `args_delta` are set, otherwise `None`.
        """
        if self.tool_name_delta is None or self.args_delta is None:
            return None

        return ToolCallPart(
            self.tool_name_delta,
            self.args_delta,
            self.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(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:
            # Set the tool_call_id if it wasn't present, otherwise error if it has changed
            if delta.tool_call_id is not None and delta.tool_call_id != self.tool_call_id:
                raise UnexpectedModelBehavior(
                    f'Cannot apply a new tool_call_id to a ToolCallPartDelta that already has one ({delta=}, {self=})'
                )
            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 and delta.args_delta is not None:
            return ToolCallPart(
                delta.tool_name_delta,
                delta.args_delta,
                delta.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 not isinstance(part.args, str):
                raise UnexpectedModelBehavior(f'Cannot apply JSON deltas to non-JSON tool arguments ({part=}, {self=})')
            updated_json = part.args + self.args_delta
            part = replace(part, args=updated_json)
        elif isinstance(self.args_delta, dict):
            if not isinstance(part.args, dict):
                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:
            # Replace the tool_call_id entirely if given
            if part.tool_call_id is not None and part.tool_call_id != self.tool_call_id:
                raise UnexpectedModelBehavior(
                    f'Cannot apply a new tool_call_id to a ToolCallPartDelta that already has one ({part=}, {self=})'
                )
            part = replace(part, tool_call_id=self.tool_call_id)
        return part

工具名称变化 类属性 实例属性

tool_name_delta: str | None = None

要添加到现有工具名称的增量文本(如果有的话)。

args_delta 类属性 实例属性

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

要添加到工具参数的增量数据。

如果这是一个字符串,它将被附加到现有的JSON参数中。如果这是一个字典,它将与现有的字典参数合并。

工具调用ID 类属性 实例属性

tool_call_id: str | None = None

可选的工具调用标识符,这在一些模型中使用,包括OpenAI。

请注意,这永远不会被视为一个增量 — 它可以替换 None,但如果提供了一个不匹配的值,将会引发错误。

部分增量类型 类属性 实例属性

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

部分增量类型标识符,用作区分符。

as_part

as_part() -> ToolCallPart | None

如果可能,将这个增量转换为完整的 ToolCallPart,否则返回 None

返回:

类型 描述
ToolCallPart | None

如果同时设置了 tool_name_deltaargs_delta,则为 ToolCallPart,否则为 None

Source code in pydantic_ai_slim/pydantic_ai/messages.py
390
391
392
393
394
395
396
397
398
399
400
401
402
403
def as_part(self) -> ToolCallPart | None:
    """Convert this delta to a fully formed `ToolCallPart` if possible, otherwise return `None`.

    Returns:
        A `ToolCallPart` if both `tool_name_delta` and `args_delta` are set, otherwise `None`.
    """
    if self.tool_name_delta is None or self.args_delta is None:
        return None

    return ToolCallPart(
        self.tool_name_delta,
        self.args_delta,
        self.tool_call_id,
    )

应用

将此增量应用于一个部分或增量,返回应用了更改的新部分或增量。

参数:

名称 类型 描述 默认值
part ModelResponsePart | ToolCallPartDelta

现有模型响应部分或更新的增量。

required

返回:

类型 描述
ToolCallPart | ToolCallPartDelta

一个新的 ToolCallPart 或者一个更新的 ToolCallPartDelta

引发:

类型 描述
ValueError

如果 part 既不是 ToolCallPart 也不是 ToolCallPartDelta

UnexpectedModelBehavior

如果将JSON增量应用于字典参数或反之。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
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(f'Can only apply ToolCallPartDeltas to ToolCallParts or ToolCallPartDeltas, not {part}')

模型响应部分增量 module-attribute

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

任何模型响应部分的局部更新(增量)。

开始事件 dataclass

一个表示新部分已开始的事件。

如果接收到多个相同索引的 PartStartEvent,新的应该完全替代旧的。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
@dataclass
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."""

索引 instance-attribute

index: int

该部分在整体响应部件列表中的索引。

部分 instance-attribute

新启动的 ModelResponsePart

事件类型 类属性 实例属性

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

事件类型标识符,用作区分符。

部分增量事件 dataclass

一个指示现有部分的增量更新的事件。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
522
523
524
525
526
527
528
529
530
531
532
533
@dataclass
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."""

索引 instance-attribute

index: int

该部分在整体响应部件列表中的索引。

delta 实例属性

要应用于指定部分的增量。

事件类型 类属性 实例属性

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

事件类型标识符,用作区分符。

模型响应流事件 module-attribute

ModelResponseStreamEvent = Annotated[
    Union[PartStartEvent, PartDeltaEvent],
    Discriminator("event_kind"),
]

模型响应流中的一个事件,可以是开始一个新部分或对现有部分应用增量。

函数工具调用事件 dataclass

一个指示调用函数工具开始的事件。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
540
541
542
543
544
545
546
547
548
549
550
551
552
@dataclass
class FunctionToolCallEvent:
    """An event indicating the start to a call to a function tool."""

    part: ToolCallPart
    """The (function) tool call to make."""
    call_id: str = field(init=False)
    """An ID used for matching details about the call to its result. If present, defaults to the part's tool_call_id."""
    event_kind: Literal['function_tool_call'] = 'function_tool_call'
    """Event type identifier, used as a discriminator."""

    def __post_init__(self):
        self.call_id = self.part.tool_call_id or str(uuid.uuid4())

部分 instance-attribute

要进行的(函数)工具调用。

调用ID class-attribute instance-attribute

call_id: str = field(init=False)

用于将呼叫的详细信息与其结果匹配的ID。如果存在,默认为该部分的tool_call_id。

事件类型 类属性 实例属性

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

事件类型标识符,用作区分符。

函数工具结果事件 dataclass

表示函数工具调用结果的事件。

Source code in pydantic_ai_slim/pydantic_ai/messages.py
555
556
557
558
559
560
561
562
563
564
@dataclass
class FunctionToolResultEvent:
    """An event indicating the result of a function tool call."""

    result: ToolReturnPart | RetryPromptPart
    """The result of the call to the function tool."""
    call_id: str
    """An ID used to match the result to its original call."""
    event_kind: Literal['function_tool_result'] = 'function_tool_result'
    """Event type identifier, used as a discriminator."""

结果 instance-attribute

对函数工具的调用结果。

调用ID instance-attribute

call_id: str

用于将结果与其原始调用匹配的ID。

事件类型 类属性 实例属性

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

事件类型标识符,用作区分符。