Skip to content

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:

  1. Natural language for conversation: agent("Analyze this data")
  2. Method-style for direct tool access: agent.tool.tool_name(param1="value")
class Agent(AgentBase)

Defined in: src/strands/agent/agent.py:98

Core Agent implementation.

An agent orchestrates the following workflow:

  1. Receives user input
  2. Processes the input using a language model
  3. Decides whether to use tools to gather information or perform actions
  4. Executes those tools and receives results
  5. Continues reasoning with the new information
  6. Produces a final response
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,
plugins: list[Plugin] | 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,
concurrent_invocation_mode:
ConcurrentInvocationMode = ConcurrentInvocationMode.THROW)

Defined in: src/strands/agent/agent.py:114

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.tool decorator.

    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.

  • plugins - List of Plugin instances to extend agent functionality. Plugins are initialized with the agent instance after construction and can register hooks, modify agent attributes, or perform other setup tasks. Defaults to None.

  • 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.

  • concurrent_invocation_mode - Mode controlling concurrent invocation behavior. Defaults to “throw” which raises ConcurrencyException if concurrent invocation is attempted. Set to “unsafe_reentrant” to skip lock acquisition entirely, allowing concurrent invocations.

  • Warning - “unsafe_reentrant” makes no guarantees about resulting behavior and is provided only for advanced use cases where the caller understands the risks.

Raises:

  • ValueError - If agent id contains path separators.
@property
def system_prompt() -> str | None

Defined in: src/strands/agent/agent.py:331

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.setter
def system_prompt(value: str | list[SystemContentBlock] | None) -> None

Defined in: src/strands/agent/agent.py:344

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
@property
def tool() -> _ToolCaller

Defined in: src/strands/agent/agent.py:360

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(...)
@property
def tool_names() -> list[str]

Defined in: src/strands/agent/agent.py:375

Get a list of all registered tool names.

Returns:

Names of all tools available to this agent.

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) -> AgentResult

Defined in: src/strands/agent/agent.py:384

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
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) -> AgentResult

Defined in: src/strands/agent/agent.py:431

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
def structured_output(output_model: type[T], prompt: AgentInput = None) -> T

Defined in: src/strands/agent/agent.py:479

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.
async def structured_output_async(output_model: type[T],
prompt: AgentInput = None) -> T

Defined in: src/strands/agent/agent.py:510

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:

def cleanup() -> None

Defined in: src/strands/agent/agent.py:581

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.

def add_hook(
callback: HookCallback[TEvent],
event_type: type[TEvent] | list[type[TEvent]] | None = None) -> None

Defined in: src/strands/agent/agent.py:593

Register a callback function for a specific event type.

This method supports multiple call patterns:

  1. add_hook(callback) - Event type inferred from callback’s type hint
  2. add_hook(callback, event_type) - Event type specified explicitly
  3. add_hook(callback, [TypeA, TypeB]) - Register for multiple event types

When the callback’s type hint is a union type (A | B or Union[A, B]), the callback is automatically registered for each event type in the union.

Callbacks can be either synchronous or asynchronous functions.

Arguments:

  • callback - The callback function to invoke when events of this type occur.
  • event_type - The class type(s) of events this callback should handle. Can be a single type, a list of types, or None to infer from the callback’s first parameter type hint. If a list is provided, the callback is registered for each type in the list.

Raises:

  • ValueError - If event_type is not provided and cannot be inferred from the callback’s type hints, or if the event_type list is empty.

Example:

def log_model_call(event: BeforeModelCallEvent) -> None:
print(f"Calling model for agent: \{event.agent.name}")
agent = Agent()
# With event type inferred from type hint
agent.add_hook(log_model_call)
# With explicit event type
agent.add_hook(log_model_call, BeforeModelCallEvent)
# With union type hint (registers for all types)
def log_event(event: BeforeModelCallEvent | AfterModelCallEvent) -> None:
print(f"Event: \{type(event).__name__}")
agent.add_hook(log_event)
# With list of event types
def multi_handler(event) -> None:
print(f"Event: \{type(event).__name__}")
agent.add_hook(multi_handler, [BeforeModelCallEvent, AfterModelCallEvent])

Docs: https://strandsagents.com/latest/documentation/docs/user-guide/concepts/agents/hooks/

def __del__() -> None

Defined in: src/strands/agent/agent.py:647

Clean up resources when agent is garbage collected.

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:654

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"]