From 01cc79b9ebb4767bc7068d5bae1d7ab3deb2276c Mon Sep 17 00:00:00 2001 From: martimfasantos Date: Sun, 11 Oct 2026 22:11:41 +0100 Subject: [PATCH 1/4] feat(strands-agents-sdk): upgrade to v1.59.0, fix context compression example and docs links, and add subagent tool example --- README.md | 2 +- strands-agents-sdk/00_hello_world.py | 2 +- strands-agents-sdk/01_custom_tools.py | 2 +- strands-agents-sdk/02_structured_output.py | 2 +- .../03_system_prompt_and_conversation.py | 2 +- strands-agents-sdk/04_model_providers.py | 2 +- strands-agents-sdk/05_agents_as_tools.py | 2 +- .../06_streaming_and_callbacks.py | 2 +- .../07_metrics_and_observability.py | 2 +- strands-agents-sdk/08_class_based_tools.py | 2 +- strands-agents-sdk/09_hooks.py | 2 +- .../10_conversation_management.py | 2 +- strands-agents-sdk/11_multi_agent_swarm.py | 2 +- strands-agents-sdk/12_multi_agent_graph.py | 2 +- strands-agents-sdk/13_multi_agent_workflow.py | 2 +- strands-agents-sdk/14_a2a_agent.py | 2 +- strands-agents-sdk/15_mcp_tools.py | 2 +- strands-agents-sdk/16_skills_plugin.py | 2 +- strands-agents-sdk/17_session_persistence.py | 2 +- strands-agents-sdk/18_context_compression.py | 74 +++++++--- strands-agents-sdk/19_interventions.py | 2 +- strands-agents-sdk/20_human_in_the_loop.py | 2 +- strands-agents-sdk/21_agent_memory.py | 2 +- strands-agents-sdk/22_invocation_limits.py | 2 +- strands-agents-sdk/23_goal_loop.py | 2 +- strands-agents-sdk/24_cancellation.py | 2 +- strands-agents-sdk/25_background_tasks.py | 2 +- strands-agents-sdk/26_subagent_tool.py | 130 ++++++++++++++++++ strands-agents-sdk/OUTPUTS.md | 57 ++++++-- strands-agents-sdk/README.md | 10 +- strands-agents-sdk/pyproject.toml | 4 +- strands-agents-sdk/settings.py | 1 + strands-agents-sdk/uv.lock | 16 +-- 33 files changed, 270 insertions(+), 74 deletions(-) create mode 100644 strands-agents-sdk/26_subagent_tool.py diff --git a/README.md b/README.md index ef7ea57..bedc086 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ This repository provides a comprehensive, hands-on comparison of modern AI agent Strands Agents SDK - 1.55.1 + 1.59.0 diff --git a/strands-agents-sdk/00_hello_world.py b/strands-agents-sdk/00_hello_world.py index d2d226b..aab9cb4 100644 --- a/strands-agents-sdk/00_hello_world.py +++ b/strands-agents-sdk/00_hello_world.py @@ -16,7 +16,7 @@ alternative provider configured via settings. For more details, visit: -https://strandsagents.com/docs/user-guide/quickstart/python/ +https://strandsagents.com/docs/user-guide/sdk/quickstart/python/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/01_custom_tools.py b/strands-agents-sdk/01_custom_tools.py index 4737dd6..c1fdcd0 100644 --- a/strands-agents-sdk/01_custom_tools.py +++ b/strands-agents-sdk/01_custom_tools.py @@ -15,7 +15,7 @@ so the agent can decide when and how to invoke each tool. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/tools/custom-tools/ +https://strandsagents.com/docs/user-guide/sdk/tools/custom-tools/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/02_structured_output.py b/strands-agents-sdk/02_structured_output.py index 4f01999..cddaee3 100644 --- a/strands-agents-sdk/02_structured_output.py +++ b/strands-agents-sdk/02_structured_output.py @@ -17,7 +17,7 @@ result through result.structured_output. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/structured-output/ +https://strandsagents.com/docs/user-guide/sdk/agents/structured-output/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/03_system_prompt_and_conversation.py b/strands-agents-sdk/03_system_prompt_and_conversation.py index 9cfa8d5..6d582f3 100644 --- a/strands-agents-sdk/03_system_prompt_and_conversation.py +++ b/strands-agents-sdk/03_system_prompt_and_conversation.py @@ -15,7 +15,7 @@ let you define the agent's personality, constraints, and response style. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/prompts/ +https://strandsagents.com/docs/user-guide/sdk/agents/prompts/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/04_model_providers.py b/strands-agents-sdk/04_model_providers.py index 993f1c7..9576ed3 100644 --- a/strands-agents-sdk/04_model_providers.py +++ b/strands-agents-sdk/04_model_providers.py @@ -17,7 +17,7 @@ more by passing a model object to the Agent constructor. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/model-providers/ +https://strandsagents.com/docs/user-guide/sdk/model-providers/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/05_agents_as_tools.py b/strands-agents-sdk/05_agents_as_tools.py index 6a6fe24..de5999e 100644 --- a/strands-agents-sdk/05_agents_as_tools.py +++ b/strands-agents-sdk/05_agents_as_tools.py @@ -16,7 +16,7 @@ description, and context behaviour (e.g. preserve_context=True). For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/multi-agent/agents-as-tools/ +https://strandsagents.com/docs/user-guide/sdk/multi-agent/agents-as-tools/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/06_streaming_and_callbacks.py b/strands-agents-sdk/06_streaming_and_callbacks.py index ce2f859..51f4623 100644 --- a/strands-agents-sdk/06_streaming_and_callbacks.py +++ b/strands-agents-sdk/06_streaming_and_callbacks.py @@ -17,7 +17,7 @@ use async iterators for fine-grained control over the event stream. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/streaming/ +https://strandsagents.com/docs/user-guide/sdk/streaming/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/07_metrics_and_observability.py b/strands-agents-sdk/07_metrics_and_observability.py index 185afb0..31eba58 100644 --- a/strands-agents-sdk/07_metrics_and_observability.py +++ b/strands-agents-sdk/07_metrics_and_observability.py @@ -18,7 +18,7 @@ slow runs, and understanding how the agent uses its tools. For more details, visit: -https://strandsagents.com/docs/user-guide/observability-evaluation/observability/ +https://strandsagents.com/docs/user-guide/sdk/observability-evaluation/observability/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/08_class_based_tools.py b/strands-agents-sdk/08_class_based_tools.py index 8950f50..3ea3b99 100644 --- a/strands-agents-sdk/08_class_based_tools.py +++ b/strands-agents-sdk/08_class_based_tools.py @@ -15,7 +15,7 @@ manage connections, or accumulate results over the course of a conversation. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/tools/custom-tools/#class-based-tools +https://strandsagents.com/docs/user-guide/sdk/tools/custom-tools/#class-based-tools ------------------------------------------------------- """ diff --git a/strands-agents-sdk/09_hooks.py b/strands-agents-sdk/09_hooks.py index 5fb215c..81b7db7 100644 --- a/strands-agents-sdk/09_hooks.py +++ b/strands-agents-sdk/09_hooks.py @@ -26,7 +26,7 @@ guardrails specifically, see the intervention API in 19_interventions.py. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/hooks/ +https://strandsagents.com/docs/user-guide/sdk/agents/hooks/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/10_conversation_management.py b/strands-agents-sdk/10_conversation_management.py index 9453436..2c2c8a8 100644 --- a/strands-agents-sdk/10_conversation_management.py +++ b/strands-agents-sdk/10_conversation_management.py @@ -24,7 +24,7 @@ reference data in context no matter how long the conversation gets. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/conversation-management/ +https://strandsagents.com/docs/user-guide/sdk/agents/conversation-management/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/11_multi_agent_swarm.py b/strands-agents-sdk/11_multi_agent_swarm.py index 6b023c9..c621463 100644 --- a/strands-agents-sdk/11_multi_agent_swarm.py +++ b/strands-agents-sdk/11_multi_agent_swarm.py @@ -17,7 +17,7 @@ The swarm manages the handoff protocol, max iterations, and execution tracking. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/multi-agent/swarm/ +https://strandsagents.com/docs/user-guide/sdk/multi-agent/swarm/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/12_multi_agent_graph.py b/strands-agents-sdk/12_multi_agent_graph.py index 1877e13..69af07a 100644 --- a/strands-agents-sdk/12_multi_agent_graph.py +++ b/strands-agents-sdk/12_multi_agent_graph.py @@ -18,7 +18,7 @@ multi-agent pipelines. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/multi-agent/graph/ +https://strandsagents.com/docs/user-guide/sdk/multi-agent/graph/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/13_multi_agent_workflow.py b/strands-agents-sdk/13_multi_agent_workflow.py index c708f56..dca73c5 100644 --- a/strands-agents-sdk/13_multi_agent_workflow.py +++ b/strands-agents-sdk/13_multi_agent_workflow.py @@ -18,7 +18,7 @@ automatically. This is ideal for complex multi-step processes. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/multi-agent/workflow/ +https://strandsagents.com/docs/user-guide/sdk/multi-agent/workflow/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/14_a2a_agent.py b/strands-agents-sdk/14_a2a_agent.py index 5ca1bdf..b1fb0ab 100644 --- a/strands-agents-sdk/14_a2a_agent.py +++ b/strands-agents-sdk/14_a2a_agent.py @@ -17,7 +17,7 @@ Install A2A support with: pip install 'strands-agents[a2a]' For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/multi-agent/agent-to-agent/ +https://strandsagents.com/docs/user-guide/sdk/multi-agent/agent-to-agent/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/15_mcp_tools.py b/strands-agents-sdk/15_mcp_tools.py index 5354f82..24efaa5 100644 --- a/strands-agents-sdk/15_mcp_tools.py +++ b/strands-agents-sdk/15_mcp_tools.py @@ -16,7 +16,7 @@ manager for explicit control. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/tools/mcp-tools/ +https://strandsagents.com/docs/user-guide/sdk/tools/mcp-tools/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/16_skills_plugin.py b/strands-agents-sdk/16_skills_plugin.py index 8e16bbd..ac3610d 100644 --- a/strands-agents-sdk/16_skills_plugin.py +++ b/strands-agents-sdk/16_skills_plugin.py @@ -17,7 +17,7 @@ agent activates a skill through a tool call. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/plugins/skills/ +https://strandsagents.com/docs/user-guide/sdk/plugins/skills/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/17_session_persistence.py b/strands-agents-sdk/17_session_persistence.py index 0d6942c..32667a0 100644 --- a/strands-agents-sdk/17_session_persistence.py +++ b/strands-agents-sdk/17_session_persistence.py @@ -20,7 +20,7 @@ S3SessionManager (cloud) as built-in backends. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/session-management/ +https://strandsagents.com/docs/user-guide/sdk/agents/session-management/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/18_context_compression.py b/strands-agents-sdk/18_context_compression.py index e530707..7805ddd 100644 --- a/strands-agents-sdk/18_context_compression.py +++ b/strands-agents-sdk/18_context_compression.py @@ -1,8 +1,9 @@ import os -from strands import Agent +from strands import Agent, tool from strands.agent.conversation_manager import SummarizingConversationManager from strands.agent.conversation_manager.conversation_manager import ProactiveCompressionConfig +from strands.experimental.context_manager import STRATEGY_PRESET_NAMES, Offload from strands.handlers.callback_handler import null_callback_handler from strands.models.openai import OpenAIModel @@ -16,17 +17,19 @@ - Proactive context compression (new in v1.40.0) - SummarizingConversationManager with ProactiveCompressionConfig - Automatic conversation summarization to stay within token limits -- The context_manager="auto" / "agentic" shortcut (new in v1.43.0) -- Override precedence between context_manager and conversation_manager +- The context_manager="auto" / "agentic" built-in modes +- A custom strategy pipeline from named presets and raw Offload strategies Proactive compression monitors token usage during conversation and automatically compresses older messages when a threshold is reached, without waiting for context window overflow errors. -context_manager="auto" is the one-word shortcut for the same setup, -composing a summarizing manager with a ContextOffloader plugin. +The context_manager parameter goes further: it registers a ContextManager +that runs an ordered pipeline of summarize / truncate / drop strategies +and replaces the conversation manager entirely (a co-provided +conversation_manager is ignored with a warning). For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/conversation-management/ +https://strandsagents.com/docs/user-guide/sdk/context-management/ ------------------------------------------------------- """ @@ -89,7 +92,7 @@ print(f" (Proactive compression keeps context manageable across long conversations)") print() -# --- 5. The same setup in one word: context_manager="auto" --- +# --- 5. context_manager="auto": a strategy-driven ContextManager --- print("=== context_manager Shortcut ===") auto_agent = Agent( @@ -97,11 +100,10 @@ context_manager="auto", callback_handler=null_callback_handler, ) -print('context_manager="auto" composes, with benchmark-validated defaults:') -print(f" conversation_manager: {type(auto_agent.conversation_manager).__name__}") -print(f" summary_ratio: {auto_agent.conversation_manager.summary_ratio}") -print(f" preserve_recent_messages: {auto_agent.conversation_manager.preserve_recent_messages}") -print(f" ContextOffloader plugin tools: {auto_agent.tool_names}") +print('context_manager="auto" registers a plugin that owns all context reduction:') +print(f" context_manager: {type(auto_agent.context_manager).__name__}") +print(f" conversation_manager: {type(auto_agent.conversation_manager).__name__} (a no-op)") +print(f" tools: {auto_agent.tool_names}") print() # "agentic" hands the compression decisions to the model instead @@ -114,14 +116,46 @@ print(f" tools: {agentic_agent.tool_names}") print() -# --- 6. Override precedence: an explicit conversation_manager wins --- -override_agent = Agent( +# --- 6. A custom pipeline: named presets mixed with a raw Offload strategy --- +BUILD_LOG = "\n".join( + [f"step {i:03d} compiled module_{i:03d}.py in {10 + i % 7}ms" for i in range(1, 400)] + + ["step 400 FAILED: test_checkout.py::test_refund timed out after 30s"] +) + + +@tool +def fetch_build_log(build_id: str) -> str: + """Fetch the full CI log for a build.""" + return BUILD_LOG + + +print("=== Custom Strategy Pipeline ===") +print(f"Named presets: {list(STRATEGY_PRESET_NAMES)}") + +pipeline_agent = Agent( model=openai_model, - context_manager="auto", - conversation_manager=conversation_manager, # the hand-built manager from step 1 + tools=[fetch_build_log], + system_prompt="Answer in one short sentence.", + # Strategies run in order; each sees the output of the previous one + context_manager={ + "strategies": [ + "large_tool_offloading", # tool results over 2,500 tokens -> 1,000-token preview + "stale_tool_cleanup", + # A pinned config, unlike the preset "proactive_summarization" (whose values may change) + Offload.summarize("*").when(utilization=0.9, preserve_recent=2), + "overflow_protection", + ], + }, callback_handler=null_callback_handler, ) -print('context_manager="auto" + an explicit conversation_manager:') -print(f" preserve_recent_messages: {override_agent.conversation_manager.preserve_recent_messages}" - " (yours wins over the auto default of 10)") -print(f" tools: {override_agent.tool_names} (the offloader is still added)") +result = pipeline_agent("Fetch the log for build b-1042. Which step failed?") + +tool_result = next( + block["toolResult"] for message in pipeline_agent.messages + for block in message["content"] if "toolResult" in block +) +seen = tool_result["content"][0]["text"] +print(f" fetch_build_log returned {len(BUILD_LOG):,} chars; the model saw {len(seen):,}") +print(f" {seen.splitlines()[0]}") +print(f" original stashed for retrieve_context: {'[Stashed]' in seen}") +print(f"A: {str(result).strip()}") diff --git a/strands-agents-sdk/19_interventions.py b/strands-agents-sdk/19_interventions.py index a07e654..ee07d98 100644 --- a/strands-agents-sdk/19_interventions.py +++ b/strands-agents-sdk/19_interventions.py @@ -19,7 +19,7 @@ blocking the call, feeding guidance back to the model, or rewriting arguments. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/interventions/ +https://strandsagents.com/docs/user-guide/sdk/agents/interventions/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/20_human_in_the_loop.py b/strands-agents-sdk/20_human_in_the_loop.py index d93941f..31e95b6 100644 --- a/strands-agents-sdk/20_human_in_the_loop.py +++ b/strands-agents-sdk/20_human_in_the_loop.py @@ -20,7 +20,7 @@ instead, and passing an async callable lets you await your own approval service. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/interventions/human-in-the-loop/ +https://strandsagents.com/docs/user-guide/sdk/agents/interventions/human-in-the-loop/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/21_agent_memory.py b/strands-agents-sdk/21_agent_memory.py index d3b9330..e55e2cc 100644 --- a/strands-agents-sdk/21_agent_memory.py +++ b/strands-agents-sdk/21_agent_memory.py @@ -23,7 +23,7 @@ 17_session_persistence.py, which replays the conversation history itself. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/memory/test-memory-store/ +https://strandsagents.com/docs/user-guide/sdk/memory/test-memory-store/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/22_invocation_limits.py b/strands-agents-sdk/22_invocation_limits.py index 00990c1..e91a66f 100644 --- a/strands-agents-sdk/22_invocation_limits.py +++ b/strands-agents-sdk/22_invocation_limits.py @@ -18,7 +18,7 @@ is left in a state you can invoke again. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/agent-loop/ +https://strandsagents.com/docs/user-guide/sdk/agents/agent-loop/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/23_goal_loop.py b/strands-agents-sdk/23_goal_loop.py index 6487a94..2eca38d 100644 --- a/strands-agents-sdk/23_goal_loop.py +++ b/strands-agents-sdk/23_goal_loop.py @@ -19,7 +19,7 @@ agent's model, so no extra provider is needed. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/plugins/goal-loop/ +https://strandsagents.com/docs/user-guide/sdk/plugins/goal-loop/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/24_cancellation.py b/strands-agents-sdk/24_cancellation.py index 02e9bde..6e70f0a 100644 --- a/strands-agents-sdk/24_cancellation.py +++ b/strands-agents-sdk/24_cancellation.py @@ -24,7 +24,7 @@ signal so they stop promptly instead of running to completion. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/agent-loop/ +https://strandsagents.com/docs/user-guide/sdk/agents/agent-loop/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/25_background_tasks.py b/strands-agents-sdk/25_background_tasks.py index 64d6505..a9e6a0d 100644 --- a/strands-agents-sdk/25_background_tasks.py +++ b/strands-agents-sdk/25_background_tasks.py @@ -24,7 +24,7 @@ inline because later reasoning depends on it immediately. For more details, visit: -https://strandsagents.com/docs/user-guide/concepts/agents/agent-loop/ +https://strandsagents.com/docs/user-guide/sdk/agents/agent-loop/ ------------------------------------------------------- """ diff --git a/strands-agents-sdk/26_subagent_tool.py b/strands-agents-sdk/26_subagent_tool.py new file mode 100644 index 0000000..dfb8e2f --- /dev/null +++ b/strands-agents-sdk/26_subagent_tool.py @@ -0,0 +1,130 @@ +import os + +from strands import Agent, tool +from strands.hooks import AfterToolCallEvent, BeforeToolCallEvent +from strands.models.openai import OpenAIModel +from strands.multiagent import AgentSpec, Choice, Option, Preset +from strands.vended_tools.subagent import make_subagent + +from settings import settings + +os.environ["OPENAI_API_KEY"] = settings.OPENAI_API_KEY.get_secret_value() + +""" +------------------------------------------------------- +In this example, we explore Strands Agents with the following features: +- The vended subagent tool, configured with make_subagent() +- Presets: named child roles with their own instructions and tool subset +- A model Choice whose Option values are model instances +- A custom builder and max_depth to control how children are built and nested + +A subagent runs a self-contained task in a fresh context and returns only +its final report, so the manager's context is not flooded with the child's +intermediate tool calls. Axis policies decide what the manager may set on +each child: a preset fixes the role, a Choice exposes a closed set of +options, and anything left unset is inherited. + +For more details, visit: +https://strandsagents.com/docs/user-guide/sdk/tools/vended-tools/#subagent +------------------------------------------------------- +""" + + +def openai_model(model_id: str) -> OpenAIModel: + return OpenAIModel( + client_args={"api_key": settings.OPENAI_API_KEY.get_secret_value()}, + model_id=model_id, + ) + + +fast_model = openai_model(settings.OPENAI_MODEL_NAME) +strong_model = openai_model(settings.OPENAI_STRONG_MODEL_NAME) + +# --- 1. Mock order data, readable only by the analyst role --- +ORDERS = { + "A-1001": {"customer": "Ana", "status": "delivered", "days_late": 0}, + "A-1002": {"customer": "Bruno", "status": "in transit", "days_late": 4}, + "A-1003": {"customer": "Carla", "status": "in transit", "days_late": 0}, + "A-1004": {"customer": "Diogo", "status": "lost in transit", "days_late": 9}, +} + + +@tool +def list_orders() -> str: + """List every order with its customer, status and how many days late it is.""" + return "\n".join( + f"{order_id} ({o['customer']}): {o['status']}, {o['days_late']} days late" + for order_id, o in ORDERS.items() + ) + + +# --- 2. A builder that turns each resolved spec into a child agent --- +# The default builder grants tools from the parent's registry; this one keeps +# the order tools out of the manager's hands entirely. +CHILD_TOOLS = {"list_orders": list_orders} + + +def build_child(spec: AgentSpec) -> Agent: + model = spec.model or fast_model + tools = [CHILD_TOOLS[name] for name in spec.tools or []] + print(f" [spawn] {spec.agent_type} on {model.get_config()['model_id']}, tools={spec.tools}") + return Agent(model=model, system_prompt=spec.instructions, tools=tools, callback_handler=None) + + +# --- 3. The subagent tool: two presets and a model choice --- +subagent = make_subagent( + builder=build_child, + presets={ + "order_analyst": Preset( + instructions=( + "Answer from the order tools in one plain-text line, no markdown, e.g. " + "'A-1002 (Bruno): in transit, 4 days late'." + ), + tools=["list_orders"], + description="looks up order data; the only role with data access", + ), + "support_writer": Preset( + instructions="Write one paragraph of at most two sentences, no greeting or sign-off.", + tools=[], + description="drafts customer emails; has no data access, so put every fact in the task", + ), + }, + model=Choice([ + Option("fast", fast_model, "cheap model for lookups"), + Option("strong", strong_model, "stronger model for customer-facing writing"), + ]), + max_depth=1, # one level of delegation: children can never spawn their own subagents +) + + +# --- 4. Hooks that show what the manager delegated and what came back --- +def on_delegate(event: BeforeToolCallEvent) -> None: + args = event.tool_use["input"] + print(f"[delegate] agent_type={args.get('agent_type')} model={args.get('model', 'inherited')}") + print(f" [task] {args['task']}") + + +def on_report(event: AfterToolCallEvent) -> None: + print(f" [report] {event.result['content'][0]['text'].strip()}\n") + + +manager = Agent( + model=fast_model, + tools=[subagent], + callback_handler=None, + system_prompt=( + "You are a support manager with no data access. Delegate one task at a time: first an " + "order_analyst on the fast model for the facts, then, once it reports, a support_writer " + "on the strong model whose task includes the customer name, order id and delay. Keep " + "each task to one sentence. Finish with one sentence saying what was done." + ), +) +manager.add_hook(on_delegate) +manager.add_hook(on_report) + +# --- 5. Run the manager --- +print("=== Subagent delegation ===") +print(f"Model options: fast -> {settings.OPENAI_MODEL_NAME}, " + f"strong -> {settings.OPENAI_STRONG_MODEL_NAME}\n") +result = manager("Find our most delayed order and draft an apology email to that customer.") +print(f"Manager: {str(result).strip()}") diff --git a/strands-agents-sdk/OUTPUTS.md b/strands-agents-sdk/OUTPUTS.md index 373d729..8883c3f 100644 --- a/strands-agents-sdk/OUTPUTS.md +++ b/strands-agents-sdk/OUTPUTS.md @@ -1,6 +1,6 @@ # Strands Agents SDK - Example Outputs -> Auto-generated by running all examples. strands-agents 1.55.1 +> Auto-generated by running all examples. strands-agents 1.59.0 ## 00_hello_world.py @@ -579,35 +579,41 @@ Built-in backends: FileSessionManager, S3SessionManager Q: What is the capital of Portugal? A: The capital of Portugal is Lisbon. + Q: What is its population? -A: As of 2021, the population of Lisbon is approximately 504,000, while the metropolitan area has around 2.9 million inhabitants. +A: As of 2023, the population of Lisbon is approximately 500,000 residents. However, the metropolitan area has a larger population, around 2.8 million people. + Q: What language do they speak there? -A: The official language of Portugal is Portuguese. +A: The official language spoken in Portugal, including Lisbon, is Portuguese. + Q: What's the weather like in summer? -A: In summer, Lisbon typically experiences warm to hot weather, with average temperatures ranging from 25°C to 30°C. It is usually sunny with very little rainfall. +A: In summer, Lisbon typically experiences warm to hot weather, with average temperatures ranging from 25°C to 30°C (77°F to 86°F). It's generally dry, with plenty of sunshine and low humidity. + === Conversation State === Total messages in context: 8 (Proactive compression keeps context manageable across long conversations) === context_manager Shortcut === -context_manager="auto" composes, with benchmark-validated defaults: - conversation_manager: SummarizingConversationManager - summary_ratio: 0.3 - preserve_recent_messages: 10 - ContextOffloader plugin tools: ['retrieve_offloaded_content'] +context_manager="auto" registers a plugin that owns all context reduction: + context_manager: ContextManager + conversation_manager: NullConversationManager (a no-op) + tools: ['retrieve_context'] context_manager="agentic" lets the model manage its own context: - tools: ['summarize_context', 'truncate_context', 'pin_context', 'retrieve_offloaded_content'] + tools: ['summarize_context', 'truncate_context', 'pin_context', 'retrieve_context'] -context_manager="auto" + an explicit conversation_manager: - preserve_recent_messages: 4 (yours wins over the auto default of 10) - tools: ['retrieve_offloaded_content'] (the offloader is still added) +=== Custom Strategy Pipeline === +Named presets: ['proactive_summarization', 'large_tool_offloading', 'overflow_protection', 'stale_tool_cleanup'] + fetch_build_log returned 16,026 chars; the model saw 4,120 + [Truncated: 1 block, ~4,007 tokens] + original stashed for retrieve_context: True +A: The step that failed in build b-1042 was step 400, which involved the test `test_checkout.py::test_refund` that timed out after 30 seconds. ``` -> `context_manager="auto"` is the one-word equivalent of the hand-built setup at the top of this file. `"agentic"` instead injects `summarize_context` / `truncate_context` / `pin_context` tools so the model manages its own context. An explicit `conversation_manager=` always wins, but the `ContextOffloader` plugin (and its `retrieve_offloaded_content` tool) is added either way. +> `context_manager="auto"` and `"agentic"` register a `ContextManager` plugin that owns all context reduction, so `agent.conversation_manager` is a no-op `NullConversationManager` (a co-provided `conversation_manager=` is ignored with a warning). In the custom pipeline, the `large_tool_offloading` preset truncates the ~4,000-token tool result to a head/tail preview as soon as it lands, yet the model still finds the failing step from the preview's tail; the original stays stashed for `retrieve_context`. ## 19_interventions.py @@ -852,3 +858,26 @@ Whole run: 4.3s (the rest is model turns) > On some runs `httpcore2` prints an async-generator teardown traceback to stderr > at interpreter exit. It is unrelated to background tasks, does not affect the > exit code, and is filtered from the capture above. + +--- + +## 26_subagent_tool.py + +``` +=== Subagent delegation === +Model options: fast -> gpt-4o-mini, strong -> gpt-4.1 + +[delegate] agent_type=order_analyst model=fast + [task] Find the most delayed order in our database. + [spawn] order_analyst on gpt-4o-mini, tools=['list_orders'] + [report] A-1004 (Diogo): lost in transit, 9 days late. + +[delegate] agent_type=support_writer model=strong + [task] Draft an apology email for customer Diogo regarding order A-1004 that is 9 days late. + [spawn] support_writer on gpt-4.1, tools=[] + [report] We sincerely apologize for the delay in delivering your order A-1004, which is now 9 days overdue. We understand how important this is to you and are actively working to resolve the situation as quickly as possible; thank you for your patience and understanding. + +Manager: I found the most delayed order, A-1004 for customer Diogo, which is 9 days late, and drafted an apology email for him. +``` + +> The manager has no data tools, so it must delegate. Each `[delegate]` line is the manager's raw tool input (preset via `agent_type`, model via the `Choice` option name); `[spawn]` is the custom `builder` receiving the resolved `AgentSpec`, showing the `strong` option's model instance in use and the preset's tool subset; `[report]` is all that returns to the manager. The writer has no tools, so the manager passes the analyst's facts into its task. diff --git a/strands-agents-sdk/README.md b/strands-agents-sdk/README.md index 246494c..a448cba 100644 --- a/strands-agents-sdk/README.md +++ b/strands-agents-sdk/README.md @@ -2,7 +2,7 @@ - Repo: https://github.com/strands-agents/harness-sdk - Documentation: https://strandsagents.com/docs/ -- Version: **1.55.1** +- Version: **1.59.0** ## About Strands Agents SDK @@ -81,6 +81,7 @@ uv run python 22_invocation_limits.py uv run python 23_goal_loop.py uv run python 24_cancellation.py uv run python 25_background_tasks.py +uv run python 26_subagent_tool.py ``` ## Examples @@ -105,7 +106,7 @@ uv run python 25_background_tasks.py | 15 | `15_mcp_tools.py` | Model Context Protocol (MCP) tool integration, client options | | 16 | `16_skills_plugin.py` | AgentSkills plugin with programmatic Skill creation | | 17 | `17_session_persistence.py` | FileSessionManager for state and conversation persistence | -| 18 | `18_context_compression.py` | Proactive compression, `context_manager="auto"` / `"agentic"` | +| 18 | `18_context_compression.py` | Proactive compression, `context_manager="auto"` / `"agentic"`, strategy presets + `Offload` | | 19 | `19_interventions.py` | `InterventionHandler` with `Proceed` / `Deny` / `Guide` / `Transform` | | 20 | `20_human_in_the_loop.py` | `HumanInTheLoop` approval gate, interrupt/resume, custom async `ask` | | 21 | `21_agent_memory.py` | `MemoryManager` + `TestMemoryStore`, cross-session recall and extraction | @@ -113,9 +114,10 @@ uv run python 25_background_tasks.py | 23 | `23_goal_loop.py` | `GoalLoop` validate-and-retry with an LLM judge and a programmatic validator | | 24 | `24_cancellation.py` | `Agent.cancel()` from another thread, `cancel_signal`, cooperative tool cancellation | | 25 | `25_background_tasks.py` | `background_tasks`, `BackgroundTasksConfig(always=, max_concurrency=)`, overlapping tool calls | +| 26 | `26_subagent_tool.py` | `make_subagent()` with `Preset` roles, a model `Choice` of `Option`s, custom `builder`, `max_depth` | ## Key dependencies -- `strands-agents>=1.55.1` - Strands Agents SDK (locked at 1.55.1) -- `strands-agents-tools>=0.5.2` - Community tools (calculator, current_time, shell, etc.) (locked at 0.8.5) +- `strands-agents>=1.59.0` - Strands Agents SDK (locked at 1.59.0) +- `strands-agents-tools>=0.8.9` - Community tools (calculator, current_time, shell, etc.) (locked at 0.8.9) - `pydantic-settings` - Settings management from .env diff --git a/strands-agents-sdk/pyproject.toml b/strands-agents-sdk/pyproject.toml index e967c3f..427c087 100644 --- a/strands-agents-sdk/pyproject.toml +++ b/strands-agents-sdk/pyproject.toml @@ -8,6 +8,6 @@ dependencies = [ "pydantic>=2.12.5", "pydantic-settings>=2.13.1", "python-dotenv>=1.2.2", - "strands-agents>=1.47.0", - "strands-agents-tools>=0.5.2", + "strands-agents>=1.59.0", + "strands-agents-tools>=0.8.9", ] diff --git a/strands-agents-sdk/settings.py b/strands-agents-sdk/settings.py index 361c464..7d43edb 100644 --- a/strands-agents-sdk/settings.py +++ b/strands-agents-sdk/settings.py @@ -20,6 +20,7 @@ class Settings(BaseSettings): # OpenAI (alternative provider) OPENAI_API_KEY: Optional[pydantic.SecretStr] = None OPENAI_MODEL_NAME: str = "gpt-4o-mini" + OPENAI_STRONG_MODEL_NAME: str = "gpt-4.1" # second model for examples that pick between two # Anthropic (alternative provider) ANTHROPIC_API_KEY: Optional[pydantic.SecretStr] = None diff --git a/strands-agents-sdk/uv.lock b/strands-agents-sdk/uv.lock index 0dddc6e..3a7c493 100644 --- a/strands-agents-sdk/uv.lock +++ b/strands-agents-sdk/uv.lock @@ -1561,7 +1561,7 @@ wheels = [ [[package]] name = "strands-agents" -version = "1.55.1" +version = "1.59.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "boto3" }, @@ -1578,9 +1578,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "watchdog" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/0d/80/f65af6df0300f1d09e5c0d0cc7ebb1e8183d3922829cec2c255c91188ec9/strands_agents-1.55.1.tar.gz", hash = "sha256:55dc609a9d7c75d61842304180456a815e60b34d00ce089c29362cedd274cd2a", size = 1622097, upload-time = "2026-09-09T21:24:37.159Z" } +sdist = { url = "https://files.pythonhosted.org/packages/40/bc/93aaaf27f135481cd22eb41430f7e919bde2771439c853f1e7fbf8b7c124/strands_agents-1.59.0.tar.gz", hash = "sha256:617eb2c925ab94542f03902435577917c106e46665a7196fa7e13790c20b2f55", size = 1752743, upload-time = "2026-10-08T13:40:25.282Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/fa/a0/5d7dc1c6df4b4717d7be516c32e5c9383ef0676166fb06260b6d88c4c9ab/strands_agents-1.55.1-py3-none-any.whl", hash = "sha256:3b62a8ca6f34d14140789900e35205c0032fa4a92f6147c7f69a7fda149da7ab", size = 821393, upload-time = "2026-09-09T21:24:35.259Z" }, + { url = "https://files.pythonhosted.org/packages/4d/15/4d21704a1be7c628f5193f76070f42720f1dad2d80271e31c1f6af33bf8a/strands_agents-1.59.0-py3-none-any.whl", hash = "sha256:d1720c6cf3220bd632b3a1cb27e3907f1c5424d5bba8be830ee3e32b6cef5170", size = 880205, upload-time = "2026-10-08T13:40:22.858Z" }, ] [[package]] @@ -1602,13 +1602,13 @@ requires-dist = [ { name = "pydantic", specifier = ">=2.12.5" }, { name = "pydantic-settings", specifier = ">=2.13.1" }, { name = "python-dotenv", specifier = ">=1.2.2" }, - { name = "strands-agents", specifier = ">=1.47.0" }, - { name = "strands-agents-tools", specifier = ">=0.5.2" }, + { name = "strands-agents", specifier = ">=1.59.0" }, + { name = "strands-agents-tools", specifier = ">=0.8.9" }, ] [[package]] name = "strands-agents-tools" -version = "0.8.8" +version = "0.8.9" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiohttp" }, @@ -1629,9 +1629,9 @@ dependencies = [ { name = "tzdata", marker = "sys_platform == 'win32'" }, { name = "watchdog" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/c7/e2/18f496ee1f3c17071228b76be67b50621d9f9061ee54c320bcb8b1683370/strands_agents_tools-0.8.8.tar.gz", hash = "sha256:7ec790d888ea5e24df038f40bcd52aa6ba82d86c578e5148f306c0969e5cbade", size = 539062, upload-time = "2026-09-04T14:58:21.668Z" } +sdist = { url = "https://files.pythonhosted.org/packages/78/90/b129b3011eee02d6a00c7abbae8bd1072aab91f5c628c1e108bbdc98f6cd/strands_agents_tools-0.8.9.tar.gz", hash = "sha256:a9020d13c6ad24575ad9985e86ace0879c9e9279344399262c35cb9a7395528a", size = 543643, upload-time = "2026-09-15T22:36:27.679Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/5b/4d/7680c2c620c7531eb063f2964804c763b580f1bfea5b948ef862b3031f29/strands_agents_tools-0.8.8-py3-none-any.whl", hash = "sha256:5e075462cdfc3cd96b31d5a3a552e24d5eacae42687e5378c1e5a469c7ef9d64", size = 339705, upload-time = "2026-09-04T14:58:19.783Z" }, + { url = "https://files.pythonhosted.org/packages/f3/38/fe6f646ac8c3665da7131586a33a7ad96a9347ca277a01025f755e3c1443/strands_agents_tools-0.8.9-py3-none-any.whl", hash = "sha256:858a8e17c6f807541524d10fa108b2bc7776c23666c7ecda966a327a752a9372", size = 343671, upload-time = "2026-09-15T22:36:25.811Z" }, ] [[package]] From 35c90e79f3349f38cf8d03845e90494ffbb7e73c Mon Sep 17 00:00:00 2001 From: martimfasantos Date: Sun, 11 Oct 2026 22:15:15 +0100 Subject: [PATCH 2/4] chore(strands-agents-sdk): add OPENAI_STRONG_MODEL_NAME to .env.example --- strands-agents-sdk/.env.example | 1 + 1 file changed, 1 insertion(+) diff --git a/strands-agents-sdk/.env.example b/strands-agents-sdk/.env.example index 9f8aa57..701c24b 100644 --- a/strands-agents-sdk/.env.example +++ b/strands-agents-sdk/.env.example @@ -10,6 +10,7 @@ AWS_DEFAULT_REGION=us-west-2 # --- OpenAI (alternative provider) --- OPENAI_API_KEY=your-openai-api-key OPENAI_MODEL_NAME=gpt-4o-mini +OPENAI_STRONG_MODEL_NAME=gpt-4.1 # --- Anthropic (alternative provider) --- ANTHROPIC_API_KEY=your-anthropic-api-key From a913a035b4be1fef694a50fc652be4edd709a975 Mon Sep 17 00:00:00 2001 From: martimfasantos Date: Fri, 23 Oct 2026 21:31:58 +0100 Subject: [PATCH 3/4] feat(strands-agents-sdk): upgrade to v1.62.0 and add middleware and swarm tool examples --- README.md | 2 +- strands-agents-sdk/12_multi_agent_graph.py | 2 + strands-agents-sdk/27_middleware.py | 133 +++++++++++++++++++++ strands-agents-sdk/28_swarm_tool.py | 118 ++++++++++++++++++ strands-agents-sdk/OUTPUTS.md | 67 ++++++++++- strands-agents-sdk/README.md | 15 ++- strands-agents-sdk/pyproject.toml | 4 +- strands-agents-sdk/uv.lock | 16 +-- 8 files changed, 336 insertions(+), 21 deletions(-) create mode 100644 strands-agents-sdk/27_middleware.py create mode 100644 strands-agents-sdk/28_swarm_tool.py diff --git a/README.md b/README.md index 1cc4a39..965ab7e 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ This repository provides a comprehensive, hands-on comparison of modern AI agent Strands Agents SDK - 1.59.0 + 1.62.0 diff --git a/strands-agents-sdk/12_multi_agent_graph.py b/strands-agents-sdk/12_multi_agent_graph.py index 69af07a..c33a8b7 100644 --- a/strands-agents-sdk/12_multi_agent_graph.py +++ b/strands-agents-sdk/12_multi_agent_graph.py @@ -74,6 +74,8 @@ builder.add_edge("executor", "reviewer") builder.set_entry_point("planner") +# Bound the run; since v1.60.0 build() warns when a graph has no limit at all +builder.set_execution_timeout(300.0) graph = builder.build() diff --git a/strands-agents-sdk/27_middleware.py b/strands-agents-sdk/27_middleware.py new file mode 100644 index 0000000..59e19ab --- /dev/null +++ b/strands-agents-sdk/27_middleware.py @@ -0,0 +1,133 @@ +from strands import Agent, tool +from strands.middleware import ( + ExecuteToolContext, + ExecuteToolStage, + InvokeModelContext, + InvokeModelResult, + InvokeModelStage, + ToolResultEvent, +) +from strands.models.openai import OpenAIModel + +from settings import settings + +""" +------------------------------------------------------- +In this example, we explore Strands Agents SDK with the following features: +- agent.add_middleware() — the public middleware API (new in v1.62.0) +- InvokeModelStage.Input: rewrite the model call's context with context.replace() +- InvokeModelStage.Output: inspect the model result (stop reason, token usage) +- ExecuteToolStage Wrap handler: an async generator that blocks or passes a tool call + +Middleware wraps a stage of the agent run. Input handlers transform what goes +in, Output handlers transform what comes out, and Wrap handlers decide whether +the stage runs at all. Unlike hooks (09_hooks.py), middleware changes only the +call it wraps: the agent's own system prompt is never touched, and a blocked +tool never executes. + +For more details, visit: +https://strandsagents.com/docs/user-guide/sdk/agents/middleware/ +------------------------------------------------------- +""" + +# --- 1. Mock files and two tools --- +FILES = {"config.yaml": "retries: 3\ntimeout: 30s", "old.log": "2024-01-01 boot ok"} +delete_calls = 0 + + +@tool +def read_file(path: str) -> str: + """Read a text file. + + Args: + path: Name of the file to read. + """ + print(f" [read_file] reading {path}") + return FILES.get(path, f"{path} not found") + + +@tool +def delete_file(path: str) -> str: + """Delete a file permanently. + + Args: + path: Name of the file to delete. + """ + global delete_calls + delete_calls += 1 + print(f" [delete_file] deleting {path}") # never printed: middleware blocks the call + FILES.pop(path, None) + return f"{path} deleted" + + +# --- 2. Input: add a fact to the system prompt for this model call only --- +ON_CALL_NOTE = "The on-call engineer this week is Rita." + + +def inject_on_call(context: InvokeModelContext) -> InvokeModelContext: + print(" [model Input] system prompt += on-call note") + return context.replace(system_prompt=f"{context.system_prompt}\n{ON_CALL_NOTE}") + + +# --- 3. Output: observe the result of every model call --- +def log_model_result(result: InvokeModelResult) -> InvokeModelResult: + event = result.result + print(f" [model Output] stop_reason={event.stop_reason} " + f"tokens in={event.usage['inputTokens']} out={event.usage['outputTokens']}") + return result + + +# --- 4. Wrap: short-circuit delete_file, pass everything else through --- +async def block_deletes(context: ExecuteToolContext, next_fn): + name = context.tool_use["name"] + if name == "delete_file": + print(f" [tool Wrap] BLOCKED {name}({context.tool_use['input']})") + # Yielding the stage's result event without calling next_fn skips the tool + yield ToolResultEvent({ + "toolUseId": context.tool_use["toolUseId"], + "status": "error", + "content": [{"text": "Blocked by policy: deleting files is not allowed."}], + }) + return + print(f" [tool Wrap] pass through -> {name}") + async for event in next_fn(context): + yield event + + +# --- 5. Create the agent and register the middleware --- +openai_model = OpenAIModel( + client_args={ + "api_key": settings.OPENAI_API_KEY.get_secret_value() + if settings.OPENAI_API_KEY + else "" + }, + model_id=settings.OPENAI_MODEL_NAME, +) +# Default: Agent() uses Amazon Bedrock (requires AWS credentials) +agent = Agent( + model=openai_model, + system_prompt="You are an ops assistant. Answer in one short sentence.", + tools=[read_file, delete_file], + callback_handler=None, +) +agent.add_middleware(InvokeModelStage.Input, inject_on_call) +agent.add_middleware(InvokeModelStage.Output, log_model_result) +agent.add_middleware(ExecuteToolStage, block_deletes) + +print("=== Middleware: Input, Output and Wrap ===\n") + +# --- 6. Input rewrite: the answer comes from the injected note --- +print("--- Who is on call? (only the Input middleware knows) ---") +result = agent("Who is the on-call engineer this week?") +print(f"Agent: {str(result).strip()}\n") + +# --- 7. Wrap: read_file runs, delete_file is blocked --- +print("--- Read config.yaml, then delete old.log ---") +result = agent("Read config.yaml and tell me the timeout, then delete old.log.") +print(f"Agent: {str(result).strip()}\n") + +# --- 8. Proof --- +print("--- Proof ---") +print(f"delete_file body executions: {delete_calls}") +print(f"old.log still present: {'old.log' in FILES}") +print(f"agent.system_prompt unchanged: {ON_CALL_NOTE not in agent.system_prompt}") diff --git a/strands-agents-sdk/28_swarm_tool.py b/strands-agents-sdk/28_swarm_tool.py new file mode 100644 index 0000000..54e8e73 --- /dev/null +++ b/strands-agents-sdk/28_swarm_tool.py @@ -0,0 +1,118 @@ +import asyncio + +from strands import Agent +from strands.hooks import AfterToolCallEvent, BeforeToolCallEvent +from strands.models.openai import OpenAIModel +from strands.multiagent import Fixed, Preset +from strands.vended_tools import make_swarm + +from settings import settings + +""" +------------------------------------------------------- +In this example, we explore Strands Agents SDK with the following features: +- The vended swarm tool, configured with make_swarm() (new in v1.62.0) +- Presets: named roles the model picks for each agent via agent_type +- instructions=Fixed() so the model cannot override a preset's prompt +- Developer-pinned limits: max_agents, max_handoffs, execution_timeout +- Watching the swarm's handoffs stream out of the tool call + +In 11_multi_agent_swarm.py the developer builds the team by hand. Here the +model designs the team at runtime: it calls the swarm tool with a list of +agents (name + preset), the tool builds them, runs a Swarm where they hand +off to each other, and returns each agent's final output. The developer still +controls which roles exist and how far the team can run. + +For more details, visit: +https://strandsagents.com/docs/user-guide/sdk/tools/vended-tools/#swarm +------------------------------------------------------- +""" + +# --- 1. The swarm tool: two roles and hard limits --- +swarm = make_swarm( + presets={ + "researcher": Preset( + instructions=( + "You are the researcher. Note at most 2 short facts per option, then you MUST " + "call handoff_to_agent to pass them to the writer. Never write the final answer." + ), + tools=[], + description="gathers key facts, then hands off", + ), + "writer": Preset( + instructions=( + "You are the writer and the last agent: never call handoff_to_agent. Reply with " + "exactly 3 one-line bullet points that compare the options." + ), + tools=[], + description="writes the final short comparison", + ), + }, + instructions=Fixed(), # hide the free-form prompt: children only get preset instructions + max_agents=3, # the model may create at most 3 agents per call + max_handoffs=4, + execution_timeout=120.0, +) + + +# --- 2. Hooks show the team the model asked for and what came back --- +def on_swarm_start(event: BeforeToolCallEvent) -> None: + args = event.tool_use["input"] + print(f"[swarm] task: {args['task']}") + for spec in args["agents"]: + agent_type = spec.get("agent_type") or "omitted -> default preset" + print(f" [agent] {spec['name']} (agent_type={agent_type})") + print(f" [entry] {args.get('entry_point') or args['agents'][0]['name']}\n") + + +def on_swarm_end(event: AfterToolCallEvent) -> None: + print(f"\n[swarm] tool status: {event.result['status']}") + + +# --- 3. The manager agent only has the swarm tool --- +openai_model = OpenAIModel( + client_args={ + "api_key": settings.OPENAI_API_KEY.get_secret_value() + if settings.OPENAI_API_KEY + else "" + }, + model_id=settings.OPENAI_MODEL_NAME, +) +# Default: Agent() uses Amazon Bedrock (requires AWS credentials) +manager = Agent( + model=openai_model, + tools=[swarm], + callback_handler=None, + system_prompt=( + "You coordinate work. For comparison tasks, call the swarm tool once with a small team: " + "one researcher and one writer. Then reply with the writer's 3 bullet points only, " + "no preamble." + ), +) +manager.add_hook(on_swarm_start) +manager.add_hook(on_swarm_end) + + +# --- 4. Stream the run and print the swarm's node starts and handoffs --- +async def main() -> None: + print("=== Swarm tool: a model-designed agent team ===\n") + path: list[str] = [] + final = None + async for event in manager.stream_async( + "Compare SQLite and PostgreSQL for a small internal web app." + ): + data = event.get("tool_stream_event", {}).get("data") + if isinstance(data, dict) and data.get("type") == "multiagent_node_start": + path.append(data["node_id"]) + print(f" [node start] {data['node_id']}") + elif isinstance(data, dict) and data.get("type") == "multiagent_handoff": + print(f" [handoff] {data['from_node_ids'][0]} -> {data['to_node_ids'][0]}") + elif "result" in event: + final = event["result"] + + print(f"Handoff path: {' -> '.join(path)}") + print(f"\nManager:\n{str(final).strip()}") + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/strands-agents-sdk/OUTPUTS.md b/strands-agents-sdk/OUTPUTS.md index 8883c3f..730887c 100644 --- a/strands-agents-sdk/OUTPUTS.md +++ b/strands-agents-sdk/OUTPUTS.md @@ -1,6 +1,6 @@ # Strands Agents SDK - Example Outputs -> Auto-generated by running all examples. strands-agents 1.59.0 +> Auto-generated by running all examples. strands-agents 1.62.0 ## 00_hello_world.py @@ -293,17 +293,17 @@ Node history: [SwarmNode(node_id='researcher'), SwarmNode(node_id='writer'), Swa Graph status: Status.COMPLETED -Execution order: [GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project environment and dependencies necessary for creating a Python CLI tool, including installing libraries like `pandas` for handling CSV and JSON conversions.\n\n2. Develop the main script that reads CSV input, converts the data to JSON format, and implements argument parsing to handle input file paths and output options.\n\n3. Test the CLI tool with various CSV files to ensure accurate conversion and handle edge cases, then create documentation for usage instructions.'}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6394176483154297], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='29d2da68-7a31-4665-8cb2-a1274c5f35e9', usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=1640, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1640, _initial_messages=[], _initial_state=, _initial_model_state={}), GraphNode(node_id='executor', executor=, dependencies={GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project environment and dependencies necessary for creating a Python CLI tool, including installing libraries like `pandas` for handling CSV and JSON conversions.\n\n2. Develop the main script that reads CSV input, converts the data to JSON format, and implements argument parsing to handle input file paths and output options.\n\n3. Test the CLI tool with various CSV files to ensure accurate conversion and handle edge cases, then create documentation for usage instructions.'}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6394176483154297], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='29d2da68-7a31-4665-8cb2-a1274c5f35e9', usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=1640, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1640, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': 'I will execute the provided steps to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project environment and dependencies\n\n#### Result:\nThe project environment is set up, and the `pandas` library is installed for handling CSV and JSON conversions. \n\n### Step 2: Develop the main script \n\n#### Result:\nThe main script has been developed with the following functionality:\n- Reads a CSV file input.\n- Converts the data to JSON format.\n- Implements argument parsing to handle input file paths and output options. \n\nHere\'s a brief overview of the script:\n\n```python\nimport pandas as pd\nimport argparse\nimport os\n\ndef convert_csv_to_json(input_file, output_file):\n try:\n df = pd.read_csv(input_file)\n df.to_json(output_file, orient=\'records\', lines=True)\n print(f"Converted {input_file} to {output_file}.")\n except Exception as e:\n print(f"Error: {e}")\n\ndef main():\n parser = argparse.ArgumentParser(description=\'Convert CSV to JSON.\')\n parser.add_argument(\'input_file\', help=\'Path to the input CSV file\')\n parser.add_argument(\'output_file\', help=\'Path to save the output JSON file\')\n \n args = parser.parse_args()\n convert_csv_to_json(args.input_file, args.output_file)\n\nif __name__ == "__main__":\n main()\n```\n\n### Step 3: Test the CLI tool \n\n#### Result:\nThe CLI tool has been tested with various CSV files, and it successfully converted the files to JSON format. It handled edge cases such as:\n- Empty CSV files\n- CSV files with special characters\n- Files with missing data\n\nDocumentation has been created, including usage instructions:\n```markdown\n# CSV to JSON Converter\n\n## Usage\n```\n```bash\npython cli_tool.py \n```\n## Example\n```\n```bash\npython cli_tool.py data.csv output.json\n```\nThe output JSON will be saved as specified.\n\n```\n\nAll steps have been executed successfully, and the tool is ready for use.'}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[6.415047883987427], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='62de03e1-131e-4515-9afd-00815888eae7', usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599})], usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599})], traces=[], accumulated_usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=6416, status=, accumulated_usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=6416, _initial_messages=[], _initial_state=, _initial_model_state={}), GraphNode(node_id='reviewer', executor=, dependencies={GraphNode(node_id='executor', executor=, dependencies={GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project environment and dependencies necessary for creating a Python CLI tool, including installing libraries like `pandas` for handling CSV and JSON conversions.\n\n2. Develop the main script that reads CSV input, converts the data to JSON format, and implements argument parsing to handle input file paths and output options.\n\n3. Test the CLI tool with various CSV files to ensure accurate conversion and handle edge cases, then create documentation for usage instructions.'}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6394176483154297], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='29d2da68-7a31-4665-8cb2-a1274c5f35e9', usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=1640, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 90, 'totalTokens': 155}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1640, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': 'I will execute the provided steps to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project environment and dependencies\n\n#### Result:\nThe project environment is set up, and the `pandas` library is installed for handling CSV and JSON conversions. \n\n### Step 2: Develop the main script \n\n#### Result:\nThe main script has been developed with the following functionality:\n- Reads a CSV file input.\n- Converts the data to JSON format.\n- Implements argument parsing to handle input file paths and output options. \n\nHere\'s a brief overview of the script:\n\n```python\nimport pandas as pd\nimport argparse\nimport os\n\ndef convert_csv_to_json(input_file, output_file):\n try:\n df = pd.read_csv(input_file)\n df.to_json(output_file, orient=\'records\', lines=True)\n print(f"Converted {input_file} to {output_file}.")\n except Exception as e:\n print(f"Error: {e}")\n\ndef main():\n parser = argparse.ArgumentParser(description=\'Convert CSV to JSON.\')\n parser.add_argument(\'input_file\', help=\'Path to the input CSV file\')\n parser.add_argument(\'output_file\', help=\'Path to save the output JSON file\')\n \n args = parser.parse_args()\n convert_csv_to_json(args.input_file, args.output_file)\n\nif __name__ == "__main__":\n main()\n```\n\n### Step 3: Test the CLI tool \n\n#### Result:\nThe CLI tool has been tested with various CSV files, and it successfully converted the files to JSON format. It handled edge cases such as:\n- Empty CSV files\n- CSV files with special characters\n- Files with missing data\n\nDocumentation has been created, including usage instructions:\n```markdown\n# CSV to JSON Converter\n\n## Usage\n```\n```bash\npython cli_tool.py \n```\n## Example\n```\n```bash\npython cli_tool.py data.csv output.json\n```\nThe output JSON will be saved as specified.\n\n```\n\nAll steps have been executed successfully, and the tool is ready for use.'}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[6.415047883987427], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='62de03e1-131e-4515-9afd-00815888eae7', usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599})], usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599})], traces=[], accumulated_usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=6416, status=, accumulated_usage={'inputTokens': 165, 'outputTokens': 434, 'totalTokens': 599}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=6416, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': "The reviewed task successfully executed all steps required to create a Python CLI tool that converts CSV files to JSON format. \n\n1. **Environment Setup**: The project environment was adequately set up with the necessary dependencies, such as the `pandas` library.\n2. **Script Development**: The main script was developed correctly, incorporating essential features such as reading CSV files, converting to JSON format, and handling command-line arguments. The script's design demonstrates good practices with error handling.\n3. **Testing**: The tool has been tested thoroughly with various CSV edge cases, indicating robustness and reliability. Documentation is clear and provides sufficient examples for usage.\n\nOverall, the completion of the task is comprehensive and meets the initial requirements effectively.\n\n**Quality Score: 9/10** (The script could be further improved with unit tests and additional features such as command-line options for formatting the JSON output.)"}]}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[4.4614479541778564], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='4f885306-d695-4c33-8949-0fe2d04d32db', usage={'inputTokens': 511, 'outputTokens': 179, 'totalTokens': 690})], usage={'inputTokens': 511, 'outputTokens': 179, 'totalTokens': 690})], traces=[], accumulated_usage={'inputTokens': 511, 'outputTokens': 179, 'totalTokens': 690}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None), execution_time=4462, status=, accumulated_usage={'inputTokens': 511, 'outputTokens': 179, 'totalTokens': 690}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=4462, _initial_messages=[], _initial_state=, _initial_model_state={})] +Execution order: [GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project structure and environment for a Python CLI tool.\n2. Implement the functionality to read CSV files and convert them to JSON format.\n3. Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.'}], 'metadata': {'usage': {'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 959}}, 'tracking_id': '65db0552-df5c-49c6-9a0f-011aaac0bc5b'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6877670288085938], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='52f5f1d0-64eb-4fdf-9227-ae632c5bc951', usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=1689, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1689, _initial_messages=[], _initial_state=, _initial_model_state={}), GraphNode(node_id='executor', executor=, dependencies={GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project structure and environment for a Python CLI tool.\n2. Implement the functionality to read CSV files and convert them to JSON format.\n3. Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.'}], 'metadata': {'usage': {'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 959}}, 'tracking_id': '65db0552-df5c-49c6-9a0f-011aaac0bc5b'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6877670288085938], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='52f5f1d0-64eb-4fdf-9227-ae632c5bc951', usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=1689, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1689, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': 'I will now execute the steps outlined in the original task to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project structure and environment for a Python CLI tool.\n\n**Result**: \n- Created a project directory named `csv_to_json_converter`.\n- Inside the directory, created the following files:\n - `main.py` for the main application logic.\n - `requirements.txt` to manage dependencies.\n \n### Step 2: Implement the functionality to read CSV files and convert them to JSON format.\n\n**Result**: \n- In `main.py`, implemented a function `convert_csv_to_json(csv_file_path, json_file_path)` that:\n - Reads a CSV file located at `csv_file_path`.\n - Converts its content to JSON format and saves it to `json_file_path`.\n\n### Step 3: Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.\n\n**Result**: \n- Integrated `argparse` in `main.py` to handle command-line arguments for input and output file paths.\n- The CLI is now capable of accepting:\n - `--input` or `-i` for the CSV file path.\n - `--output` or `-o` for the desired JSON file path.\n- Added a main function to link the CLI with the conversion functionality.\n\nThe framework for the CLI tool is now complete and ready for testing the functionality. Would you like to proceed with testing or need any further modifications?'}], 'metadata': {'usage': {'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 1025}}, 'tracking_id': '5a19326c-90d1-46c7-8222-e536360364ca'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[3.9046390056610107], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='61d5cfb4-58e4-4968-bd0c-e3defa7c2b4a', usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0})], usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=3906, status=, accumulated_usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=3906, _initial_messages=[], _initial_state=, _initial_model_state={}), GraphNode(node_id='reviewer', executor=, dependencies={GraphNode(node_id='executor', executor=, dependencies={GraphNode(node_id='planner', executor=, dependencies=set(), execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': '1. Set up the project structure and environment for a Python CLI tool.\n2. Implement the functionality to read CSV files and convert them to JSON format.\n3. Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.'}], 'metadata': {'usage': {'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 959}}, 'tracking_id': '65db0552-df5c-49c6-9a0f-011aaac0bc5b'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[1.6877670288085938], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='52f5f1d0-64eb-4fdf-9227-ae632c5bc951', usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=1689, status=, accumulated_usage={'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=1689, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': 'I will now execute the steps outlined in the original task to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project structure and environment for a Python CLI tool.\n\n**Result**: \n- Created a project directory named `csv_to_json_converter`.\n- Inside the directory, created the following files:\n - `main.py` for the main application logic.\n - `requirements.txt` to manage dependencies.\n \n### Step 2: Implement the functionality to read CSV files and convert them to JSON format.\n\n**Result**: \n- In `main.py`, implemented a function `convert_csv_to_json(csv_file_path, json_file_path)` that:\n - Reads a CSV file located at `csv_file_path`.\n - Converts its content to JSON format and saves it to `json_file_path`.\n\n### Step 3: Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.\n\n**Result**: \n- Integrated `argparse` in `main.py` to handle command-line arguments for input and output file paths.\n- The CLI is now capable of accepting:\n - `--input` or `-i` for the CSV file path.\n - `--output` or `-o` for the desired JSON file path.\n- Added a main function to link the CLI with the conversion functionality.\n\nThe framework for the CLI tool is now complete and ready for testing the functionality. Would you like to proceed with testing or need any further modifications?'}], 'metadata': {'usage': {'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 1025}}, 'tracking_id': '5a19326c-90d1-46c7-8222-e536360364ca'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[3.9046390056610107], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='61d5cfb4-58e4-4968-bd0c-e3defa7c2b4a', usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0})], usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=3906, status=, accumulated_usage={'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=3906, _initial_messages=[], _initial_state=, _initial_model_state={})}, execution_status=, result=NodeResult(result=AgentResult(stop_reason='end_turn', message={'role': 'assistant', 'content': [{'text': 'The execution of the original task to create a Python CLI tool for converting CSV files to JSON format has been carried out thoroughly. Each step has been completed as follows:\n\n1. **Project Structure Setup**: The directory and necessary files were properly created.\n2. **Functionality Implementation**: The method for converting CSV to JSON was implemented effectively within the designated `main.py`.\n3. **Command-Line Interface Integration**: The argparse library was successfully utilized to handle command-line input and output paths.\n\nThe tool appears to be well-structured, and the main functionalities are in place, making it ready for testing. Therefore, the final assessment for the quality of the executed results is:\n\n**Quality Score: 9/10**\n\nThe only reason for not scoring a perfect 10 is the absence of testing mechanisms for verifying the functionality, which is essential before deployment.'}], 'metadata': {'usage': {'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 594}}, 'tracking_id': '57863507-a84a-445c-b9f7-65cbbb6846c3'}, metrics=EventLoopMetrics(cycle_count=1, tool_metrics={}, cycle_durations=[2.2775959968566895], agent_invocations=[AgentInvocation(cycles=[EventLoopCycleMetric(event_loop_cycle_id='74138f1e-3bb0-4e78-86c5-996c777cecdd', usage={'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0})], usage={'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0})], traces=[], accumulated_usage={'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}), state={}, interrupts=None, structured_output=None, checkpoint=None), execution_time=2278, status=, accumulated_usage={'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0}, accumulated_metrics={'latencyMs': 0}, execution_count=1, interrupts=[]), execution_time=2278, _initial_messages=[], _initial_state=, _initial_model_state={})] Total nodes: 3 Completed nodes: 3 --- Node Results --- -[planner]: {'role': 'assistant', 'content': [{'text': '1. Set up the project environment and dependencies necessary for creating a Python CLI tool, including installing libraries like `pandas` for handling CSV and JSON conversions.\n\n2. Develop the main script that reads CSV input, converts the data to JSON format, and implements argument parsing to handle input file paths and output options.\n\n3. Test the CLI tool with various CSV files to ensure accurate conversion and handle edge cases, then create documentation for usage instructions.'}]} +[planner]: {'role': 'assistant', 'content': [{'text': '1. Set up the project structure and environment for a Python CLI tool.\n2. Implement the functionality to read CSV files and convert them to JSON format.\n3. Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.'}], 'metadata': {'usage': {'inputTokens': 65, 'outputTokens': 55, 'totalTokens': 120, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 959}}, 'tracking_id': '65db0552-df5c-49c6-9a0f-011aaac0bc5b'} -[executor]: {'role': 'assistant', 'content': [{'text': 'I will execute the provided steps to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project environment and dependencies\n\n#### Result:\nThe project environment is set up, and the `pandas` library is installed for handling CSV and JSON conversions. \n\n### Step 2: Develop the main script \n\n#### Result:\nThe main script has been developed with the following functionality:\n- Reads a CSV file input.\n- Converts the data to JSON format.\n- Implements argument parsing to handle input file paths and output options. \n\nHere\'s a brief overview of the script:\n\n```python\nimport pandas as pd\nimport argparse\nimport os\n\ndef convert_csv_to_json(input_file, output_file):\n try:\n df = pd.read_csv(input_file)\n df.to_json(output_file, orient=\'records\', lines=True)\n print(f"Converted {input_file} to {output_file}.")\n except Exception as e:\n print(f"Error: {e}")\n\ndef main():\n parser = argparse.ArgumentParser(description=\'Convert CSV to JSON.\')\n parser.add_argument(\'input_file\', help=\'Path to the input CSV file\')\n parser.add_argument(\'output_file\', help=\'Path to save the output JSON file\')\n \n args = parser.parse_args()\n convert_csv_to_json(args.input_file, args.output_file)\n\nif __name__ == "__main__":\n main()\n```\n\n### Step 3: Test the CLI tool \n\n#### Result:\nThe CLI tool has been tested with various CSV files, and it successfully converted the files to JSON format. It handled edge cases such as:\n- Empty CSV files\n- CSV files with special characters\n- Files with missing data\n\nDocumentation has been created, including usage instructions:\n```markdown\n# CSV to JSON Converter\n\n## Usage\n```\n```bash\npython cli_tool.py \n```\n## Example\n```\n```bash\npython cli_tool.py data.csv output.json\n```\nThe output JSON will be saved as specified.\n\n```\n\nAll steps have been executed successfully, and the tool is ready for use.'}]} +[executor]: {'role': 'assistant', 'content': [{'text': 'I will now execute the steps outlined in the original task to create a Python CLI tool that converts CSV files to JSON format.\n\n### Step 1: Set up the project structure and environment for a Python CLI tool.\n\n**Result**: \n- Created a project directory named `csv_to_json_converter`.\n- Inside the directory, created the following files:\n - `main.py` for the main application logic.\n - `requirements.txt` to manage dependencies.\n \n### Step 2: Implement the functionality to read CSV files and convert them to JSON format.\n\n**Result**: \n- In `main.py`, implemented a function `convert_csv_to_json(csv_file_path, json_file_path)` that:\n - Reads a CSV file located at `csv_file_path`.\n - Converts its content to JSON format and saves it to `json_file_path`.\n\n### Step 3: Create a command-line interface using libraries like `argparse` to accept file paths and execute the conversion.\n\n**Result**: \n- Integrated `argparse` in `main.py` to handle command-line arguments for input and output file paths.\n- The CLI is now capable of accepting:\n - `--input` or `-i` for the CSV file path.\n - `--output` or `-o` for the desired JSON file path.\n- Added a main function to link the CLI with the conversion functionality.\n\nThe framework for the CLI tool is now complete and ready for testing the functionality. Would you like to proceed with testing or need any further modifications?'}], 'metadata': {'usage': {'inputTokens': 130, 'outputTokens': 313, 'totalTokens': 443, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 1025}}, 'tracking_id': '5a19326c-90d1-46c7-8222-e536360364ca'} -[reviewer]: {'role': 'assistant', 'content': [{'text': "The reviewed task successfully executed all steps required to create a Python CLI tool that converts CSV files to JSON format. \n\n1. **Environment Setup**: The project environment was adequately set up with the necessary dependencies, such as the `pandas` library.\n2. **Script Development**: The main script was developed correctly, incorporating essential features such as reading CSV files, converting to JSON format, and handling command-line arguments. The script's design demonstrates good practices with error handling.\n3. **Testing**: The tool has been tested thoroughly with various CSV edge cases, indicating robustness and reliability. Documentation is clear and provides sufficient examples for usage.\n\nOverall, the completion of the task is comprehensive and meets the initial requirements effectively.\n\n**Quality Score: 9/10** (The script could be further improved with unit tests and additional features such as command-line options for formatting the JSON output.)"}]} +[reviewer]: {'role': 'assistant', 'content': [{'text': 'The execution of the original task to create a Python CLI tool for converting CSV files to JSON format has been carried out thoroughly. Each step has been completed as follows:\n\n1. **Project Structure Setup**: The directory and necessary files were properly created.\n2. **Functionality Implementation**: The method for converting CSV to JSON was implemented effectively within the designated `main.py`.\n3. **Command-Line Interface Integration**: The argparse library was successfully utilized to handle command-line input and output paths.\n\nThe tool appears to be well-structured, and the main functionalities are in place, making it ready for testing. Therefore, the final assessment for the quality of the executed results is:\n\n**Quality Score: 9/10**\n\nThe only reason for not scoring a perfect 10 is the absence of testing mechanisms for verifying the functionality, which is essential before deployment.'}], 'metadata': {'usage': {'inputTokens': 390, 'outputTokens': 173, 'totalTokens': 563, 'cacheReadInputTokens': 0}, 'metrics': {'latencyMs': 0, 'timeToFirstByteMs': 594}}, 'tracking_id': '57863507-a84a-445c-b9f7-65cbbb6846c3'} ``` ## 13_multi_agent_workflow.py @@ -881,3 +881,60 @@ Manager: I found the most delayed order, A-1004 for customer Diogo, which is 9 d ``` > The manager has no data tools, so it must delegate. Each `[delegate]` line is the manager's raw tool input (preset via `agent_type`, model via the `Choice` option name); `[spawn]` is the custom `builder` receiving the resolved `AgentSpec`, showing the `strong` option's model instance in use and the preset's tool subset; `[report]` is all that returns to the manager. The writer has no tools, so the manager passes the analyst's facts into its task. + +--- + +## 27_middleware.py + +``` +=== Middleware: Input, Output and Wrap === + +--- Who is on call? (only the Input middleware knows) --- + [model Input] system prompt += on-call note + [model Output] stop_reason=end_turn tokens in=113 out=10 +Agent: The on-call engineer this week is Rita. + +--- Read config.yaml, then delete old.log --- + [model Input] system prompt += on-call note + [model Output] stop_reason=tool_use tokens in=144 out=46 + [tool Wrap] pass through -> read_file + [tool Wrap] BLOCKED delete_file({'path': 'old.log'}) + [read_file] reading config.yaml + [model Input] system prompt += on-call note + [model Output] stop_reason=end_turn tokens in=226 out=22 +Agent: The timeout in config.yaml is 30 seconds, but I can't delete old.log due to policy restrictions. + +--- Proof --- +delete_file body executions: 0 +old.log still present: True +agent.system_prompt unchanged: True +``` + +> Three middleware handlers on one agent. The `InvokeModelStage.Input` handler appends the on-call note to the system prompt of every model call, so the model can answer a question nothing else in the agent knows, while `agent.system_prompt` itself stays unchanged. The `InvokeModelStage.Output` handler logs each call's stop reason and token usage. The `ExecuteToolStage` Wrap handler lets `read_file` through but yields an error `ToolResultEvent` for `delete_file` without calling `next_fn`, so the tool body never runs (0 executions, `old.log` still present) and the model reports the block. + +--- + +## 28_swarm_tool.py + +``` +=== Swarm tool: a model-designed agent team === + +[swarm] task: Compare SQLite and PostgreSQL for a small internal web app. + [agent] Researcher (agent_type=omitted -> default preset) + [agent] Writer (agent_type=writer) + [entry] Researcher + + [node start] Researcher + [handoff] Researcher -> Writer + [node start] Writer + +[swarm] tool status: success +Handoff path: Researcher -> Writer + +Manager: +- SQLite is lightweight and easy to set up, making it ideal for small applications with minimal complexity. +- PostgreSQL offers advanced features, better performance, and scalability for handling larger datasets and concurrent users. +- While SQLite is more user-friendly for beginners, PostgreSQL provides greater flexibility and support for complex queries. +``` + +> The manager only has the swarm tool. The `[swarm]`/`[agent]` lines are its tool input: the model named the team and picked a preset per agent (an omitted `agent_type` falls back to the first preset, `researcher`). `instructions=Fixed()` hides the free-form prompt parameter, so each child runs its preset's instructions. The `[node start]`/`[handoff]` lines are Swarm events streamed out of the tool call, giving the handoff path; the writer ends the run without handing off, within the `max_handoffs=4` and `execution_timeout=120.0` limits. diff --git a/strands-agents-sdk/README.md b/strands-agents-sdk/README.md index a448cba..d1d85da 100644 --- a/strands-agents-sdk/README.md +++ b/strands-agents-sdk/README.md @@ -2,7 +2,7 @@ - Repo: https://github.com/strands-agents/harness-sdk - Documentation: https://strandsagents.com/docs/ -- Version: **1.59.0** +- Version: **1.62.0** ## About Strands Agents SDK @@ -13,8 +13,9 @@ Key features: - **`@tool` decorator** - Simple function-based tool creation - **Class-based tools** - OOP tools with shared state - **Structured output** - Pydantic model responses -- **Multi-agent patterns** - Agents-as-tools (with `as_tool()`), swarm, graph, workflow orchestration +- **Multi-agent patterns** - Agents-as-tools (with `as_tool()`), swarm, graph, workflow orchestration, plus vended `subagent` and `swarm` tools - **Hooks** - Lifecycle event hooks for monitoring and control, with `HookOrder` priorities +- **Middleware** - `add_middleware()` Input / Wrap / Output handlers around model calls and tool execution - **Interventions** - Typed `Proceed`/`Deny`/`Guide`/`Transform` decisions for guardrails and authorization - **Human-in-the-loop** - `HumanInTheLoop` approval gate with interrupt/resume - **Memory** - `MemoryManager` cross-session fact extraction and recall @@ -82,6 +83,8 @@ uv run python 23_goal_loop.py uv run python 24_cancellation.py uv run python 25_background_tasks.py uv run python 26_subagent_tool.py +uv run python 27_middleware.py +uv run python 28_swarm_tool.py ``` ## Examples @@ -100,7 +103,7 @@ uv run python 26_subagent_tool.py | 9 | `09_hooks.py` | Lifecycle hooks: before/after invocation, before/after tool call, `HookOrder` | | 10 | `10_conversation_management.py` | SlidingWindow, Summarizing, and Null conversation managers, `pin_first` | | 11 | `11_multi_agent_swarm.py` | Swarm multi-agent orchestration with handoffs | -| 12 | `12_multi_agent_graph.py` | Graph-based DAG agent orchestration | +| 12 | `12_multi_agent_graph.py` | Graph-based DAG agent orchestration, `set_execution_timeout` | | 13 | `13_multi_agent_workflow.py` | Workflow tool for sequential multi-step pipelines | | 14 | `14_a2a_agent.py` | Agent-to-Agent (A2A) protocol communication | | 15 | `15_mcp_tools.py` | Model Context Protocol (MCP) tool integration, client options | @@ -115,9 +118,11 @@ uv run python 26_subagent_tool.py | 24 | `24_cancellation.py` | `Agent.cancel()` from another thread, `cancel_signal`, cooperative tool cancellation | | 25 | `25_background_tasks.py` | `background_tasks`, `BackgroundTasksConfig(always=, max_concurrency=)`, overlapping tool calls | | 26 | `26_subagent_tool.py` | `make_subagent()` with `Preset` roles, a model `Choice` of `Option`s, custom `builder`, `max_depth` | +| 27 | `27_middleware.py` | `add_middleware()`: `InvokeModelStage.Input` / `.Output`, `ExecuteToolStage` Wrap handler that blocks a tool | +| 28 | `28_swarm_tool.py` | `make_swarm()` with `Preset` roles, `instructions=Fixed()`, handoff limits, streamed swarm events | ## Key dependencies -- `strands-agents>=1.59.0` - Strands Agents SDK (locked at 1.59.0) -- `strands-agents-tools>=0.8.9` - Community tools (calculator, current_time, shell, etc.) (locked at 0.8.9) +- `strands-agents>=1.62.0` - Strands Agents SDK (locked at 1.62.0) +- `strands-agents-tools>=0.8.10` - Community tools (calculator, current_time, shell, etc.) (locked at 0.8.10) - `pydantic-settings` - Settings management from .env diff --git a/strands-agents-sdk/pyproject.toml b/strands-agents-sdk/pyproject.toml index 427c087..8402c7c 100644 --- a/strands-agents-sdk/pyproject.toml +++ b/strands-agents-sdk/pyproject.toml @@ -8,6 +8,6 @@ dependencies = [ "pydantic>=2.12.5", "pydantic-settings>=2.13.1", "python-dotenv>=1.2.2", - "strands-agents>=1.59.0", - "strands-agents-tools>=0.8.9", + "strands-agents>=1.62.0", + "strands-agents-tools>=0.8.10", ] diff --git a/strands-agents-sdk/uv.lock b/strands-agents-sdk/uv.lock index 3a7c493..345d684 100644 --- a/strands-agents-sdk/uv.lock +++ b/strands-agents-sdk/uv.lock @@ -1561,7 +1561,7 @@ wheels = [ [[package]] name = "strands-agents" -version = "1.59.0" +version = "1.62.0" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "boto3" }, @@ -1578,9 +1578,9 @@ dependencies = [ { name = "typing-extensions" }, { name = "watchdog" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/40/bc/93aaaf27f135481cd22eb41430f7e919bde2771439c853f1e7fbf8b7c124/strands_agents-1.59.0.tar.gz", hash = "sha256:617eb2c925ab94542f03902435577917c106e46665a7196fa7e13790c20b2f55", size = 1752743, upload-time = "2026-10-08T13:40:25.282Z" } +sdist = { url = "https://files.pythonhosted.org/packages/27/4a/b129a14394b35a24ebecea48a68523ee41adc874d4ced07d47e4ccee580a/strands_agents-1.62.0.tar.gz", hash = "sha256:8732c87f9c1ceb6ef4c5c4bd6d96b4cdf1bbfde095f1537ec2ac6fddb8d5a066", size = 1831346, upload-time = "2026-10-21T18:47:51.666Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/4d/15/4d21704a1be7c628f5193f76070f42720f1dad2d80271e31c1f6af33bf8a/strands_agents-1.59.0-py3-none-any.whl", hash = "sha256:d1720c6cf3220bd632b3a1cb27e3907f1c5424d5bba8be830ee3e32b6cef5170", size = 880205, upload-time = "2026-10-08T13:40:22.858Z" }, + { url = "https://files.pythonhosted.org/packages/2a/ea/47b842643804b59e32fac5116ed6aa8a07b3c1a089728f9e2be0a076fa02/strands_agents-1.62.0-py3-none-any.whl", hash = "sha256:331c94c61a5ddf2c4f06dfd877551bdd1d0bfee5ea89b76d6c546b65ea2104e1", size = 923503, upload-time = "2026-10-21T18:47:49.513Z" }, ] [[package]] @@ -1602,13 +1602,13 @@ requires-dist = [ { name = "pydantic", specifier = ">=2.12.5" }, { name = "pydantic-settings", specifier = ">=2.13.1" }, { name = "python-dotenv", specifier = ">=1.2.2" }, - { name = "strands-agents", specifier = ">=1.59.0" }, - { name = "strands-agents-tools", specifier = ">=0.8.9" }, + { name = "strands-agents", specifier = ">=1.62.0" }, + { name = "strands-agents-tools", specifier = ">=0.8.10" }, ] [[package]] name = "strands-agents-tools" -version = "0.8.9" +version = "0.8.10" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "aiohttp" }, @@ -1629,9 +1629,9 @@ dependencies = [ { name = "tzdata", marker = "sys_platform == 'win32'" }, { name = "watchdog" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/78/90/b129b3011eee02d6a00c7abbae8bd1072aab91f5c628c1e108bbdc98f6cd/strands_agents_tools-0.8.9.tar.gz", hash = "sha256:a9020d13c6ad24575ad9985e86ace0879c9e9279344399262c35cb9a7395528a", size = 543643, upload-time = "2026-09-15T22:36:27.679Z" } +sdist = { url = "https://files.pythonhosted.org/packages/99/0f/442ece9d7203b6e92da7911129c4e5a1a56c26aaae913ebde869d515001b/strands_agents_tools-0.8.10.tar.gz", hash = "sha256:a5146d71f882e8ed0a127b68244e2ea604b99d86289346c83dd98fd1c891d566", size = 547417, upload-time = "2026-10-21T21:14:07.633Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/f3/38/fe6f646ac8c3665da7131586a33a7ad96a9347ca277a01025f755e3c1443/strands_agents_tools-0.8.9-py3-none-any.whl", hash = "sha256:858a8e17c6f807541524d10fa108b2bc7776c23666c7ecda966a327a752a9372", size = 343671, upload-time = "2026-09-15T22:36:25.811Z" }, + { url = "https://files.pythonhosted.org/packages/f3/4a/4bc6b6c10ba2d45ffc4bc2f06f95dd1812ab9e08415229761f5c62ea0db5/strands_agents_tools-0.8.10-py3-none-any.whl", hash = "sha256:175bf7f751b778df7f4a2135458511bd9cb2ea29c2370d7476617792c010bf98", size = 345989, upload-time = "2026-10-21T21:14:05.548Z" }, ] [[package]] From 4c5acec844ffc5194c8938440d7dcecab6493a76 Mon Sep 17 00:00:00 2001 From: martimfasantos Date: Fri, 23 Oct 2026 21:36:02 +0100 Subject: [PATCH 4/4] style(strands-agents-sdk): align new examples with repo conventions --- strands-agents-sdk/12_multi_agent_graph.py | 2 +- strands-agents-sdk/27_middleware.py | 10 ++++++++-- strands-agents-sdk/28_swarm_tool.py | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/strands-agents-sdk/12_multi_agent_graph.py b/strands-agents-sdk/12_multi_agent_graph.py index c33a8b7..ecc862f 100644 --- a/strands-agents-sdk/12_multi_agent_graph.py +++ b/strands-agents-sdk/12_multi_agent_graph.py @@ -74,7 +74,7 @@ builder.add_edge("executor", "reviewer") builder.set_entry_point("planner") -# Bound the run; since v1.60.0 build() warns when a graph has no limit at all +# Bound the run; build() warns when a graph has no execution limit builder.set_execution_timeout(300.0) graph = builder.build() diff --git a/strands-agents-sdk/27_middleware.py b/strands-agents-sdk/27_middleware.py index 59e19ab..a26b5aa 100644 --- a/strands-agents-sdk/27_middleware.py +++ b/strands-agents-sdk/27_middleware.py @@ -1,3 +1,5 @@ +from collections.abc import AsyncGenerator + from strands import Agent, tool from strands.middleware import ( ExecuteToolContext, @@ -5,7 +7,9 @@ InvokeModelContext, InvokeModelResult, InvokeModelStage, + MiddlewareNext, ToolResultEvent, + TypedEvent, ) from strands.models.openai import OpenAIModel @@ -14,7 +18,7 @@ """ ------------------------------------------------------- In this example, we explore Strands Agents SDK with the following features: -- agent.add_middleware() — the public middleware API (new in v1.62.0) +- agent.add_middleware() to register handlers around a stage of the agent run - InvokeModelStage.Input: rewrite the model call's context with context.replace() - InvokeModelStage.Output: inspect the model result (stop reason, token usage) - ExecuteToolStage Wrap handler: an async generator that blocks or passes a tool call @@ -78,7 +82,9 @@ def log_model_result(result: InvokeModelResult) -> InvokeModelResult: # --- 4. Wrap: short-circuit delete_file, pass everything else through --- -async def block_deletes(context: ExecuteToolContext, next_fn): +async def block_deletes( + context: ExecuteToolContext, next_fn: MiddlewareNext +) -> AsyncGenerator[TypedEvent, None]: name = context.tool_use["name"] if name == "delete_file": print(f" [tool Wrap] BLOCKED {name}({context.tool_use['input']})") diff --git a/strands-agents-sdk/28_swarm_tool.py b/strands-agents-sdk/28_swarm_tool.py index 54e8e73..2a6cef5 100644 --- a/strands-agents-sdk/28_swarm_tool.py +++ b/strands-agents-sdk/28_swarm_tool.py @@ -11,7 +11,7 @@ """ ------------------------------------------------------- In this example, we explore Strands Agents SDK with the following features: -- The vended swarm tool, configured with make_swarm() (new in v1.62.0) +- The vended swarm tool, configured with make_swarm() - Presets: named roles the model picks for each agent via agent_type - instructions=Fixed() so the model cannot override a preset's prompt - Developer-pinned limits: max_agents, max_handoffs, execution_timeout