Skip to main content

Message

Represents a message in the conversation.

Class

@dataclass
class Message:
role: str
content: str
tool_calls: list[dict[str, Any]] = field(default_factory=list)
tool_call_id: str | None = None
name: str | None = None

Attributes

AttributeTypeDescription
rolestrMessage role: "system", "user", "assistant", "tool"
contentstrMessage content
tool_callslist[dict]Tool calls made by the assistant
tool_call_idstr | NoneID of the tool call this message responds to
namestr | NoneTool name (for tool messages)

Methods

to_dict

def to_dict(self) -> dict[str, Any]

Convert to API format.

msg = Message(role="user", content="Hello")
msg.to_dict()
# {"role": "user", "content": "Hello"}

from_dict

@classmethod
def from_dict(cls, data: dict[str, Any]) -> Message

Create a Message from a dictionary.

msg = Message.from_dict({"role": "user", "content": "Hello"})

Message types

System message

Message(role="system", content="You are a helpful assistant.")

User message

Message(role="user", content="What is 2 + 2?")

Assistant message

# Simple response
Message(role="assistant", content="The answer is 4.")

# With tool call
Message(
role="assistant",
content="",
tool_calls=[{
"id": "call_123",
"function": {
"name": "calculate",
"arguments": '{"expression": "2 + 2"}'
}
}]
)

Tool message

Message(
role="tool",
content="4",
tool_call_id="call_123",
name="calculate"
)

Accessing conversation history

agent = Agent()
await agent.run("Hello")
await agent.run("How are you?")

for msg in agent.messages:
print(f"[{msg.role}] {msg.content}")

Output:

[system] You are a helpful assistant...
[user] Hello
[assistant] Hi! How can I help you today?
[user] How are you?
[assistant] I'm doing well, thank you for asking!