strands.agent.agent
Agent Interface.
This module implements the core Agent class that serves as the primary entry point for interacting with foundation models and tools in the SDK.
The Agent interface supports two complementary interaction patterns:
- Natural language for conversation:
agent("Analyze this data") - Method-style for direct tool access:
agent.tool.tool_name(param1="value")
Agent
class Agent(AgentBase)Defined in: src/strands/agent/agent.py:94
Core Agent implementation.
An agent orchestrates the following workflow:
- Receives user input
- Processes the input using a language model
- Decides whether to use tools to gather information or perform actions
- Executes those tools and receives results
- Continues reasoning with the new information
- Produces a final response
__init__
def __init__( model: Model | str | None = None, messages: Messages | None = None, tools: list[Union[str, dict[str, str], "ToolProvider", Any]] | None = None, system_prompt: str | list[SystemContentBlock] | None = None, structured_output_model: type[BaseModel] | None = None, callback_handler: Callable[..., Any] | _DefaultCallbackHandlerSentinel | None = _DEFAULT_CALLBACK_HANDLER, conversation_manager: ConversationManager | None = None, record_direct_tool_call: bool = True, load_tools_from_directory: bool = False, trace_attributes: Mapping[str, AttributeValue] | None = None, *, agent_id: str | None = None, name: str | None = None, description: str | None = None, state: AgentState | dict | None = None, hooks: list[HookProvider] | None = None, session_manager: SessionManager | None = None, structured_output_prompt: str | None = None, tool_executor: ToolExecutor | None = None, retry_strategy: ModelRetryStrategy | _DefaultRetryStrategySentinel | None = _DEFAULT_RETRY_STRATEGY)Defined in: src/strands/agent/agent.py:110
Initialize the Agent with the specified configuration.
Arguments:
-
model- Provider for running inference or a string representing the model-id for Bedrock to use. Defaults to strands.models.BedrockModel if None. -
messages- List of initial messages to pre-load into the conversation. Defaults to an empty list if None. -
tools- List of tools to make available to the agent. Can be specified as:- String tool names (e.g., “retrieve”)
- File paths (e.g., “/path/to/tool.py”)
- Imported Python modules (e.g., from strands_tools import current_time)
- Dictionaries with name/path keys (e.g., {“name”: “tool_name”, “path”: “/path/to/tool.py”})
- ToolProvider instances for managed tool collections
- Functions decorated with
@strands.tooldecorator.
If provided, only these tools will be available. If None, all tools will be available.
-
system_prompt- System prompt to guide model behavior. Can be a string or a list of SystemContentBlock objects for advanced features like caching. If None, the model will behave according to its default settings. -
structured_output_model- Pydantic model type(s) for structured output. When specified, all agent calls will attempt to return structured output of this type. This can be overridden on the agent invocation. Defaults to None (no structured output). -
callback_handler- Callback for processing events as they happen during agent execution. If not provided (using the default), a new PrintingCallbackHandler instance is created. If explicitly set to None, null_callback_handler is used. -
conversation_manager- Manager for conversation history and context window. Defaults to strands.agent.conversation_manager.SlidingWindowConversationManager if None. -
record_direct_tool_call- Whether to record direct tool calls in message history. Defaults to True. -
load_tools_from_directory- Whether to load and automatically reload tools in the./tools/directory. Defaults to False. -
trace_attributes- Custom trace attributes to apply to the agent’s trace span. -
agent_id- Optional ID for the agent, useful for session management and multi-agent scenarios. Defaults to “default”. -
name- name of the Agent Defaults to “Strands Agents”. -
description- description of what the Agent does Defaults to None. -
state- stateful information for the agent. Can be either an AgentState object, or a json serializable dict. Defaults to an empty AgentState object. -
hooks- hooks to be added to the agent hook registry Defaults to None. -
session_manager- Manager for handling agent sessions including conversation history and state. If provided, enables session-based persistence and state management. -
structured_output_prompt- Custom prompt message used when forcing structured output. When using structured output, if the model doesn’t automatically use the output tool, the agent sends a follow-up message to request structured formatting. This parameter allows customizing that message. Defaults to “You must format the previous response as structured output.” -
tool_executor- Definition of tool execution strategy (e.g., sequential, concurrent, etc.). -
retry_strategy- Strategy for retrying model calls on throttling or other transient errors. Defaults to ModelRetryStrategy with max_attempts=6, initial_delay=4s, max_delay=240s. Implement a custom HookProvider for custom retry logic, or pass None to disable retries.
Raises:
ValueError- If agent id contains path separators.
system_prompt
@propertydef system_prompt() -> str | NoneDefined in: src/strands/agent/agent.py:308
Get the system prompt as a string for backwards compatibility.
Returns the system prompt as a concatenated string when it contains text content, or None if no text content is present. This maintains backwards compatibility with existing code that expects system_prompt to be a string.
Returns:
The system prompt as a string, or None if no text content exists.
system_prompt
@system_prompt.setterdef system_prompt(value: str | list[SystemContentBlock] | None) -> NoneDefined in: src/strands/agent/agent.py:321
Set the system prompt and update internal content representation.
Accepts either a string or list of SystemContentBlock objects. When set, both the backwards-compatible string representation and the internal content block representation are updated to maintain consistency.
Arguments:
value- System prompt as string, list of SystemContentBlock objects, or None.- str: Simple text prompt (most common use case)
- list[SystemContentBlock]: Content blocks with features like caching
- None: Clear the system prompt
tool
@propertydef tool() -> _ToolCallerDefined in: src/strands/agent/agent.py:337
Call tool as a function.
Returns:
Tool caller through which user can invoke tool as a function.
Example:
agent = Agent(tools=[calculator])agent.tool.calculator(...)tool_names
@propertydef tool_names() -> list[str]Defined in: src/strands/agent/agent.py:352
Get a list of all registered tool names.
Returns:
Names of all tools available to this agent.
__call__
def __call__(prompt: AgentInput = None, *, invocation_state: dict[str, Any] | None = None, structured_output_model: type[BaseModel] | None = None, structured_output_prompt: str | None = None, **kwargs: Any) -> AgentResultDefined in: src/strands/agent/agent.py:361
Process a natural language prompt through the agent’s event loop.
This method implements the conversational interface with multiple input patterns:
- String input:
agent("hello!") - ContentBlock list:
agent([\{"text": "hello"}, \{"image": \{...}}]) - Message list:
agent([\{"role": "user", "content": [\{"text": "hello"}]}]) - No input:
agent()- uses existing conversation history
Arguments:
prompt- User input in various formats:- str: Simple text input
- list[ContentBlock]: Multi-modal content blocks
- list[Message]: Complete messages with roles
- None: Use existing conversation history
invocation_state- Additional parameters to pass through the event loop.structured_output_model- Pydantic model type(s) for structured output (overrides agent default).structured_output_prompt- Custom prompt for forcing structured output (overrides agent default).**kwargs- Additional parameters to pass through the event loop.[Deprecating]
Returns:
Result object containing:
- stop_reason: Why the event loop stopped (e.g., “end_turn”, “max_tokens”)
- message: The final message from the model
- metrics: Performance metrics from the event loop
- state: The final state of the event loop
- structured_output: Parsed structured output when structured_output_model was specified
invoke_async
async def invoke_async(prompt: AgentInput = None, *, invocation_state: dict[str, Any] | None = None, structured_output_model: type[BaseModel] | None = None, structured_output_prompt: str | None = None, **kwargs: Any) -> AgentResultDefined in: src/strands/agent/agent.py:408
Process a natural language prompt through the agent’s event loop.
This method implements the conversational interface with multiple input patterns:
- String input: Simple text input
- ContentBlock list: Multi-modal content blocks
- Message list: Complete messages with roles
- No input: Use existing conversation history
Arguments:
prompt- User input in various formats:- str: Simple text input
- list[ContentBlock]: Multi-modal content blocks
- list[Message]: Complete messages with roles
- None: Use existing conversation history
invocation_state- Additional parameters to pass through the event loop.structured_output_model- Pydantic model type(s) for structured output (overrides agent default).structured_output_prompt- Custom prompt for forcing structured output (overrides agent default).**kwargs- Additional parameters to pass through the event loop.[Deprecating]
Returns:
-
Result- object containing:- stop_reason: Why the event loop stopped (e.g., “end_turn”, “max_tokens”)
- message: The final message from the model
- metrics: Performance metrics from the event loop
- state: The final state of the event loop
structured_output
def structured_output(output_model: type[T], prompt: AgentInput = None) -> TDefined in: src/strands/agent/agent.py:456
This method allows you to get structured output from the agent.
If you pass in a prompt, it will be used temporarily without adding it to the conversation history. If you don’t pass in a prompt, it will use only the existing conversation history to respond.
For smaller models, you may want to use the optional prompt to add additional instructions to explicitly instruct the model to output the structured data.
Arguments:
output_model- The output model (a JSON schema written as a Pydantic BaseModel) that the agent will use when responding.prompt- The prompt to use for the agent in various formats:- str: Simple text input
- list[ContentBlock]: Multi-modal content blocks
- list[Message]: Complete messages with roles
- None: Use existing conversation history
Raises:
ValueError- If no conversation history or prompt is provided.
structured_output_async
async def structured_output_async(output_model: type[T], prompt: AgentInput = None) -> TDefined in: src/strands/agent/agent.py:487
This method allows you to get structured output from the agent.
If you pass in a prompt, it will be used temporarily without adding it to the conversation history. If you don’t pass in a prompt, it will use only the existing conversation history to respond.
For smaller models, you may want to use the optional prompt to add additional instructions to explicitly instruct the model to output the structured data.
Arguments:
output_model- The output model (a JSON schema written as a Pydantic BaseModel) that the agent will use when responding.prompt- The prompt to use for the agent (will not be added to conversation history).
Raises:
-
ValueError- If no conversation history or prompt is provided.
cleanup
def cleanup() -> NoneDefined in: src/strands/agent/agent.py:558
Clean up resources used by the agent.
This method cleans up all tool providers that require explicit cleanup, such as MCP clients. It should be called when the agent is no longer needed to ensure proper resource cleanup.
Note: This method uses a “belt and braces” approach with automatic cleanup through finalizers as a fallback, but explicit cleanup is recommended.
__del__
def __del__() -> NoneDefined in: src/strands/agent/agent.py:570
Clean up resources when agent is garbage collected.
stream_async
async def stream_async(prompt: AgentInput = None, *, invocation_state: dict[str, Any] | None = None, structured_output_model: type[BaseModel] | None = None, structured_output_prompt: str | None = None, **kwargs: Any) -> AsyncIterator[Any]Defined in: src/strands/agent/agent.py:577
Process a natural language prompt and yield events as an async iterator.
This method provides an asynchronous interface for streaming agent events with multiple input patterns:
- String input: Simple text input
- ContentBlock list: Multi-modal content blocks
- Message list: Complete messages with roles
- No input: Use existing conversation history
Arguments:
prompt- User input in various formats:- str: Simple text input
- list[ContentBlock]: Multi-modal content blocks
- list[Message]: Complete messages with roles
- None: Use existing conversation history
invocation_state- Additional parameters to pass through the event loop.structured_output_model- Pydantic model type(s) for structured output (overrides agent default).structured_output_prompt- Custom prompt for forcing structured output (overrides agent default).**kwargs- Additional parameters to pass to the event loop.[Deprecating]
Yields:
An async iterator that yields events. Each event is a dictionary containing information about the current state of processing, such as:
- data: Text content being generated
- complete: Whether this is the final chunk
- current_tool_use: Information about tools being executed
- And other event data provided by the callback handler
Raises:
ConcurrencyException- If another invocation is already in progress on this agent instance.Exception- Any exceptions from the agent invocation will be propagated to the caller.
Example:
async for event in agent.stream_async("Analyze this data"): if "data" in event: yield event["data"]