Skip to main content

langchain_rust/agent/open_ai_tools/
agent.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use serde_json::json;
6
7use crate::{
8    agent::{Agent, AgentError},
9    chain::Chain,
10    fmt_message, fmt_placeholder, fmt_template, message_formatter,
11    prompt::{HumanMessagePromptTemplate, MessageFormatterStruct, PromptArgs},
12    schemas::{
13        agent::{AgentAction, AgentEvent, AgentFinish, LogTools},
14        messages::Message,
15        FunctionCallResponse,
16    },
17    template_jinja2,
18    tools::Tool,
19};
20
21pub struct OpenAiToolAgent {
22    pub(crate) chain: Box<dyn Chain>,
23    pub(crate) tools: Vec<Arc<dyn Tool>>,
24}
25
26impl OpenAiToolAgent {
27    pub fn create_prompt(prefix: &str) -> Result<MessageFormatterStruct, AgentError> {
28        let prompt = message_formatter![
29            fmt_message!(Message::new_system_message(prefix)),
30            fmt_placeholder!("chat_history"),
31            fmt_template!(HumanMessagePromptTemplate::new(template_jinja2!(
32                "{{input}}",
33                "input"
34            ))),
35            fmt_placeholder!("agent_scratchpad")
36        ];
37
38        Ok(prompt)
39    }
40
41    fn construct_scratchpad(
42        &self,
43        intermediate_steps: &[(AgentAction, String)],
44    ) -> Result<Vec<Message>, AgentError> {
45        let mut thoughts: Vec<Message> = Vec::new();
46
47        let mut tools_ai_message_seen: HashMap<String, ()> = HashMap::default();
48        for (action, observation) in intermediate_steps {
49            // Deserialize directly and embed in method calls to streamline code.
50            // Extract the tool ID and tool calls from the log.
51            let LogTools { tool_id, tools } = serde_json::from_str(&action.log)?;
52            let tools_vec: Vec<FunctionCallResponse> = serde_json::from_str(&tools)?;
53
54            // one action can trigger multiple observations.  But make sure we add it to
55            // the scratchpad before the related observations.  There can also be multiple
56            // different actions in the same thought chain.
57            if tools_ai_message_seen.insert(tools, ()).is_none() {
58                thoughts.push(Message::new_ai_message("").with_tool_calls(json!(tools_vec)));
59            }
60
61            // Add a tool message for each observation. Observation is the ouput of the tool call.
62            // tool_id is the id of the tool.
63            thoughts.push(Message::new_tool_message(observation, tool_id));
64        }
65
66        Ok(thoughts)
67    }
68}
69
70#[async_trait]
71impl Agent for OpenAiToolAgent {
72    async fn plan(
73        &self,
74        intermediate_steps: &[(AgentAction, String)],
75        inputs: PromptArgs,
76    ) -> Result<AgentEvent, AgentError> {
77        let mut inputs = inputs.clone();
78        let scratchpad = self.construct_scratchpad(intermediate_steps)?;
79        inputs.insert("agent_scratchpad".to_string(), json!(scratchpad));
80        let output = self.chain.call(inputs).await?.generation;
81        match serde_json::from_str::<Vec<FunctionCallResponse>>(&output) {
82            Ok(tools) => {
83                let mut actions: Vec<AgentAction> = Vec::new();
84                for tool in tools {
85                    //Log tools will be send as log
86                    let log: LogTools = LogTools {
87                        tool_id: tool.id.clone(),
88                        tools: output.clone(), //We send the complete tools ouput, we will need it in
89                                               //the open ai call
90                    };
91                    actions.push(AgentAction {
92                        tool: tool.function.name.clone(),
93                        tool_input: tool.function.arguments.clone(),
94                        log: serde_json::to_string(&log)?, //We send this as string to minimise changes
95                    });
96                }
97                return Ok(AgentEvent::Action(actions));
98            }
99            Err(_) => return Ok(AgentEvent::Finish(AgentFinish { output })),
100        }
101    }
102
103    fn get_tools(&self) -> Vec<Arc<dyn Tool>> {
104        self.tools.clone()
105    }
106}