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