Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/user-guide/concepts/agents/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,44 @@ Some events come in pairs, such as Before/After events. The After event callback

## Advanced Usage

### Accessing Invocation State in Hooks

Hook events that involve tool execution include access to `invocation_state`, which provides configuration and context data passed through the agent invocation. This is particularly useful for:

1. **Configuration and Credentials**: Access API keys, database configurations, or other settings without hardcoding them
2. **Request Context**: Access session IDs, user information, or request-specific data
3. **Multi-Agent Shared State**: In [Graph](../multi-agent/graph.md) and [Swarm](../multi-agent/swarm.md) patterns, access state shared across all agents
4. **Custom Parameters**: Pass any additional data that hooks might need

```python
from strands.experimental.hooks import BeforeToolInvocationEvent
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has been updated, lets point to the main location

Suggested change
from strands.experimental.hooks import BeforeToolInvocationEvent
from strands.hooks import BeforeToolCallEvent


def log_with_context(event: BeforeToolInvocationEvent) -> None:
"""Log tool invocations with context from invocation state."""
# Access invocation state from the event
user_id = event.invocation_state.get("user_id", "unknown")
session_id = event.invocation_state.get("session_id")
environment = event.invocation_state.get("environment", "production")

# Log with context
logger.info(
f"User {user_id} in session {session_id} ({environment}) "
f"invoking tool: {event.tool_use['name']}"
)

# Register the hook
agent = Agent(tools=[my_tool])
agent.hooks.add_callback(BeforeToolInvocationEvent, log_with_context)

# Execute with context in invocation state
result = agent(
"Process the data",
user_id="user123",
session_id="sess456",
environment="staging"
Comment on lines +165 to +167
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Can we give an example where we are passing a non-json serializable object through invocation state? Right now, its not really clear what its benefit is over AgentState

)
```

### Fixed Tool Arguments

Enforce specific arguments for tools, ensuring they always use particular values regardless of what the agent specifies:
Expand Down
32 changes: 32 additions & 0 deletions docs/user-guide/concepts/multi-agent/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,38 @@ From [another_node_id]:
- [Agent name]: [Result text]
```

## Shared State

Graphs support passing shared state to all agents through the `invocation_state` parameter. This enables sharing configuration, credentials, and other data across agents without exposing it to the LLM.

```python
# Execute graph with shared state
result = graph(
"Analyze customer data",
invocation_state={
"api_key": "secret-key-123",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we remove references to api keys/tool-configs from invocation_state usages?

The python-tools section update is good, but the examples throughout the other pages should be updated as well

"database_config": {"host": "db.example.com", "port": 5432},
"session_id": "user-session-456"
}
)
```

The `invocation_state` is automatically propagated to:

- All agents in the graph via their `**kwargs`
- Tools via `ToolContext` when using `@tool(context=True)` - see [Python Tools](../tools/python-tools.md#accessing-invocation-state-in-tools)
- Tool-related hooks (BeforeToolInvocationEvent, AfterToolInvocationEvent) - see [Hooks](../agents/hooks.md#accessing-invocation-state-in-hooks)

```python
# Tools access shared state through ToolContext
@tool(context=True)
def api_call(endpoint: str, tool_context: ToolContext) -> str:
api_key = tool_context.invocation_state.get("api_key")
# Use api_key for authenticated requests...
```

Use `invocation_state` for configuration and credentials that shouldn't appear in prompts, while using normal Graph input propagation for data the LLM should reason about.

## Graphs as a Tool

Agents can dynamically create and orchestrate graphs by using the `graph` tool available in the [Strands tools package](../tools/community-tools-package.md).
Expand Down
36 changes: 36 additions & 0 deletions docs/user-guide/concepts/multi-agent/swarm.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,42 @@ Agent name: security_specialist. Agent description: Focuses on secure coding pra
You have access to swarm coordination tools if you need help from other agents.
```

## Shared State

Swarms support passing shared state to all agents through the `invocation_state` parameter. This enables sharing configuration and credentials across agents without exposing them to the LLM, keeping them separate from the shared context used for collaboration.

```python
# Execute swarm with shared state
result = swarm(
"Research and analyze the data",
invocation_state={
"api_key": "bearer-token-xyz",
"api_base_url": "https://api.example.com",
"cache_enabled": True
}
)
```

The `invocation_state` is automatically propagated to:

- All agents in the swarm via their `**kwargs`
- Tools via `ToolContext` when using `@tool(context=True)` - see [Python Tools](../tools/python-tools.md#accessing-invocation-state-in-tools)
- Tool-related hooks (BeforeToolInvocationEvent, AfterToolInvocationEvent) - see [Hooks](../agents/hooks.md#accessing-invocation-state-in-hooks)

```python
# Tools access shared state through ToolContext
@tool(context=True)
def fetch_data(source: str, tool_context: ToolContext) -> dict:
api_key = tool_context.invocation_state.get("api_key")
base_url = tool_context.invocation_state.get("api_base_url")
# Use configuration for API calls...
```

**Important distinction:**

- **Shared Context**: Information agents share through handoffs, visible in prompts for collaboration
- **Shared State**: Hidden configuration passed via `invocation_state`, not visible in prompts

## Asynchronous Execution

You can also execute a Swarm asynchronously by calling the [`invoke_async`](../../../api-reference/multiagent.md#strands.multiagent.swarm.Swarm.invoke_async) function:
Expand Down
44 changes: 44 additions & 0 deletions docs/user-guide/concepts/tools/python-tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,50 @@ agent("What is the tool use id?")
agent("What is the invocation state?", custom_data="You're the best agent ;)")
```

#### Accessing Invocation State in Tools

The `invocation_state` attribute in `ToolContext` provides access to data passed through the agent invocation. This is particularly useful for:

1. **Request Context**: Access session IDs, user information, or request-specific data
2. **Multi-Agent Shared State**: In [Graph](../multi-agent/graph.md) and [Swarm](../multi-agent/swarm.md) patterns, access state shared across all agents
3. **Per-Invocation Overrides**: Override behavior or settings for specific requests

```python
from strands import tool, Agent, ToolContext
import requests

@tool(context=True)
def api_call(query: str, tool_context: ToolContext) -> dict:
"""Make an API call with user context.

Args:
query: The search query to send to the API
tool_context: Context containing user information
"""
user_id = tool_context.invocation_state.get("user_id")

response = requests.get(
"https://api.example.com/search",
headers={"X-User-ID": user_id},
params={"q": query}
)

return response.json()

agent = Agent(tools=[api_call])
result = agent("Get my profile data", user_id="user123")
```

##### Invocation State Compared To Other Approaches

It's important to understand how invocation state compares to other approaches that impact tool execution:

- **Tool Parameters**: Use for data that the LLM should reason about and provide based on the user's request. Examples include search queries, file paths, calculation inputs, or any data the agent needs to determine from context.

- **Invocation State**: Use for context and configuration that should not appear in prompts but affects tool behavior. Best suited for parameters that can change between agent invocations. Examples include user IDs for personalization, session IDs, or user flags.

- **[Class-based tools](#class-based-tools)**: Use for configuration that doesn't change between requests and requires initialization. Examples include API keys, database connection strings, service endpoints, or shared resources that need setup.

### Tool Streaming

Async tools can yield intermediate results to provide real-time progress updates. Each yielded value becomes a [streaming event](../streaming/overview.md), with the final value serving as the tool's return result:
Expand Down