strands/agent/mod.rs
1//! The agent: [`Agent`] and its configuration, the invocation API and its result, the
2//! per-invocation state, the request context, direct tool calls, agents as tools, and the agent
3//! views: [`LocalAgent`] for sequential hooks and plugins, [`ToolAgent`] for tools and per-tool
4//! hooks.
5//!
6//! # Agent, tool and streaming
7//!
8//! ```
9//! use futures::StreamExt;
10//! use strands::{tool, Agent, AgentStreamEvent};
11//!
12//! /// Get the current weather for a city.
13//! #[tool]
14//! async fn get_weather(
15//! /// City name, for example "Seattle".
16//! city: String,
17//! ) -> Result<String, strands::ToolError> {
18//! Ok(format!("Sunny in {city}"))
19//! }
20//!
21//! #[tokio::main]
22//! async fn main() -> Result<(), strands::Error> {
23//! let mut agent = Agent::builder() // default model: Bedrock
24//! # .model(strands::testing::MockModel::from_turns(["It is sunny.", "It is mild."]))
25//! # .printer(false)
26//! .system_prompt("You are a concise assistant.")
27//! .tools([GetWeather])
28//! .build()?;
29//!
30//! let result = agent.invoke("What's the weather in Seattle?").await?;
31//! println!("{result}");
32//!
33//! {
34//! let mut stream = agent.stream("And in Lisbon?");
35//! while let Some(event) = stream.next().await {
36//! if let AgentStreamEvent::ModelStreamUpdate(update) = event? {
37//! if let Some(text) = update.text_delta() {
38//! print!("{text}");
39//! }
40//! }
41//! }
42//! }
43//! agent.shutdown().await
44//! }
45//! ```
46//!
47//! # Config struct
48//!
49//! ```
50//! use strands::{Agent, AgentConfig};
51//! # use strands::testing::MockModel;
52//!
53//! let agent = Agent::new(AgentConfig {
54//! model: Some(MockModel::new().into()), // any provider, such as an `AnthropicModel`
55//! system_prompt: Some("You are a concise assistant.".into()),
56//! ..Default::default()
57//! })?;
58//! # Ok::<(), strands::Error>(())
59//! ```
60//!
61//! # Tools with state
62//!
63//! ```
64//! use std::sync::Arc;
65//! use strands::{tools, Agent, ToolContext};
66//! # struct Pool;
67//! # impl Pool {
68//! # async fn stock(&self, _sku: &str) -> std::io::Result<u32> { Ok(3) }
69//! # }
70//! # let db = Pool;
71//!
72//! struct Inventory { db: Pool }
73//!
74//! #[tools]
75//! impl Inventory {
76//! /// Look up stock for a product.
77//! #[tool]
78//! async fn check_stock(&self, #[tool(context)] ctx: &ToolContext, sku: String) -> Result<u32, strands::ToolError> {
79//! let _ = ctx.agent().app_state().get::<String>("region");
80//! Ok(self.db.stock(&sku).await?)
81//! }
82//! }
83//!
84//! let inventory = Arc::new(Inventory { db });
85//! let agent = Agent::builder()
86//! # .model(strands::testing::MockModel::new())
87//! .tools(inventory.tools())
88//! .build()?;
89//! # assert_eq!(agent.tools()[0].name(), "check_stock");
90//! # Ok::<(), strands::Error>(())
91//! ```
92//!
93//! # Hooks, structured output and cancellation
94//!
95//! ```
96//! use strands::hooks::BeforeToolCallEvent;
97//! use strands::{Agent, CancelOptions, InvokeOptions};
98//! # use serde_json::json;
99//! # use strands::testing::{MockModel, MockTurn};
100//! # use strands::types::ToolUseBlock;
101//!
102//! # async fn audit_log(_tool_use: &strands::ToolUse) {}
103//! # async fn run() -> Result<(), strands::Error> {
104//! # let reply = ToolUseBlock::new("strands_structured_output", "t-1", json!({"title": "Thread", "points": ["a"]}));
105//! # let model = MockModel::from_turns([MockTurn::content([strands::ContentBlock::from(reply)])]);
106//! let mut agent = Agent::builder()
107//! # .model(model)
108//! # .printer(false)
109//! .build()?;
110//!
111//! agent.add_hook(|event: &mut BeforeToolCallEvent| {
112//! if event.tool_use().name == "shell" {
113//! event.set_cancel("shell is disabled");
114//! }
115//! });
116//!
117//! agent.add_async_hook::<BeforeToolCallEvent>(|event| Box::pin(async move {
118//! audit_log(event.tool_use()).await;
119//! }));
120//!
121//! #[derive(serde::Deserialize, schemars::JsonSchema)]
122//! struct Summary { title: String, points: Vec<String> }
123//!
124//! let summary: Summary = agent
125//! .invoke_with("Summarize this thread", InvokeOptions::default().structured_output_schema::<Summary>())
126//! .await?
127//! .structured_output()?;
128//! # assert_eq!(summary.title, "Thread");
129//! # assert_eq!(summary.points, ["a"]);
130//!
131//! let cancel = agent.cancel_handle();
132//! tokio::spawn(async move {
133//! tokio::time::sleep(std::time::Duration::from_secs(30)).await;
134//! cancel.cancel(CancelOptions::default());
135//! });
136//! # Ok(())
137//! # }
138//! # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(run()).unwrap();
139//! ```
140
141#[allow(
142 clippy::module_inception,
143 reason = "the `Agent` type has its own file, apart from the rest of the module"
144)]
145mod agent;
146mod agent_as_tool;
147mod agent_delegation;
148mod config;
149pub(crate) mod continuation;
150#[cfg(not(feature = "bedrock"))]
151mod default_model;
152mod event_loop;
153mod invocation_context;
154mod invocation_state;
155mod invoke_args;
156mod local_agent;
157mod mcp_tools;
158mod printer;
159mod result;
160pub(crate) mod snapshot;
161mod stream;
162mod tool_agent;
163mod tool_caller;
164mod tool_pipeline;
165
166pub use agent::Agent;
167pub(crate) use agent::resolve_plain_model;
168pub use agent_as_tool::{AgentAsTool, AgentAsToolOptions, DELEGATION_DESCRIPTION_SUFFIX};
169pub(crate) use agent_as_tool::{AgentToolStreamer, Resume, merge_events_first};
170pub use config::{AgentBuilder, AgentConfig, InvokeOptions, ModelSource};
171pub(crate) use event_loop::BLANK_TEXT_PLACEHOLDER;
172#[cfg(test)]
173pub(crate) use event_loop::cancelled_error;
174pub(crate) use event_loop::is_cancelled_error;
175pub use invocation_context::{InvocationContext, InvocationContextUsage, InvokeLimits, LimitKey};
176pub use invocation_state::InvocationState;
177pub use invoke_args::InvokeArgs;
178pub use local_agent::LocalAgent;
179pub use result::AgentResult;
180pub use snapshot::{SnapshotField, SnapshotPreset, TakeSnapshotOptions};
181pub use stream::AgentStream;
182pub use tool_agent::{RefusedCall, ToolAgent};
183pub use tool_caller::{DirectToolCallOptions, ToolHandle};