TextContent Class
Represents text content in a chat.
Initializes a TextContent instance.
Constructor
TextContent()
Parameters
| Name | Description |
|---|---|
|
text
Required
|
The text content represented by this instance. |
Keyword-Only Parameters
| Name | Description |
|---|---|
|
additional_properties
|
Optional additional properties associated with the content. Default value: None
|
|
raw_representation
|
Optional raw representation of the content. Default value: None
|
|
annotations
|
Optional annotations associated with the content. Default value: None
|
|
**kwargs
|
Any additional keyword arguments. |
Examples
from agent_framework import TextContent
# Create basic text content
text = TextContent(text="Hello, world!")
print(text.text) # "Hello, world!"
# Concatenate text content
text1 = TextContent(text="Hello, ")
text2 = TextContent(text="world!")
combined = text1 + text2
print(combined.text) # "Hello, world!"
Methods
| __init__ |
Initializes a TextContent instance. |
| __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 to a dictionary. Extracts additional_properties fields to the root level. |
| to_json |
Convert the instance to a JSON string. This is a convenience method that calls |
__init__
Initializes a TextContent instance.
__init__(text: str, *, additional_properties: dict[str, Any] | None = None, raw_representation: Any | None = None, annotations: Sequence[CitationAnnotation | MutableMapping[str, Any]] | None = None, **kwargs: Any)
Parameters
| Name | Description |
|---|---|
|
text
Required
|
The text content represented by this instance. |
|
additional_properties
Required
|
|
|
raw_representation
Required
|
|
|
annotations
Required
|
|
|
kwargs
Required
|
|
Keyword-Only Parameters
| Name | Description |
|---|---|
|
additional_properties
|
Optional additional properties associated with the content. Default value: None
|
|
raw_representation
|
Optional raw representation of the content. Default value: None
|
|
annotations
|
Optional annotations associated with the content. Default value: None
|
|
**kwargs
|
Any additional keyword arguments. |
__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 to a dictionary.
Extracts additional_properties fields to the root level.
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
|
Set of 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
|
Returns
| Type | Description |
|---|---|
|
Dictionary representation of the instance. |
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
The text content represented by this instance.
type
The type of content, which is always "text" for this class.
annotations
Optional annotations associated with the content.
annotations: list[CitationAnnotation] | None
additional_properties
Optional additional properties associated with the content.
raw_representation
Optional raw representation of the content.
DEFAULT_EXCLUDE
DEFAULT_EXCLUDE: ClassVar[set[str]] = {'additional_properties', 'raw_representation'}
INJECTABLE
INJECTABLE: ClassVar[set[str]] = {}