Skip to main content

Module agent

Module agent 

Source
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).
AgentAsTool
An agent wrapped as a tool (AgentAsTool): the tool takes an input string, invokes the agent with it and returns the agent’s answer.
AgentAsToolOptions
Options for Agent::as_tool (AgentAsToolOptions).
AgentBuilder
Builds an Agent; the setters are the AgentConfig keys.
AgentConfig
Configuration for an Agent (AgentConfig).
AgentResult
The result of an agent invocation (AgentResult).
AgentStream
The stream of an agent invocation (agent.stream()): event records, ending with AgentStreamEvent::AgentResult. An invocation a BeforeInvocationEvent hook cancelled ends without that record; into_result returns the result either way.
DirectToolCallOptions
Options for a direct tool call (DirectToolCallOptions).
InvocationContext
Handle to the request an object belongs to (InvocationContext).
InvocationContextUsage
What the work in an InvocationContext has used (InvocationContextUsage): its turns and the token usage of every model call, nested and auxiliary calls included.
InvocationState
Per-invocation state threaded through hooks and tools for one agent invocation (InvocationState).
InvokeLimits
Limits for the request a top-level invoke or stream call starts (InvokeLimits).
InvokeOptions
Options for one invocation (InvokeOptions).
LocalAgent
The agent as sequential hook events and plugins see it (LocalAgent).
RefusedCall
An inner call that stopped for human input, from ToolAgent::call_tool_without_interrupts. Nothing records or registers its interrupts.
TakeSnapshotOptions
Which fields Agent::take_snapshot captures (TakeSnapshotOptions): the preset’s fields, plus include, minus exclude.
ToolAgent
The view of the agent that tools and per-tool hook events get.
ToolHandle
A registered tool, called directly rather than by the model (ToolHandle).

Enums§

InvokeArgs
The input of an agent invocation (InvokeArgs).
LimitKey
One of the InvokeLimits (keyof InvokeLimits).
ModelSource
The model an agent calls: a model instance, a router or a Bedrock model id.
SnapshotField
A field an agent snapshot can capture (SnapshotField).
SnapshotPreset
A named set of snapshot fields (SnapshotPreset).

Constants§

DELEGATION_DESCRIPTION_SUFFIX
Appended to a delegating tool’s description (DELEGATION_DESCRIPTION_SUFFIX).