Skip to main content

strands/agent/
tool_caller.rs

1//! Direct tool calls: `agent.tool("name").invoke(input)`.
2
3use std::collections::VecDeque;
4use std::sync::Arc;
5
6use futures::StreamExt;
7
8use super::agent::{Agent, PendingCleanup};
9use super::invocation_state::InvocationState;
10use super::tool_pipeline::ToolCallPipeline;
11use crate::error::Result;
12use crate::interrupt::Interrupt;
13use crate::models::BoxStream;
14use crate::tools::{ToolContext, ToolOutcome, ToolStreamItem, create_error_result};
15use crate::types::{ContentBlock, JsonValue, Message, Role, ToolResultBlock, ToolUse, ToolUseBlock};
16
17/// Options for a direct tool call (`DirectToolCallOptions`).
18#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, bon::Builder)]
19pub struct DirectToolCallOptions {
20    /// Record the call and its result in the agent's history. Defaults to `true`.
21    pub record_direct_tool_call: Option<bool>,
22}
23
24/// A registered tool, called directly rather than by the model (`ToolHandle`).
25///
26/// The name resolves like the model's tool names: an exact match, then `_` for `-`, then
27/// case-insensitively. A recorded call appends the tool use, its result and
28/// `agent.tool.<name> was called.` to history and fires `MessageAddedEvent` for each. Direct
29/// calls run the tool alone: no tool hooks fire, and an interrupt becomes an error result.
30///
31/// ```
32/// use serde_json::json;
33/// use strands::Agent;
34/// use strands::testing::MockModel;
35/// use strands::tools::FunctionTool;
36///
37/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
38/// let add = FunctionTool::builder("add", "Adds two numbers").callback(|input, _ctx| async move {
39///     Ok(json!(input["a"].as_i64().unwrap_or(0) + input["b"].as_i64().unwrap_or(0)))
40/// });
41/// let mut agent = Agent::builder().model(MockModel::new()).tools([add]).printer(false).build()?;
42/// let result = agent.tool("add").invoke(json!({"a": 5, "b": 3})).await?;
43/// assert_eq!(serde_json::to_value(&result.content)?, json!([{"text": "8"}]));
44/// assert_eq!(agent.messages().len(), 3);
45/// # Ok::<(), strands::Error>(())
46/// # }).unwrap();
47/// ```
48#[derive(Debug)]
49pub struct ToolHandle<'a> {
50    agent: &'a mut Agent,
51    name: String,
52}
53
54impl Agent {
55    /// A handle that calls the named tool directly (`agent.tool.<name>`).
56    pub fn tool(&mut self, name: impl Into<String>) -> ToolHandle<'_> {
57        ToolHandle {
58            agent: self,
59            name: name.into(),
60        }
61    }
62}
63
64impl<'a> ToolHandle<'a> {
65    /// Calls the tool and returns its result (`invoke`).
66    ///
67    /// # Errors
68    ///
69    /// [`ToolNotFoundError`](crate::ToolNotFoundError) when no tool matches the name.
70    pub async fn invoke(self, input: JsonValue) -> Result<ToolResultBlock> {
71        self.invoke_with(input, DirectToolCallOptions::default()).await
72    }
73
74    /// Calls the tool with options.
75    ///
76    /// # Errors
77    ///
78    /// The same as [`invoke`](Self::invoke).
79    pub async fn invoke_with(self, input: JsonValue, options: DirectToolCallOptions) -> Result<ToolResultBlock> {
80        let mut stream = self.stream_with(input, options);
81        let mut result = None;
82        while let Some(item) = stream.next().await {
83            if let ToolStreamItem::Outcome(ToolOutcome::Result(block)) = item? {
84                result = Some(block);
85            }
86        }
87        result.ok_or_else(|| crate::Error::other("direct tool call ended without a result"))
88    }
89
90    /// Streams the tool's progress events, ending with its result (`stream`).
91    pub fn stream(self, input: JsonValue) -> BoxStream<'a, Result<ToolStreamItem>> {
92        self.stream_with(input, DirectToolCallOptions::default())
93    }
94
95    /// Streams the tool with options.
96    pub fn stream_with(
97        self,
98        input: JsonValue,
99        options: DirectToolCallOptions,
100    ) -> BoxStream<'a, Result<ToolStreamItem>> {
101        let ToolHandle { agent, name } = self;
102        Box::pin(async_stream::try_stream! {
103            let tool = agent.local.tool_registry().resolve(&name)?.clone();
104            let tool_use_id = format!("tooluse_{}", uuid::Uuid::new_v4());
105            let tool_use = ToolUse::new(tool.name(), tool_use_id.clone(), input);
106            let pipeline = ToolCallPipeline::new(
107                agent.local.hooks().clone(),
108                agent.local.middleware().clone(),
109                InvocationState::new(),
110                agent.local.meter().clone(),
111                agent.local.tracer().clone(),
112            );
113            let view = agent.local.tool_agent().with_pipeline(Arc::new(pipeline));
114            let context = ToolContext::new(tool_use.clone(), view, InvocationState::new())
115                .with_interrupt(Arc::new(|params: &crate::types::InterruptParams| {
116                    Err(Interrupt::new("direct", params.name.clone()).into())
117                }));
118            let mut tool_stream = tool.stream(context);
119            let mut result = None;
120            while let Some(item) = tool_stream.next().await {
121                match item {
122                    ToolStreamItem::Event(event) => yield ToolStreamItem::Event(event),
123                    ToolStreamItem::Outcome(ToolOutcome::Result(block)) => {
124                        result = Some(block);
125                        break;
126                    }
127                    ToolStreamItem::Outcome(ToolOutcome::Interrupt(_)) => {
128                        result = Some(create_error_result(
129                            "Interrupts are not supported in direct tool calls",
130                            tool_use_id.clone(),
131                        ));
132                        break;
133                    }
134                }
135            }
136            let result = result.unwrap_or_else(|| super::tool_agent::no_result(&tool_use));
137            if options.record_direct_tool_call.unwrap_or(true) {
138                agent.record_direct_tool_call(&tool_use, &result).await?;
139            }
140            yield ToolStreamItem::Outcome(ToolOutcome::Result(result));
141        })
142    }
143}
144
145impl Agent {
146    async fn record_direct_tool_call(&mut self, tool_use: &ToolUse, result: &ToolResultBlock) -> Result<()> {
147        let block = ToolUseBlock::new(
148            tool_use.name.clone(),
149            tool_use.tool_use_id.clone(),
150            tool_use.input.clone(),
151        );
152        let messages = VecDeque::from([
153            Message::new(Role::Assistant, vec![ContentBlock::ToolUse(block)]),
154            Message::new(Role::User, vec![ContentBlock::ToolResult(result.clone())]),
155            Message::new(
156                Role::Assistant,
157                vec![ContentBlock::text(format!("agent.tool.{} was called.", tool_use.name))],
158            ),
159        ]);
160        self.run_pending_cleanup().await;
161        self.local.messages_mut().extend(messages.iter().cloned());
162        self.pending_cleanup = Some(PendingCleanup {
163            messages,
164            message_progress: Arc::default(),
165            after_invocation: None,
166            invocation_state: InvocationState::new(),
167            invocation_context: None,
168        });
169        self.drain_pending_cleanup().await
170    }
171}