1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
use super::tool::Tool;
use crate::parsing::{find_yaml, ExtractionError};
use crate::prompt::PromptTemplate;
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Default)]
pub struct ToolCollection {
    tools: Vec<Box<dyn Tool>>,
}

#[derive(Error, Debug)]
pub enum ToolUseError {
    #[error("Tool not found")]
    ToolNotFound,
    #[error("You must output YAML: {0}")]
    InvalidYaml(#[from] ExtractionError),
    #[error("Invalid format: {0}")]
    InvalidFormat(#[from] serde_yaml::Error),
    #[error("You must output exactly one tool invocation")]
    InvalidInvocation,
    #[error("Tool invocation failed: {0}")]
    ToolInvocationFailed(String),
}

impl ToolCollection {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn add_tool<T: Tool + 'static>(&mut self, tool: T) {
        self.tools.push(Box::new(tool));
    }

    pub fn invoke(
        &self,
        name: &str,
        input: &serde_yaml::Value,
    ) -> Result<serde_yaml::Value, ToolUseError> {
        let tool = self
            .tools
            .iter()
            .find(|t| t.matches(name))
            .ok_or(ToolUseError::ToolNotFound)?;
        tool.invoke(input.clone())
    }

    /// Process chat input and execute the appropriate tool.
    ///
    /// The input string should contain a YAML block describing the tool invocation.
    /// The YAML block should have a `command` field and an `input` field.
    ///
    /// # Errors
    ///
    /// Returns an `OpaqueError` variant if the input is not a valid YAML or
    /// if the specified tool is not found.
    pub fn process_chat_input(&self, data: &str) -> Result<String, ToolUseError> {
        let tool_invocations: Vec<ToolInvocationInput> = find_yaml::<ToolInvocationInput>(data)?;
        if tool_invocations.len() != 1 {
            return Err(ToolUseError::InvalidInvocation);
        }
        let output = self.invoke(&tool_invocations[0].command, &tool_invocations[0].input)?;
        Ok(serde_yaml::to_string(&output).unwrap())
    }

    /// Generate a YAML-formatted string describing the available tools.
    pub fn describe(&self) -> String {
        let des: Vec<_> = self.tools.iter().map(|t| t.description()).collect();
        serde_yaml::to_string(&des).unwrap()
    }

    /// Generate a prompt template for the tool collection. Combine it with a normal prompt template to perform your task.
    pub fn to_prompt_template(&self) -> PromptTemplate {
        PromptTemplate::combine(vec![
            PromptTemplate::static_string(include_str!("./tool_prompt_prefix.txt").to_string()),
            PromptTemplate::static_string(self.describe()),
            PromptTemplate::static_string("\n\n"),
        ])
    }
}

#[derive(Serialize, Deserialize, Debug)]
struct ToolInvocationInput {
    command: String,
    input: serde_yaml::Value,
}