ChatMessage Class
Represents a chat message.
Initialize ChatMessage.
Constructor
ChatMessage()
Parameters
| Name | Description |
|---|---|
|
role
Required
|
The role of the author of the message (Role, string, or dict). |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
text
|
Optional text content of the message. Default value: None
|
|
contents
|
Optional list of BaseContent items or dicts to include in the message. Default value: None
|
|
author_name
|
Optional name of the author of the message. Default value: None
|
|
message_id
|
Optional ID of the chat message. Default value: None
|
|
additional_properties
|
Optional additional properties associated with the chat message. Additional properties are used within Agent Framework, they are not sent to services. Default value: None
|
|
raw_representation
|
Optional raw representation of the chat message. Default value: None
|
|
kwargs
|
will be combined with additional_properties if provided. |
Examples
from agent_framework import ChatMessage, TextContent
# Create a message with text
user_msg = ChatMessage(role="user", text="What's the weather?")
print(user_msg.text) # "What's the weather?"
# Create a message with role string
system_msg = ChatMessage(role="system", text="You are a helpful assistant.")
# Create a message with contents
assistant_msg = ChatMessage(
role="assistant",
contents=[TextContent(text="The weather is sunny!")],
)
print(assistant_msg.text) # "The weather is sunny!"
# Serialization - to_dict and from_dict
msg_dict = user_msg.to_dict()
# {'type': 'chat_message', 'role': {'type': 'role', 'value': 'user'},
# 'contents': [{'type': 'text', 'text': "What's the weather?"}], 'additional_properties': {}}
restored_msg = ChatMessage.from_dict(msg_dict)
print(restored_msg.text) # "What's the weather?"
# Serialization - to_json and from_json
msg_json = user_msg.to_json()
# '{"type": "chat_message", "role": {"type": "role", "value": "user"}, "contents": [...], ...}'
restored_from_json = ChatMessage.from_json(msg_json)
print(restored_from_json.role.value) # "user"
Methods
| __init__ |
Initialize ChatMessage. |
| __new__ | |
| from_dict |
Create an instance from a dictionary with optional dependency injection. This method reconstructs an object from its dictionary representation, automatically handling type conversion and dependency injection. It supports three patterns of dependency injection to handle different scenarios where external dependencies need to be provided at deserialization time. |
| from_json |
Create an instance from a JSON string. This is a convenience method that parses the JSON string using |
| to_dict |
Convert the instance and any nested objects to a dictionary. This method performs deep serialization, automatically converting nested
Fields marked in |
| to_json |
Convert the instance to a JSON string. This is a convenience method that calls |
__init__
Initialize ChatMessage.
__init__(role: Role | Literal['system', 'user', 'assistant', 'tool'], *, text: str, author_name: str | None = None, message_id: str | None = None, additional_properties: MutableMapping[str, Any] | None = None, raw_representation: Any | None = None, **kwargs: Any) -> None
Parameters
| Name | Description |
|---|---|
|
role
Required
|
The role of the author of the message (Role, string, or dict). |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
text
|
Optional text content of the message. Default value: None
|
|
contents
|
Optional list of BaseContent items or dicts to include in the message. Default value: None
|
|
author_name
|
Optional name of the author of the message. Default value: None
|
|
message_id
|
Optional ID of the chat message. Default value: None
|
|
additional_properties
|
Optional additional properties associated with the chat message. Additional properties are used within Agent Framework, they are not sent to services. Default value: None
|
|
raw_representation
|
Optional raw representation of the chat message. Default value: None
|
|
kwargs
|
will be combined with additional_properties if provided. |
__new__
__new__(**kwargs)
from_dict
Create an instance from a dictionary with optional dependency injection.
This method reconstructs an object from its dictionary representation, automatically handling type conversion and dependency injection. It supports three patterns of dependency injection to handle different scenarios where external dependencies need to be provided at deserialization time.
from_dict()
Positional-Only Parameters
| Name | Description |
|---|---|
|
value
Required
|
|
Parameters
| Name | Description |
|---|---|
|
value
Required
|
The dictionary containing the instance data (positional-only). Must include a 'type' field matching the class type identifier. |
|
dependencies
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
dependencies
|
A nested dictionary mapping type identifiers to their injectable dependencies. The structure varies based on injection pattern:
Default value: None
|
Returns
| Type | Description |
|---|---|
|
<xref:agent_framework._serialization.TClass>
|
New instance of the class with injected dependencies. |
Exceptions
| Type | Description |
|---|---|
|
If the 'type' field in the data doesn't match the class type identifier. |
Examples
Simple Client Injection - OpenAI client dependency injection:
from agent_framework.openai import OpenAIChatClient
from openai import AsyncOpenAI
# OpenAI chat client requires an AsyncOpenAI client instance
# The client is marked as INJECTABLE = {"client"} in OpenAIBase
# Serialized data contains only the model configuration
client_data = {
"type": "open_ai_chat_client",
"model_id": "gpt-4o-mini",
# client is excluded from serialization
}
# Provide the OpenAI client during deserialization
openai_client = AsyncOpenAI(api_key="your-api-key")
dependencies = {"open_ai_chat_client": {"client": openai_client}}
# The chat client is reconstructed with the OpenAI client injected
chat_client = OpenAIChatClient.from_dict(client_data, dependencies=dependencies)
# Now ready to make API calls with the injected client
Function Injection for Tools - AIFunction runtime dependency:
from agent_framework import AIFunction
from typing import Annotated
# Define a function to be wrapped
async def get_current_weather(location: Annotated[str, "The city name"]) -> str:
# In real implementation, this would call a weather API
return f"Current weather in {location}: 72°F and sunny"
# AIFunction has INJECTABLE = {"func"}
function_data = {
"type": "ai_function",
"name": "get_weather",
"description": "Get current weather for a location",
# func is excluded from serialization
}
# Inject the actual function implementation during deserialization
dependencies = {"ai_function": {"func": get_current_weather}}
# Reconstruct the AIFunction with the callable injected
weather_func = AIFunction.from_dict(function_data, dependencies=dependencies)
# The function is now callable and ready for agent use
Middleware Context Injection - Agent execution context:
from agent_framework._middleware import AgentRunContext
from agent_framework import BaseAgent
# AgentRunContext has INJECTABLE = {"agent", "result"}
context_data = {
"type": "agent_run_context",
"messages": [{"role": "user", "text": "Hello"}],
"is_streaming": False,
"metadata": {"session_id": "abc123"},
# agent and result are excluded from serialization
}
# Inject agent and result during middleware processing
my_agent = BaseAgent(name="test-agent")
dependencies = {
"agent_run_context": {
"agent": my_agent,
"result": None, # Will be populated during execution
}
}
# Reconstruct context with agent dependency for middleware chain
context = AgentRunContext.from_dict(context_data, dependencies=dependencies)
# Middleware can now access context.agent and process the execution
This injection system allows the agent framework to maintain clean separation between serializable configuration and runtime dependencies like API clients, functions, and execution contexts that cannot or should not be persisted.
from_json
Create an instance from a JSON string.
This is a convenience method that parses the JSON string using json.loads()
and then calls from_dict() to reconstruct the object. All dependency injection
capabilities are available through the dependencies parameter.
from_json()
Positional-Only Parameters
| Name | Description |
|---|---|
|
value
Required
|
|
Parameters
| Name | Description |
|---|---|
|
value
Required
|
The JSON string containing the instance data (positional-only). Must be valid JSON that deserializes to a dictionary with a 'type' field. |
|
dependencies
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
dependencies
|
A nested dictionary mapping type identifiers to their injectable dependencies. See from_dict for detailed structure and examples of the three injection patterns (simple, dict parameter, and instance-specific). Default value: None
|
Returns
| Type | Description |
|---|---|
|
<xref:agent_framework._serialization.TClass>
|
New instance of the class with any specified dependencies injected. |
Exceptions
| Type | Description |
|---|---|
|
If the JSON string is malformed. |
|
|
If the parsed data doesn't contain a valid 'type' field. |
to_dict
Convert the instance and any nested objects to a dictionary.
This method performs deep serialization, automatically converting nested
SerializationProtocol objects, lists, and dictionaries containing
serializable objects. Non-serializable objects are skipped with debug logging.
Fields marked in DEFAULT_EXCLUDE and INJECTABLE are automatically
excluded from the output, as are any private attributes (starting with '_').
to_dict(*, exclude: set[str] | None = None, exclude_none: bool = True) -> dict[str, Any]
Parameters
| Name | Description |
|---|---|
|
exclude
Required
|
|
|
exclude_none
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
exclude
|
Additional field names to exclude from serialization beyond
the default exclusions ( Default value: None
|
|
exclude_none
|
Whether to exclude None values from the output. When True, None values are omitted from the dictionary. Defaults to True. Default value: True
|
Returns
| Type | Description |
|---|---|
|
Dictionary representation of the instance including a 'type' field for type identification during deserialization (unless 'type' is excluded). |
to_json
Convert the instance to a JSON string.
This is a convenience method that calls to_dict() and then serializes
the result using json.dumps(). All the same serialization rules apply
as in to_dict(), including automatic exclusion of injectable dependencies
and deep serialization of nested objects.
to_json(*, exclude: set[str] | None = None, exclude_none: bool = True, **kwargs: Any) -> str
Parameters
| Name | Description |
|---|---|
|
exclude
Required
|
|
|
exclude_none
Required
|
|
|
kwargs
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
exclude
|
Additional field names to exclude from serialization. Default value: None
|
|
exclude_none
|
Whether to exclude None values from the output. Defaults to True. Default value: True
|
|
**kwargs
|
Additional keyword arguments passed through to |
Returns
| Type | Description |
|---|---|
|
JSON string representation of the instance. |
Attributes
text
Returns the text content of the message.
Remarks: This property concatenates the text of all TextContent objects in Contents.
role
The role of the author of the message.
contents
The chat message content items.
author_name
The name of the author of the message.
message_id
The ID of the chat message.
additional_properties
Any additional properties associated with the chat message. Additional properties are used within Agent Framework, they are not sent to services.
raw_representation
The raw representation of the chat message from an underlying implementation.
DEFAULT_EXCLUDE
DEFAULT_EXCLUDE: ClassVar[set[str]] = {'raw_representation'}
INJECTABLE
INJECTABLE: ClassVar[set[str]] = {}