Expand description
The agent: Agent and its configuration, the invocation API and its result, the
per-invocation state, the request context, direct tool calls, agents as tools, and the agent
views: LocalAgent for sequential hooks and plugins, ToolAgent for tools and per-tool
hooks.
§Agent, tool and streaming
use futures::StreamExt;
use strands::{tool, Agent, AgentStreamEvent};
/// Get the current weather for a city.
#[tool]
async fn get_weather(
/// City name, for example "Seattle".
city: String,
) -> Result<String, strands::ToolError> {
Ok(format!("Sunny in {city}"))
}
#[tokio::main]
async fn main() -> Result<(), strands::Error> {
let mut agent = Agent::builder() // default model: Bedrock
.system_prompt("You are a concise assistant.")
.tools([GetWeather])
.build()?;
let result = agent.invoke("What's the weather in Seattle?").await?;
println!("{result}");
{
let mut stream = agent.stream("And in Lisbon?");
while let Some(event) = stream.next().await {
if let AgentStreamEvent::ModelStreamUpdate(update) = event? {
if let Some(text) = update.text_delta() {
print!("{text}");
}
}
}
}
agent.shutdown().await
}§Config struct
use strands::{Agent, AgentConfig};
let agent = Agent::new(AgentConfig {
model: Some(MockModel::new().into()), // any provider, such as an `AnthropicModel`
system_prompt: Some("You are a concise assistant.".into()),
..Default::default()
})?;§Tools with state
use std::sync::Arc;
use strands::{tools, Agent, ToolContext};
struct Inventory { db: Pool }
#[tools]
impl Inventory {
/// Look up stock for a product.
#[tool]
async fn check_stock(&self, #[tool(context)] ctx: &ToolContext, sku: String) -> Result<u32, strands::ToolError> {
let _ = ctx.agent().app_state().get::<String>("region");
Ok(self.db.stock(&sku).await?)
}
}
let inventory = Arc::new(Inventory { db });
let agent = Agent::builder()
.tools(inventory.tools())
.build()?;§Hooks, structured output and cancellation
use strands::hooks::BeforeToolCallEvent;
use strands::{Agent, CancelOptions, InvokeOptions};
let mut agent = Agent::builder()
.build()?;
agent.add_hook(|event: &mut BeforeToolCallEvent| {
if event.tool_use().name == "shell" {
event.set_cancel("shell is disabled");
}
});
agent.add_async_hook::<BeforeToolCallEvent>(|event| Box::pin(async move {
audit_log(event.tool_use()).await;
}));
#[derive(serde::Deserialize, schemars::JsonSchema)]
struct Summary { title: String, points: Vec<String> }
let summary: Summary = agent
.invoke_with("Summarize this thread", InvokeOptions::default().structured_output_schema::<Summary>())
.await?
.structured_output()?;
let cancel = agent.cancel_handle();
tokio::spawn(async move {
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
cancel.cancel(CancelOptions::default());
});Structs§
- Agent
- An agent: a model, tools and a conversation, run by the agent loop (
Agent). - Agent
AsTool - An agent wrapped as a tool (
AgentAsTool): the tool takes aninputstring, invokes the agent with it and returns the agent’s answer. - Agent
AsTool Options - Options for
Agent::as_tool(AgentAsToolOptions). - Agent
Builder - Builds an
Agent; the setters are theAgentConfigkeys. - Agent
Config - Configuration for an
Agent(AgentConfig). - Agent
Result - The result of an agent invocation (
AgentResult). - Agent
Stream - The stream of an agent invocation (
agent.stream()): event records, ending withAgentStreamEvent::AgentResult. An invocation aBeforeInvocationEventhook cancelled ends without that record;into_resultreturns the result either way. - Direct
Tool Call Options - Options for a direct tool call (
DirectToolCallOptions). - Invocation
Context - Handle to the request an object belongs to (
InvocationContext). - Invocation
Context Usage - What the work in an
InvocationContexthas used (InvocationContextUsage): its turns and the token usage of every model call, nested and auxiliary calls included. - Invocation
State - Per-invocation state threaded through hooks and tools for one agent invocation
(
InvocationState). - Invoke
Limits - Limits for the request a top-level
invokeorstreamcall starts (InvokeLimits). - Invoke
Options - Options for one invocation (
InvokeOptions). - Local
Agent - The agent as sequential hook events and plugins see it (
LocalAgent). - Refused
Call - An inner call that stopped for human input, from
ToolAgent::call_tool_without_interrupts. Nothing records or registers its interrupts. - Take
Snapshot Options - Which fields
Agent::take_snapshotcaptures (TakeSnapshotOptions): the preset’s fields, plusinclude, minusexclude. - Tool
Agent - The view of the agent that tools and per-tool hook events get.
- Tool
Handle - A registered tool, called directly rather than by the model (
ToolHandle).
Enums§
- Invoke
Args - The input of an agent invocation (
InvokeArgs). - Limit
Key - One of the
InvokeLimits(keyof InvokeLimits). - Model
Source - The model an agent calls: a model instance, a router or a Bedrock model id.
- Snapshot
Field - A field an agent snapshot can capture (
SnapshotField). - Snapshot
Preset - A named set of snapshot fields (
SnapshotPreset).
Constants§
- DELEGATION_
DESCRIPTION_ SUFFIX - Appended to a delegating tool’s description (
DELEGATION_DESCRIPTION_SUFFIX).