Skip to content

pydantic_ai.messages

Message module-attribute

Any message send to or returned by a model.

SystemPrompt 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
18
19
20
21
22
23
24
25
26
27
28
@dataclass
class SystemPrompt:
    """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."""
    role: Literal['system'] = 'system'
    """Message type identifier, this type is available on all message as a discriminator."""

content instance-attribute

content: str

The content of the prompt.

role class-attribute instance-attribute

role: Literal['system'] = 'system'

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

UserPrompt 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass
class UserPrompt:
    """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
    """The content of the prompt."""
    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp of the prompt."""
    role: Literal['user'] = 'user'
    """Message type identifier, this type is available on all message as a discriminator."""

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.

role class-attribute instance-attribute

role: Literal['user'] = 'user'

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

ToolReturn dataclass

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

Source code in pydantic_ai_slim/pydantic_ai/messages.py
56
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
@dataclass
class ToolReturn:
    """A tool return message, this encodes the result of running a tool."""

    tool_name: str
    """The name of the "tool" was called."""
    content: JsonData
    """The return value."""
    tool_id: str | None = None
    """Optional tool identifier, this is used by some models including OpenAI."""
    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp, when the tool returned."""
    role: Literal['tool-return'] = 'tool-return'
    """Message type identifier, this type is available on all message as a discriminator."""

    def model_response_str(self) -> str:
        if isinstance(self.content, str):
            return self.content
        else:
            content = json_ta.validate_python(self.content)
            return json_ta.dump_json(content).decode()

    def model_response_object(self) -> dict[str, JsonData]:
        # 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 json_ta.validate_python(self.content)  # pyright: ignore[reportReturnType]
        else:
            return {'return_value': json_ta.validate_python(self.content)}

tool_name instance-attribute

tool_name: str

The name of the "tool" was called.

content instance-attribute

content: JsonData

The return value.

tool_id class-attribute instance-attribute

tool_id: str | None = None

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

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp, when the tool returned.

role class-attribute instance-attribute

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

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

RetryPrompt 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
  • a result validator raised a ModelRetry exception
Source code in pydantic_ai_slim/pydantic_ai/messages.py
 86
 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
119
120
121
122
@dataclass
class RetryPrompt:
    """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_id: str | None = None
    """The tool identifier, if any."""
    timestamp: datetime = field(default_factory=_now_utc)
    """The timestamp, when the retry was triggered."""
    role: Literal['retry-prompt'] = 'retry-prompt'
    """Message type identifier, this type is available on all message as a discriminator."""

    def model_response(self) -> str:
        if isinstance(self.content, str):
            description = self.content
        else:
            description = f'{len(self.content)} validation errors: {json.dumps(self.content, indent=2)}'
        return f'{description}\n\nFix the errors and try again.'

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_id class-attribute instance-attribute

tool_id: str | None = None

The tool identifier, if any.

timestamp class-attribute instance-attribute

timestamp: datetime = field(default_factory=now_utc)

The timestamp, when the retry was triggered.

role class-attribute instance-attribute

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

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

ModelAnyResponse module-attribute

Any response from a model.

ModelTextResponse dataclass

A plain text response from a model.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
125
126
127
128
129
130
131
132
133
134
135
136
137
@dataclass
class ModelTextResponse:
    """A plain text response from a model."""

    content: str
    """The text content of 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.
    """
    role: Literal['model-text-response'] = 'model-text-response'
    """Message type identifier, this type is available on all message as a discriminator."""

content instance-attribute

content: str

The text content of 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.

role class-attribute instance-attribute

role: Literal["model-text-response"] = "model-text-response"

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

ModelStructuredResponse dataclass

A structured response from a model.

This is used either to call a tool or to return a structured response from an agent run.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@dataclass
class ModelStructuredResponse:
    """A structured response from a model.

    This is used either to call a tool or to return a structured response from an agent run.
    """

    calls: list[ToolCall]
    """The tool calls being made."""
    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.
    """
    role: Literal['model-structured-response'] = 'model-structured-response'
    """Message type identifier, this type is available on all message as a discriminator."""

calls instance-attribute

calls: list[ToolCall]

The tool calls being made.

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.

role class-attribute instance-attribute

role: Literal["model-structured-response"] = (
    "model-structured-response"
)

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

ToolCall dataclass

Either a tool call from the agent.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
@dataclass
class ToolCall:
    """Either a tool call from the agent."""

    tool_name: str
    """The name of the tool to call."""
    args: ArgsJson | ArgsDict
    """The arguments to pass to the tool.

    Either as JSON or a Python dictionary depending on how data was returned.
    """
    tool_id: str | None = None
    """Optional tool identifier, this is used by some models including OpenAI."""

    @classmethod
    def from_json(cls, tool_name: str, args_json: str, tool_id: str | None = None) -> ToolCall:
        return cls(tool_name, ArgsJson(args_json), tool_id)

    @classmethod
    def from_dict(cls, tool_name: str, args_dict: dict[str, Any]) -> ToolCall:
        return cls(tool_name, ArgsDict(args_dict))

    def has_content(self) -> bool:
        if isinstance(self.args, ArgsDict):
            return any(self.args.args_dict.values())
        else:
            return bool(self.args.args_json)

tool_name instance-attribute

tool_name: str

The name of the tool to call.

args instance-attribute

args: ArgsJson | ArgsDict

The arguments to pass to the tool.

Either as JSON or a Python dictionary depending on how data was returned.

tool_id class-attribute instance-attribute

tool_id: str | None = None

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

ArgsJson dataclass

Tool arguments as a JSON string.

Source code in pydantic_ai_slim/pydantic_ai/messages.py
140
141
142
143
144
145
@dataclass
class ArgsJson:
    """Tool arguments as a JSON string."""

    args_json: str
    """A JSON string of arguments."""

args_json instance-attribute

args_json: str

A JSON string of arguments.

MessagesTypeAdapter module-attribute

MessagesTypeAdapter = LazyTypeAdapter(
    list[Annotated[Message, Field(discriminator="role")]]
)

Pydantic TypeAdapter for (de)serializing messages.