strands/agent/config.rs
1//! Agent configuration (`AgentConfig`) and per-invocation options (`InvokeOptions`).
2
3use std::collections::BTreeMap;
4use std::fmt;
5use std::sync::Arc;
6
7use schemars::JsonSchema as SchemarsJsonSchema;
8
9use super::invocation_context::{InvocationContext, InvokeLimits};
10use super::invocation_state::InvocationState;
11use crate::background_tasks::BackgroundTasksConfig;
12use crate::cancel::CancelSignal;
13use crate::context_manager::ContextManagerStrategy;
14use crate::conversation_manager::ConversationManager;
15use crate::interventions::InterventionHandler;
16use crate::memory::MemoryManagerSource;
17use crate::models::Model;
18use crate::models::routing::ModelRouter;
19use crate::plugins::Plugin;
20use crate::retry::RetryStrategy;
21use crate::sandbox::Sandbox;
22use crate::session::SessionManager;
23use crate::storage::Storage;
24use crate::telemetry::AttributeValue;
25use crate::tools::{ToolExecutorStrategy, ToolSource, schema_for};
26use crate::types::{JsonObject, JsonSchema, Message, SystemPrompt, Toggle};
27
28/// The model an agent calls: a model instance, a router or a Bedrock model id.
29#[derive(Clone)]
30#[non_exhaustive]
31pub enum ModelSource {
32 /// A model instance.
33 Model(Arc<dyn Model>),
34 /// A [`ModelRouter`]; the agent's model is its default model. Not accepted as `aux_model`.
35 Router(ModelRouter),
36 /// A Bedrock model id; needs the `bedrock` feature.
37 Id(String),
38}
39
40impl From<Arc<dyn Model>> for ModelSource {
41 fn from(model: Arc<dyn Model>) -> Self {
42 Self::Model(model)
43 }
44}
45
46impl<M: Model> From<M> for ModelSource {
47 fn from(model: M) -> Self {
48 Self::Model(Arc::new(model))
49 }
50}
51
52impl<M: Model> From<Arc<M>> for ModelSource {
53 fn from(model: Arc<M>) -> Self {
54 Self::Model(model)
55 }
56}
57
58impl From<ModelRouter> for ModelSource {
59 fn from(router: ModelRouter) -> Self {
60 Self::Router(router)
61 }
62}
63
64impl From<&str> for ModelSource {
65 fn from(model_id: &str) -> Self {
66 Self::Id(model_id.to_owned())
67 }
68}
69
70impl From<String> for ModelSource {
71 fn from(model_id: String) -> Self {
72 Self::Id(model_id)
73 }
74}
75
76impl fmt::Debug for ModelSource {
77 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78 match self {
79 Self::Model(model) => f.debug_tuple("Model").field(&model.model_id()).finish(),
80 Self::Router(router) => f.debug_tuple("Router").field(router).finish(),
81 Self::Id(model_id) => f.debug_tuple("Id").field(model_id).finish(),
82 }
83 }
84}
85
86/// Configuration for an [`Agent`](crate::Agent) (`AgentConfig`).
87///
88/// Build an agent from it with [`Agent::new`](crate::Agent::new), or set the same keys on
89/// [`Agent::builder`](crate::Agent::builder).
90///
91/// ```
92/// use strands::{Agent, AgentConfig};
93/// use strands::testing::MockModel;
94///
95/// let agent = Agent::new(AgentConfig {
96/// model: Some(MockModel::new().with_turn("Hi").into()),
97/// system_prompt: Some("You are a concise assistant.".into()),
98/// printer: Some(false),
99/// ..Default::default()
100/// })?;
101/// assert_eq!(agent.name(), "Strands Agent");
102/// # Ok::<(), strands::Error>(())
103/// ```
104#[derive(Default, bon::Builder)]
105#[builder(
106 builder_type(name = AgentBuilder, vis = "pub", doc {
107 /// Builds an [`Agent`](crate::Agent); the setters are the [`AgentConfig`] keys.
108 }),
109 start_fn(name = builder, vis = "pub(crate)"),
110 finish_fn(name = into_config, vis = "pub(crate)")
111)]
112pub struct AgentConfig {
113 /// Initial tools; nested lists are flattened and agents become tools (`ToolList`). Set them
114 /// with the builder's `tools(..)`, which takes any iterator of [`ToolSource`] items.
115 #[builder(field)]
116 pub tools: Vec<ToolSource>,
117 /// Plugins to initialize with the agent. Set them with the builder's `plugins(..)`, which
118 /// takes plugins by value or as `Arc`s.
119 #[builder(field)]
120 pub plugins: Vec<Arc<dyn Plugin>>,
121 /// Intervention handlers, evaluated in registration order at each lifecycle point
122 /// (`interventions`); names must be unique. Set them with the builder's `interventions(..)`,
123 /// which takes handlers of one type by value or as `Arc`s, or one at a time with
124 /// `intervention(..)`.
125 #[builder(field)]
126 pub interventions: Vec<Arc<dyn InterventionHandler>>,
127 /// The model the agent calls: a model instance, a [`ModelRouter`] or a Bedrock model id.
128 /// Defaults to Bedrock, resolved when the agent first calls it. With a router, the agent's
129 /// model is the router's default model.
130 #[builder(into)]
131 pub model: Option<ModelSource>,
132 /// The model for auxiliary side calls (conversation-manager summaries, memory extraction,
133 /// classification); defaults to `model`. The context manager's summarize strategy does not
134 /// use it: it resolves its own model, then `model`. A router is rejected: side calls run outside the loop it
135 /// attaches to.
136 #[builder(into)]
137 pub aux_model: Option<ModelSource>,
138 /// Initial conversation history.
139 #[builder(default)]
140 pub messages: Vec<Message>,
141 /// The system prompt.
142 #[builder(into)]
143 pub system_prompt: Option<SystemPrompt>,
144 /// Initial app state.
145 pub app_state: Option<JsonObject>,
146 /// Initial model-provider state, such as a restored response id.
147 pub model_state: Option<JsonObject>,
148 /// Print text, reasoning and tool activity to stdout as it streams. Defaults to `true`; turn
149 /// it off in services with `printer(false)`.
150 pub printer: Option<bool>,
151 /// Retry strategies for failed model calls. `None` installs the default
152 /// [`DefaultModelRetryStrategy`](crate::DefaultModelRetryStrategy); an empty list disables
153 /// retries.
154 pub retry_strategy: Option<Vec<RetryStrategy>>,
155 /// JSON schema the agent's final answer must satisfy. The builder
156 /// sets it from a type with `structured_output_schema::<T>()`, or from JSON with
157 /// `structured_output_schema_json(..)`.
158 #[builder(setters(name = structured_output_schema_json))]
159 pub structured_output_schema: Option<JsonSchema>,
160 /// The agent's name. Defaults to `Strands Agent`.
161 #[builder(into)]
162 pub name: Option<String>,
163 /// What the agent does.
164 #[builder(into)]
165 pub description: Option<String>,
166 /// The agent's id. Defaults to `agent`.
167 #[builder(into)]
168 pub id: Option<String>,
169 /// Send tool specs to the model sorted by name on every request (model calls, context
170 /// summaries, token counts), to keep prompt-cache prefixes stable when the same tools are
171 /// registered in a different order, for example from MCP servers (`sortTools`). Sorting
172 /// happens before middleware, which can still reorder them. Defaults to `false`, which keeps
173 /// registration order.
174 pub sort_tools: Option<bool>,
175 /// How the tool calls of one model turn run. Defaults to concurrent.
176 #[builder(into)]
177 pub tool_executor: Option<ToolExecutorStrategy>,
178 /// Keeps the history within the context window. Defaults to a
179 /// [`SlidingWindowConversationManager`](crate::conversation_manager::SlidingWindowConversationManager)
180 /// of 40 messages; a stateful model uses
181 /// [`NullConversationManager`](crate::conversation_manager::NullConversationManager) and
182 /// rejects one. The builder's `conversation_manager(..)` takes a manager by value or as an
183 /// `Arc`.
184 #[builder(with = |manager: impl ConversationManager| Arc::new(manager) as Arc<dyn ConversationManager>)]
185 pub conversation_manager: Option<Arc<dyn ConversationManager>>,
186 /// Strategy-driven context management: a preset, a
187 /// configuration, an instance, or `Disabled`. When set (except `Disabled`) it owns overflow
188 /// recovery and compression, and a co-provided `conversation_manager` is ignored.
189 #[builder(into)]
190 pub context_manager: Option<ContextManagerStrategy>,
191 /// Background tool execution:
192 /// `true`, a [`BackgroundTasksConfig`], or `false`. Unset is off.
193 #[builder(into)]
194 pub background_tasks: Option<Toggle<BackgroundTasksConfig>>,
195 /// Attributes added to every span of the agent, replacing a standard
196 /// attribute of the same name. Keys other than the standard ones need the `otel` feature.
197 /// The builder takes any iterator of key and value pairs.
198 #[builder(with = |attributes: impl IntoIterator<Item = (impl Into<String>, impl Into<AttributeValue>)>| {
199 attributes.into_iter().map(|(key, value)| (key.into(), value.into())).collect()
200 })]
201 pub trace_attributes: Option<BTreeMap<String, AttributeValue>>,
202 /// OpenTelemetry baggage entries attached to the context for every invocation,
203 /// propagated to downstream services in the W3C `baggage` header;
204 /// needs the `otel` feature. The builder takes any iterator of key and value pairs.
205 #[builder(with = |entries: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>| {
206 entries.into_iter().map(|(key, value)| (key.into(), value.into())).collect()
207 })]
208 pub baggage_attributes: Option<BTreeMap<String, String>>,
209 /// Where sandbox-aware tools run commands and code and read and write files (`sandbox`).
210 /// `None` uses the shared
211 /// [`NotASandboxLocalEnvironment`](crate::sandbox::NotASandboxLocalEnvironment), the host
212 /// with no isolation. A configured sandbox's [`get_tools`](Sandbox::get_tools) are
213 /// registered at initialization, except those whose name is already registered. The
214 /// builder's `sandbox(..)` takes a sandbox by value or as an `Arc`.
215 #[builder(with = |sandbox: impl crate::sandbox::IntoSandbox| sandbox.into_sandbox())]
216 pub sandbox: Option<Arc<dyn Sandbox>>,
217 /// Default storage backend for agent subsystems (`storage`). Subsystems without their own
218 /// storage (the session manager, the context manager's archive) resolve from it, each under
219 /// its own namespace; a subsystem's own storage always wins. The builder's `storage(..)`
220 /// takes a storage by value or as an `Arc`.
221 #[builder(with = |storage: impl crate::storage::IntoStorage| storage.into_storage())]
222 pub storage: Option<Arc<dyn Storage>>,
223 /// Saves and restores the agent's session. With one attached, the agent's
224 /// session id is the manager's and the model receives it in its
225 /// [`AgentMetadata`](crate::types::AgentMetadata).
226 pub session_manager: Option<SessionManager>,
227 /// Cross-session memory: a [`MemoryManager`](crate::memory::MemoryManager)
228 /// or a [`MemoryManagerConfig`](crate::memory::MemoryManagerConfig) the agent builds one from.
229 #[builder(into)]
230 pub memory_manager: Option<MemoryManagerSource>,
231}
232
233impl<S: agent_builder::State> AgentBuilder<S> {
234 /// Adds tools: any iterator of tools, agents, `Arc<dyn Tool>`s or nested lists
235 /// (`tools`). Mixed types go through [`tool_list!`](crate::tool_list).
236 pub fn tools(mut self, tools: impl IntoIterator<Item = impl Into<ToolSource>>) -> Self {
237 self.tools.extend(tools.into_iter().map(Into::into));
238 self
239 }
240
241 /// Adds plugins, by value or as `Arc`s (`plugins`).
242 pub fn plugins(mut self, plugins: impl IntoIterator<Item = impl Plugin>) -> Self {
243 self.plugins
244 .extend(plugins.into_iter().map(|plugin| Arc::new(plugin) as Arc<dyn Plugin>));
245 self
246 }
247
248 /// Adds intervention handlers of one type, by value or as `Arc`s (`interventions`). Add
249 /// handlers of different types with [`intervention`](Self::intervention), one at a time, or
250 /// as a list of `Arc<dyn InterventionHandler>`:
251 ///
252 /// ```
253 /// use std::sync::Arc;
254 ///
255 /// use strands::Agent;
256 /// use strands::interventions::InterventionHandler;
257 /// use strands::testing::MockModel;
258 /// use strands::vended_interventions::hitl::{HumanInTheLoop, HumanInTheLoopConfig};
259 ///
260 /// struct Audit;
261 ///
262 /// #[strands::async_trait]
263 /// impl InterventionHandler for Audit {
264 /// fn name(&self) -> &str {
265 /// "audit"
266 /// }
267 /// }
268 ///
269 /// let one_by_one = Agent::builder()
270 /// .model(MockModel::new())
271 /// .intervention(HumanInTheLoop::default())
272 /// .intervention(Audit)
273 /// .printer(false)
274 /// .build()?;
275 /// let shared: [Arc<dyn InterventionHandler>; 2] = [Arc::new(HumanInTheLoop::default()), Arc::new(Audit)];
276 /// let listed = Agent::builder().model(MockModel::new()).interventions(shared).printer(false).build()?;
277 /// # let _ = (one_by_one, listed);
278 /// # Ok::<(), strands::Error>(())
279 /// ```
280 pub fn interventions(mut self, handlers: impl IntoIterator<Item = impl InterventionHandler>) -> Self {
281 self.interventions.extend(
282 handlers
283 .into_iter()
284 .map(|handler| Arc::new(handler) as Arc<dyn InterventionHandler>),
285 );
286 self
287 }
288
289 /// Adds one intervention handler, by value or as an `Arc` (an `Arc<dyn InterventionHandler>`
290 /// included), after the ones already added.
291 pub fn intervention(mut self, handler: impl InterventionHandler) -> Self {
292 self.interventions.push(Arc::new(handler));
293 self
294 }
295
296 /// Sets the structured output schema from a type's `schemars` schema;
297 /// needs `schemars = "1"` in your dependencies.
298 pub fn structured_output_schema<T: SchemarsJsonSchema>(
299 self,
300 ) -> AgentBuilder<agent_builder::SetStructuredOutputSchema<S>>
301 where
302 S::StructuredOutputSchema: agent_builder::IsUnset,
303 {
304 self.structured_output_schema_json(schema_for::<T>())
305 }
306}
307
308impl<S: agent_builder::IsComplete> AgentBuilder<S> {
309 /// Builds the agent.
310 ///
311 /// # Errors
312 ///
313 /// The same errors as [`Agent::new`](crate::Agent::new).
314 pub fn build(self) -> crate::Result<crate::Agent> {
315 crate::Agent::new(self.into_config())
316 }
317}
318
319impl fmt::Debug for AgentConfig {
320 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
321 f.debug_struct("AgentConfig")
322 .field("model", &self.model)
323 .field("name", &self.name)
324 .field("id", &self.id)
325 .field("tools", &self.tools)
326 .finish_non_exhaustive()
327 }
328}
329
330/// Options for one invocation (`InvokeOptions`).
331///
332/// ```
333/// use strands::{InvokeOptions, InvokeLimits};
334///
335/// #[derive(serde::Deserialize, schemars::JsonSchema)]
336/// struct Summary { title: String }
337///
338/// let options = InvokeOptions {
339/// limits: Some(InvokeLimits { turns: Some(5), ..Default::default() }),
340/// ..Default::default()
341/// }
342/// .structured_output_schema::<Summary>();
343/// assert!(options.structured_output_schema.is_some());
344/// ```
345#[derive(Debug, Clone, Default, bon::Builder)]
346pub struct InvokeOptions {
347 /// JSON schema for this invocation's structured output, overriding the agent's.
348 /// The builder sets it from a type with
349 /// `structured_output_schema::<T>()`, or from JSON with `structured_output_schema_json(..)`.
350 #[builder(setters(name = structured_output_schema_json))]
351 pub structured_output_schema: Option<JsonSchema>,
352 /// Per-invocation state passed to hooks and tools and returned on the result.
353 pub invocation_state: Option<InvocationState>,
354 /// A signal from outside the agent that cancels the invocation, merged with the agent's own.
355 /// Its message and `after_current_tools` count like the agent's.
356 pub cancel_signal: Option<CancelSignal>,
357 /// Runs this call inside the request a hook event's or tool context's handle belongs to,
358 /// sharing its limits and usage.
359 pub invocation_context: Option<InvocationContext>,
360 /// Limits for the request this call starts (`limits`).
361 pub limits: Option<InvokeLimits>,
362}
363
364impl InvokeOptions {
365 /// Sets the structured output schema from a type's `schemars` schema.
366 #[must_use]
367 pub fn structured_output_schema<T: SchemarsJsonSchema>(mut self) -> Self {
368 self.structured_output_schema = Some(schema_for::<T>());
369 self
370 }
371}
372
373impl<S: invoke_options_builder::State> InvokeOptionsBuilder<S> {
374 /// Sets the structured output schema from a type's `schemars` schema.
375 pub fn structured_output_schema<T: SchemarsJsonSchema>(
376 self,
377 ) -> InvokeOptionsBuilder<invoke_options_builder::SetStructuredOutputSchema<S>>
378 where
379 S::StructuredOutputSchema: invoke_options_builder::IsUnset,
380 {
381 self.structured_output_schema_json(schema_for::<T>())
382 }
383}