Skip to main content

rig_agent/agent/
tool.rs

1//! Conversion of agents into dynamically named tools.
2//!
3//! ```
4//! use rig_agent::{Agent, core::message::EmptyToolName, tool::DynamicTool};
5//! fn delegate(agent: Agent) -> Result<DynamicTool, EmptyToolName> {
6//!     agent.into_tool()
7//! }
8//! ```
9
10use std::sync::Arc;
11
12use crate::{
13    agent::Agent,
14    tool::{DynamicTool, ToolExecutionError, ToolOutput},
15};
16use rig_core::message::{EmptyToolName, ToolName};
17use schemars::{JsonSchema, schema_for};
18use serde::{Deserialize, Serialize};
19use serde_json::json;
20
21#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
22struct AgentToolArgs {
23    /// The prompt for the agent to call.
24    prompt: String,
25}
26
27const DEFAULT_AGENT_TOOL_NAME: &str = "agent_tool";
28
29impl Agent {
30    /// Convert this agent into a runtime-defined tool.
31    ///
32    /// Uses the configured name or `agent_tool`. The tool accepts a JSON `prompt`
33    /// string and inherits dispatch context. Invalid arguments and failed runs
34    /// become tool execution errors; successful output is returned as text.
35    ///
36    /// Returns [`EmptyToolName`] when the configured name is empty.
37    pub fn into_tool(self) -> Result<DynamicTool, EmptyToolName> {
38        let name = ToolName::new(
39            self.config
40                .name
41                .clone()
42                .unwrap_or_else(|| DEFAULT_AGENT_TOOL_NAME.to_string()),
43        )?;
44        let description = format!(
45            "
46            Prompt a sub-agent to do a task for you.
47
48            Agent name: {name}
49            Agent description: {description}
50            Agent system prompt: {sysprompt}
51            ",
52            name = name,
53            description = self.config.description.as_deref().unwrap_or_default(),
54            sysprompt = self.config.preamble.as_deref().unwrap_or_default()
55        );
56        let parameters = json!(schema_for!(AgentToolArgs));
57        let agent = Arc::new(self);
58
59        Ok(DynamicTool::new_with_context(
60            name,
61            description,
62            parameters,
63            move |context, args| {
64                let agent = Arc::clone(&agent);
65                let inherited_context = context.for_dispatch();
66                Box::pin(async move {
67                    let args: AgentToolArgs = serde_json::from_value(args).map_err(|error| {
68                        ToolExecutionError::invalid_args(format!(
69                            "failed to parse agent tool arguments: {error}"
70                        ))
71                        .with_source(error)
72                    })?;
73                    agent
74                        .prompt(args.prompt)
75                        .tool_context(inherited_context)
76                        .await
77                        .map(|response| ToolOutput::text(response.output()))
78                        .map_err(ToolExecutionError::from_error)
79                })
80            },
81        ))
82    }
83}
84
85impl TryFrom<Agent> for DynamicTool {
86    type Error = EmptyToolName;
87
88    fn try_from(agent: Agent) -> Result<Self, EmptyToolName> {
89        agent.into_tool()
90    }
91}
92
93#[cfg(test)]
94mod tests;