Skip to main content

rig_agent/agent/
tool.rs

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