Skip to content

Commit e370e41

Browse files
Unshurezastrowm
andauthored
Add Agent State to docs (#112)
* Add Agent State to docs * Update docs/user-guide/concepts/agents/state-sessions.md Co-authored-by: Mackenzie Zastrow <3211021+zastrowm@users.noreply.github.com> * Update docs/user-guide/concepts/agents/state-sessions.md Co-authored-by: Mackenzie Zastrow <3211021+zastrowm@users.noreply.github.com> --------- Co-authored-by: Mackenzie Zastrow <3211021+zastrowm@users.noreply.github.com>
1 parent 2071f04 commit e370e41

File tree

6 files changed

+114
-62
lines changed

6 files changed

+114
-62
lines changed

docs/user-guide/concepts/agents/agent-loop.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ Messages flow through the agent loop in a structured format:
6969
2. **Assistant messages**: Responses from the model that may include tool requests
7070
3. **Tool result messages**: Results from tool executions fed back to the model
7171

72-
The SDK automatically formats these messages into the appropriate structure for model inputs and [session state](sessions-state.md).
72+
The SDK automatically formats these messages into the appropriate structure for model inputs and [session state](state-sessions.md).
7373

7474
### Tool Execution
7575

docs/user-guide/concepts/agents/prompts.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ For programmatic control, you can call tools directly:
4040
result = agent.tool.current_time(timezone="US/Pacific")
4141
```
4242

43-
This bypasses the natural language interface and directly executes the tool with the specified parameters. By default, direct tool calls are added to the [session state](sessions-state.md) but can be optionally not included by specifying `record_direct_tool_call=False`.
43+
This bypasses the natural language interface and directly executes the tool with the specified parameters. By default, direct tool calls are added to the [session state](state-sessions.md) but can be optionally not included by specifying `record_direct_tool_call=False`.
4444

4545
## Prompt Engineering
4646

docs/user-guide/concepts/agents/sessions-state.md renamed to docs/user-guide/concepts/agents/state-sessions.md

Lines changed: 109 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1-
# Sessions & State
1+
# State & Sessions
22

3-
This document explains how Strands agents maintain conversation context, handle state management, and support persistent sessions across interactions.
3+
## State Management
44

5-
Strands agents maintain state in several forms:
5+
Strands Agents state is maintained in several forms:
66

7-
1. **Conversation History**: The sequence of messages between the user and the agent
8-
2. **Tool State**: Information about tool executions and results
9-
3. **Request State**: Contextual information maintained within a single request
7+
1. **Conversation History:** The sequence of messages between the user and the agent.
8+
2. **Agent State**: Stateful information outside of conversation context, maintained across multiple requests.
9+
3. **Request State**: Contextual information maintained within a single request.
1010

1111
Understanding how state works in Strands is essential for building agents that can maintain context across multi-turn interactions and workflows.
1212

13-
## Conversation History
13+
### Conversation History
1414

15-
The primary form of state in a Strands agent is the conversation history, directly accessible through the `agent.messages` property:
15+
Conversation history is the primary form of context in a Strands agent, directly accessible through the `agent.messages` property:
1616

1717
```python
1818
from strands import Agent
@@ -51,7 +51,30 @@ Conversation history is automatically:
5151
- Used for tool execution context
5252
- Managed to prevent context window overflow
5353

54-
## Conversation Manager
54+
#### Direct Tool Calling
55+
56+
Direct tool calls are (by default) recorded in the conversation history:
57+
58+
```python
59+
from strands import Agent
60+
from strands_tools import calculator
61+
62+
agent = Agent(tools=[calculator])
63+
64+
# Direct tool call with recording (default behavior)
65+
agent.tool.calculator(expression="123 * 456")
66+
67+
# Direct tool call without recording
68+
agent.tool.calculator(expression="765 / 987", record_direct_tool_call=False)
69+
70+
print(agent.messages)
71+
```
72+
73+
In this example we can see that the first `agent.tool.calculator()` call is recorded in the agent's conversation history.
74+
75+
The second `agent.tool.calculator()` call is **not** recorded in the history because we specified the `record_direct_tool_call=False` argument.
76+
77+
#### Conversation Manager
5578

5679
Strands uses a conversation manager to handle conversation history effectively. The default is the [`SlidingWindowConversationManager`](../../../api-reference/agent.md#strands.agent.conversation_manager.sliding_window_conversation_manager.SlidingWindowConversationManager), which keeps recent messages and removes older ones when needed:
5780

@@ -76,52 +99,101 @@ The sliding window conversation manager:
7699
- Handles context window overflow exceptions by reducing context
77100
- Ensures conversations don't exceed model context limits
78101

79-
## Tool State
102+
See [`Context Management`](context-management.md) for more information about conversation managers.
80103

81-
When an agent uses tools, the tool executions and results become part of the conversation state:
104+
105+
### Agent State
106+
107+
Agent state provides key-value storage for stateful information that exists outside of the conversation context. Unlike conversation history, agent state is not passed to the model during inference but can be accessed and modified by tools and application logic.
108+
109+
#### Basic Usage
82110

83111
```python
84112
from strands import Agent
85-
from strands_tools import calculator
86113

87-
agent = Agent(tools=[calculator])
114+
# Create an agent with initial state
115+
agent = Agent(state={"user_preferences": {"theme": "dark"}, "session_count": 0})
88116

89-
# Tool use is recorded in the conversation history
90-
agent("What is 123 × 456?") # Uses calculator tool and records result
91117

92-
# You can examine the tool interactions in the conversation history
93-
print(agent.messages) # Shows tool calls and results
94-
```
118+
# Access state values
119+
theme = agent.state.get("user_preferences")
120+
print(theme) # {"theme": "dark"}
95121

96-
Tool state includes:
122+
# Set new state values
123+
agent.state.set("last_action", "login")
124+
agent.state.set("session_count", 1)
97125

98-
- Tool use requests from the model
99-
- Tool execution parameters
100-
- Tool execution results
101-
- Any errors or exceptions that occurred
126+
# Get entire state
127+
all_state = agent.state.get()
128+
print(all_state) # All state data as a dictionary
102129

103-
Direct tool calls can also be recorded in the conversation history:
130+
# Delete state values
131+
agent.state.delete("last_action")
132+
```
133+
134+
#### State Validation and Safety
135+
136+
Agent state enforces JSON serialization validation to ensure data can be persisted and restored:
104137

105138
```python
106139
from strands import Agent
107-
from strands_tools import calculator
108140

109-
agent = Agent(tools=[calculator])
141+
agent = Agent()
110142

111-
# Direct tool call with recording (default behavior)
112-
agent.tool.calculator(expression="123 * 456")
143+
# Valid JSON-serializable values
144+
agent.state.set("string_value", "hello")
145+
agent.state.set("number_value", 42)
146+
agent.state.set("boolean_value", True)
147+
agent.state.set("list_value", [1, 2, 3])
148+
agent.state.set("dict_value", {"nested": "data"})
149+
agent.state.set("null_value", None)
150+
151+
# Invalid values will raise ValueError
152+
try:
153+
agent.state.set("function", lambda x: x) # Not JSON serializable
154+
except ValueError as e:
155+
print(f"Error: {e}")
156+
```
113157

114-
# Direct tool call without recording
115-
agent.tool.calculator(expression="765 / 987", record_direct_tool_call=False)
158+
#### Using State in Tools
116159

117-
print(agent.messages)
118-
```
160+
Agent state is particularly useful for maintaining information across tool executions:
119161

120-
In this example we can see that the first `agent.tool.calculator()` call is recorded in the agent's conversation history.
162+
```python
163+
from strands import Agent
164+
from strands.tools.decorator import tool
121165

122-
The second `agent.tool.calculator()` call is **not** recorded in the history because we specified the `record_direct_tool_call=False` argument.
166+
@tool
167+
def track_user_action(action: str, agent: Agent):
168+
"""Track user actions in agent state."""
169+
# Get current action count
170+
action_count = agent.state.get("action_count") or 0
171+
172+
# Update state
173+
agent.state.set("action_count", action_count + 1)
174+
agent.state.set("last_action", action)
175+
176+
return f"Action '{action}' recorded. Total actions: {action_count + 1}"
177+
178+
@tool
179+
def get_user_stats(agent: Agent):
180+
"""Get user statistics from agent state."""
181+
action_count = agent.state.get("action_count") or 0
182+
last_action = agent.state.get("last_action") or "none"
183+
184+
return f"Actions performed: {action_count}, Last action: {last_action}"
123185

124-
## Request State
186+
# Create agent with tools
187+
agent = Agent(tools=[track_user_action, get_user_stats])
188+
189+
# Use tools that modify and read state
190+
agent("Track that I logged in")
191+
agent("Track that I viewed my profile")
192+
print(f"Actions taken: {agent.state.get('action_count')}")
193+
print(f"Last action: {agent.state.get('last_action')}")
194+
```
195+
196+
### Request State
125197

126198
Each agent interaction maintains a request state dictionary that persists throughout the event loop cycles and is **not** included in the agent's context:
127199

@@ -149,12 +221,12 @@ The request state:
149221

150222
- Is initialized at the beginning of each agent call
151223
- Persists through recursive event loop cycles
152-
- Can be modified by tools and handlers
224+
- Can be modified by callback handlers
153225
- Is returned in the AgentResult object
154226

155227
## Session Management
156228

157-
For applications requiring persistent sessions across separate interactions, Strands provides several approaches:
229+
A session represents all of the stateful information that is needed by an agent to function. For applications requiring persistent sessions across separate interactions, Strands provides several approaches:
158230

159231
### 1. Object Persistence
160232

@@ -256,23 +328,3 @@ def chat():
256328
return {"response": result.message}
257329
```
258330

259-
## Custom Conversation Management
260-
261-
For specialized requirements, you can implement your own conversation manager:
262-
263-
```python
264-
from strands.agent.conversation_manager import ConversationManager
265-
from strands.types.content import Messages
266-
from typing import Optional
267-
268-
class CustomConversationManager(ConversationManager):
269-
def apply_management(self, messages: Messages) -> None:
270-
"""Apply management strategies to the messages list."""
271-
# Implement your management strategy
272-
pass
273-
274-
def reduce_context(self, messages: Messages, e: Optional[Exception] = None) -> None:
275-
"""Reduce context to handle overflow exceptions."""
276-
# Implement your reduction strategy
277-
pass
278-
```

docs/user-guide/concepts/tools/tools_overview.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ agent = Agent(load_tools_from_directory=False)
5656

5757
Tools can be invoked in two primary ways.
5858

59-
Agents have context about tool calls and their results as part of conversation history. See [sessions & state](../agents/sessions-state.md#tool-state) for more information.
59+
Agents have context about tool calls and their results as part of conversation history. See [state & sessions](../agents/state-sessions.md#using-state-in-tools) for more information.
6060

6161
### Natural Language Invocation
6262

docs/user-guide/quickstart.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,7 @@ Ready to learn more? Check out these resources:
327327
- [Example Built-in Tools](concepts/tools/example-tools-package.md) - The `strands-agents-tools` package provides many powerful example tools for your agents to use during development
328328
- [Strands Agent Builder]({{ agent_builder_repo_home }}) - Use the accompanying `strands-agents-builder` agent builder to harness the power of LLMs to generate your own tools and agents
329329
- [Agent Loop](concepts/agents/agent-loop.md) - Learn how Strands agents work under the hood
330-
- [Sessions & State](concepts/agents/sessions-state.md) - Understand how agents maintain context and state across a conversation or workflow
330+
- [State & Sessions](concepts/agents/state-sessions.md) - Understand how agents maintain context and state across a conversation or workflow
331331
- [Multi-agent](concepts/multi-agent/agents-as-tools.md) - Orchestrate multiple agents together as one system, with each agent completing specialized tasks
332332
- [Observability & Evaluation](observability-evaluation/observability.md) - Understand how agents make decisions and improve them with data
333333
- [Operating Agents in Production](deploy/operating-agents-in-production.md) - Taking agents from development to production, operating them responsibly at scale

mkdocs.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ nav:
7272
- Concepts:
7373
- Agents:
7474
- Agent Loop: user-guide/concepts/agents/agent-loop.md
75-
- Sessions & State: user-guide/concepts/agents/sessions-state.md
75+
- State & Sessions: user-guide/concepts/agents/state-sessions.md
7676
- Prompts: user-guide/concepts/agents/prompts.md
7777
- Structured Output: user-guide/concepts/agents/structured-output.md
7878
- Context Management: user-guide/concepts/agents/context-management.md

0 commit comments

Comments
 (0)