Skip to main content

tiny_agent_loop/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::{iter::once, marker::PhantomData, ops::ControlFlow};
4
5use async_openai::{
6    Client,
7    config::Config,
8    error::OpenAIError,
9    types::chat::{
10        ChatCompletionMessageToolCall, ChatCompletionMessageToolCalls,
11        ChatCompletionRequestAssistantMessage, ChatCompletionRequestAssistantMessageContent,
12        ChatCompletionRequestAssistantMessageContentPart,
13        ChatCompletionRequestDeveloperMessageContent,
14        ChatCompletionRequestDeveloperMessageContentPart, ChatCompletionRequestMessage,
15        ChatCompletionRequestSystemMessageContent, ChatCompletionRequestSystemMessageContentPart,
16        ChatCompletionRequestToolMessage, ChatCompletionRequestToolMessageContent,
17        ChatCompletionRequestToolMessageContentPart, ChatCompletionRequestUserMessage,
18        ChatCompletionRequestUserMessageContent, ChatCompletionRequestUserMessageContentPart,
19        ChatCompletionTool, ChatCompletionTools, CreateChatCompletionRequestArgs, FinishReason,
20        FunctionObjectArgs, ResponseFormat, ResponseFormatJsonSchema,
21    },
22};
23use futures_util::StreamExt;
24use log::{debug, trace};
25use schemars::{JsonSchema, generate::SchemaSettings, transform::RestrictFormats};
26use serde::de::DeserializeOwned;
27use serde_json::Value;
28
29macro_rules! impl_tools {
30    ($($name:ident),*) => {
31        impl<R, $($name: Tool<R>),*> Tools<R> for ($($name,)*) {
32            #[allow(non_snake_case)]
33            fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
34                where R: 'r
35            {
36                let ($($name,)*) = self;
37
38                [
39                    $($name as &mut dyn Tool<R>,)*
40                ].into_iter()
41            }
42        }
43    }
44}
45
46impl_tools!(T0);
47impl_tools!(T0, T1);
48impl_tools!(T0, T1, T2);
49impl_tools!(T0, T1, T2, T3);
50impl_tools!(T0, T1, T2, T3, T4);
51impl_tools!(T0, T1, T2, T3, T4, T5);
52impl_tools!(T0, T1, T2, T3, T4, T5, T6);
53impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7);
54impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
55impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
56impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
57impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
58impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
59impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
60impl_tools!(
61    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
62);
63impl_tools!(
64    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
65);
66
67impl<
68    D: JsonSchema + DeserializeOwned,
69    R,
70    Fut: Future<Output = ControlFlow<R, String>>,
71    F: FnMut(D) -> Fut,
72> Tools<R> for FnTool<D, R, Fut, F>
73{
74    fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
75    where
76        R: 'r,
77    {
78        once(self as &mut dyn Tool<R>)
79    }
80}
81
82pub trait Tools<R> {
83    fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
84    where
85        R: 'r;
86}
87
88pub trait Tool<R> {
89    /// Returns the name of the tool. May not change between calls.
90    fn name(&self) -> &str;
91
92    /// The description of the tool, provided to the LLM.
93    fn description(&self) -> &str;
94
95    /// The JSON schema of the tool parameters.
96    fn parameter_schema(&self) -> Value;
97
98    /// Invokes the tool with `data` as the provided parameters.
99    /// It is assumed that the LLM ensures that the parameters match the JSON schema.
100    fn invoke<'lt>(
101        &'lt mut self,
102        data: &str,
103    ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt>;
104}
105
106struct FnTool<D, R, Fut, F> {
107    name: &'static str,
108    description: &'static str,
109    invoke: F,
110    _phantom: PhantomData<(fn(D) -> R, Fut)>,
111}
112
113pub fn tool<
114    'a,
115    D: JsonSchema + DeserializeOwned,
116    R,
117    Fut: Future<Output = ControlFlow<R, String>>,
118    F: FnMut(D) -> Fut,
119>(
120    name: &'static str,
121    description: &'static str,
122    invoke: F,
123) -> impl Tool<R> {
124    FnTool {
125        name,
126        description,
127        invoke,
128        _phantom: PhantomData,
129    }
130}
131
132impl<
133    D: JsonSchema + DeserializeOwned,
134    R,
135    Fut: Future<Output = ControlFlow<R, String>>,
136    F: FnMut(D) -> Fut,
137> Tool<R> for FnTool<D, R, Fut, F>
138{
139    fn name(&self) -> &str {
140        self.name
141    }
142
143    fn description(&self) -> &str {
144        self.description
145    }
146
147    fn parameter_schema(&self) -> Value {
148        make_schema::<D>()
149    }
150
151    fn invoke<'lt>(
152        &'lt mut self,
153        data: &str,
154    ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt> {
155        let args = serde_json::from_str::<D>(data).unwrap();
156        Box::new((self.invoke)(args)) as Box<dyn Future<Output = ControlFlow<R, String>>>
157    }
158}
159
160fn make_schema<D: JsonSchema>() -> Value {
161    let schema = SchemaSettings::draft2020_12()
162        .with_transform(RestrictFormats::default())
163        .with(|s| s.inline_subschemas = true)
164        .into_generator()
165        .into_root_schema_for::<D>();
166
167    serde_json::to_value(&schema).unwrap()
168}
169
170pub struct FinishHandler<R> {
171    finish: Box<dyn FnMut() -> Box<dyn Future<Output = ControlFlow<R, String>>>>,
172}
173
174impl<R> FinishHandler<R> {
175    fn invoke(&mut self) -> Box<dyn Future<Output = ControlFlow<R, String>>> {
176        (self.finish)()
177    }
178}
179
180impl<R, Fut: Future<Output = ControlFlow<R, String>> + 'static, F: FnMut() -> Fut + 'static> From<F>
181    for FinishHandler<R>
182{
183    fn from(mut value: F) -> Self {
184        Self {
185            finish: Box::new(move || Box::new((value)())),
186        }
187    }
188}
189
190pub struct Agent<T, R> {
191    tools: T,
192    listen_content: Option<Box<dyn Fn(&str)>>,
193    listen_tool_call: Option<Box<dyn Fn(&str)>>,
194    _phantom: PhantomData<R>,
195    finish: FinishHandler<R>,
196    model: String,
197}
198
199impl<R, T: Tools<R>> Agent<T, R> {
200    /// Creates a new agent with the provided `tools`.
201    ///
202    /// `finish` is invoked when the LLM finishes without a tool call.
203    /// When `ControlFlow::Break` is returned, the loop will terminate with the provided return value.
204    /// When `ControlFlow::Continue(message)` is returned, the loop continues with the returned message appended to the chat history.
205    pub fn new(model: impl Into<String>, tools: T, finish: FinishHandler<R>) -> Self {
206        Self {
207            tools,
208            finish,
209            listen_content: None,
210            listen_tool_call: None,
211            _phantom: PhantomData,
212            model: model.into(),
213        }
214    }
215
216    /// Adds a listener that is invoked when streamed message content is available.
217    /// This is intended for debugging purposes only.
218    pub fn with_content_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
219        self.listen_content = Some(listener);
220        self
221    }
222
223    /// Adds a listener that is invoked when tool calling content is available.
224    /// This is intended for debugging purposes only.
225    /// Tools are called automatically.
226    pub fn with_tool_call_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
227        self.listen_tool_call = Some(listener);
228        self
229    }
230
231    /// Convenience function that calls [`Self::start_session`] followed by [`Session::run`].
232    /// 
233    /// See [`Session::run`].
234    pub async fn run<C: Config>(&mut self, client: &Client<C>, prompt: &str) -> R {
235        self.start_session(prompt).run(client).await
236    }
237
238    /// Start a new chat session with the provided prompt.
239    ///
240    /// Keeps a reference to the agent rather than consuming it, such that the agent can be re-used later.
241    pub fn start_session<'agent>(
242        &'agent mut self,
243        prompt: &str,
244    ) -> Session<&'agent mut Agent<T, R>, T, R> {
245        Session {
246            agent: self,
247            messages: vec![ChatCompletionRequestUserMessage::from(prompt).into()],
248            _phantom: PhantomData,
249        }
250    }
251
252    /// Start a new chat session with the provided prompt.
253    ///
254    /// Consumes the [`Agent`], creating a session without lifetimes.
255    pub fn into_session(self, prompt: &str) -> Session<Agent<T, R>, T, R> {
256        Session {
257            agent: self,
258            messages: vec![ChatCompletionRequestUserMessage::from(prompt).into()],
259            _phantom: PhantomData,
260        }
261    }
262}
263
264impl<T, R> AsMut<Agent<T, R>> for Agent<T, R> {
265    fn as_mut(&mut self) -> &mut Agent<T, R> {
266        self
267    }
268}
269
270pub struct Session<A, T, R> {
271    agent: A,
272    messages: Vec<ChatCompletionRequestMessage>,
273    _phantom: PhantomData<(R, T)>,
274}
275
276impl<R, T: Tools<R>, A: AsMut<Agent<T, R>>> Session<A, T, R> {
277    /// Append an additional message to the chat.
278    pub fn add_message(
279        &mut self,
280        message: impl Into<ChatCompletionRequestUserMessage>,
281    ) -> &mut Self {
282        self.messages.push(message.into().into());
283        self
284    }
285
286    /// Runs the agent loop. If tools were provided, they may be called.
287    ///
288    /// Terminates when a tool returns ControlFlow::Break.
289    ///
290    /// It is assumed that any single message or tool response always fits in the context window fully.
291    /// If this is not the case, this function may crash.
292    pub async fn run<C: Config>(&mut self, client: &Client<C>) -> R {
293        loop {
294            let tools = self
295                .agent
296                .as_mut()
297                .tools
298                .iter()
299                .map(|tool| {
300                    ChatCompletionTools::Function(ChatCompletionTool {
301                        function: FunctionObjectArgs::default()
302                            .name(tool.name())
303                            .description(tool.description())
304                            .parameters(tool.parameter_schema())
305                            .build()
306                            .unwrap(),
307                    })
308                })
309                .collect::<Vec<_>>();
310
311            let request = CreateChatCompletionRequestArgs::default()
312                .messages(self.messages.clone())
313                .tools(tools)
314                .model(&self.agent.as_mut().model)
315                .build()
316                .unwrap();
317
318            let mut stream = client.chat().create_stream(request).await.unwrap();
319            let mut tool_calls = Vec::new();
320            let mut execution_results = Vec::new();
321
322            while let Some(result) = stream.next().await {
323                let response = match result {
324                    Ok(response) => response,
325                    Err(OpenAIError::JSONDeserialize(e, json)) => {
326                        let json: Value = serde_json::from_str(&json).unwrap();
327                        if let Some(err) = json.get("error")
328                            && let Some(ty) = err.get("type")
329                            && let Some(ty) = ty.as_str()
330                            && ty == "exceed_context_size_error"
331                        {
332                            // When we run out of context, we summarize older messages.
333                            // It is assumed that a single message will always fit the context size.
334                            let num_to_summarize = {
335                                // messages: Vec<async_openai::types::chat::ChatCompletionRequestMessage>
336                                let total_characters =
337                                    self.messages.iter().map(get_message_len).sum::<usize>();
338                                let min_to_summarize = total_characters / 2;
339                                let mut running_sum = 0;
340                                self.messages
341                                    .iter()
342                                    .enumerate()
343                                    .take_while(|(n, m)| {
344                                        // 1. Ensure we leave a buffer of recent messages (at least 3)
345                                        // 2. Ensure we don't exceed the target summarization length
346
347                                        let limit = self.messages.len().saturating_sub(3).max(1);
348                                        let content_len = get_message_len(m);
349
350                                        // We continue taking messages as long as:
351                                        // We haven't reached the index limit AND we haven't reached the char limit
352                                        if *n < limit && running_sum < min_to_summarize {
353                                            running_sum += content_len;
354                                            true
355                                        } else {
356                                            false
357                                        }
358                                    })
359                                    .count()
360                            };
361                            let mut messages_to_summarize =
362                                self.messages.drain(..num_to_summarize).collect::<Vec<_>>();
363                            debug!(
364                                "Context size exceeded ({err:?}), attempting summary of messages: {messages_to_summarize:#?}."
365                            );
366
367                            messages_to_summarize.push(
368                                ChatCompletionRequestUserMessage::from(include_str!("summary.txt"))
369                                    .into(),
370                            );
371
372                            // TODO: This will panic if there is just a single message left that doesn't fit the context window.
373                            let request = CreateChatCompletionRequestArgs::default()
374                                .messages(messages_to_summarize)
375                                .model(&self.agent.as_mut().model)
376                                .build()
377                                .unwrap();
378                            let response = client.chat().create(request).await.unwrap();
379                            trace!("Summarized to: {response:#?}");
380                            for (index, choice) in response.choices.into_iter().enumerate() {
381                                self.messages.insert(
382                                    index,
383                                    ChatCompletionRequestUserMessage {
384                                        content: ChatCompletionRequestUserMessageContent::Text(
385                                            choice.message.content.unwrap(),
386                                        ),
387                                        ..Default::default()
388                                    }
389                                    .into(),
390                                );
391                            }
392
393                            break;
394                        } else {
395                            panic!("Unexpected error: failed to deserialize JSON: {e} in {json}");
396                        }
397                    }
398                    Err(e) => panic!("Unexpected error: {e}"),
399                };
400
401                for choice in response.choices {
402                    if let Some(content) = &choice.delta.content {
403                        trace!("Agent: {content:?}");
404                        if let Some(f) = &self.agent.as_mut().listen_content {
405                            (f)(&content);
406                        }
407                    }
408
409                    if let Some(tool_call_chunks) = choice.delta.tool_calls {
410                        for chunk in tool_call_chunks {
411                            let index = chunk.index as usize;
412                            if tool_calls.len() <= index {
413                                tool_calls.resize(
414                                    index + 1,
415                                    ChatCompletionMessageToolCall {
416                                        id: String::new(),
417                                        function: Default::default(),
418                                    },
419                                );
420                            }
421
422                            let tool_call = &mut tool_calls[index];
423                            if let Some(id) = chunk.id {
424                                tool_call.id = id;
425                            }
426
427                            if let Some(function_chunk) = chunk.function {
428                                if let Some(name) = function_chunk.name {
429                                    if let Some(f) = &self.agent.as_mut().listen_tool_call {
430                                        (f)(&name);
431                                    }
432
433                                    tool_call.function.name = name;
434                                }
435                                if let Some(arguments) = function_chunk.arguments {
436                                    if let Some(f) = &self.agent.as_mut().listen_tool_call {
437                                        (f)(&arguments);
438                                    }
439
440                                    tool_call.function.arguments.push_str(&arguments);
441                                }
442                            }
443                        }
444                    }
445
446                    match choice.finish_reason {
447                        Some(FinishReason::ToolCalls) => {
448                            for tool_call in tool_calls.iter() {
449                                let name = tool_call.function.name.clone();
450                                let tool_call_id = tool_call.id.clone();
451                                let result = {
452                                    debug!("Executing tool: {name}");
453                                    let tool = self
454                                        .agent
455                                        .as_mut()
456                                        .tools
457                                        .iter()
458                                        .find(|tool| tool.name() == name);
459
460                                    match tool {
461                                        Some(tool) => {
462                                            let future = tool.invoke(&tool_call.function.arguments);
463                                            let pinned = Box::into_pin(future);
464                                            pinned.await
465                                        }
466                                        None => ControlFlow::Continue(String::from(
467                                            "ERROR: Tool not found",
468                                        )),
469                                    }
470                                };
471
472                                match result {
473                                    ControlFlow::Continue(result) => {
474                                        execution_results.push((tool_call_id, result))
475                                    }
476                                    ControlFlow::Break(val) => return val,
477                                }
478                            }
479                        }
480                        Some(FinishReason::Stop | FinishReason::Length) => {
481                            let future = self.agent.as_mut().finish.invoke();
482                            let pinned = Box::into_pin(future);
483                            let result = pinned.await;
484
485                            match result {
486                                ControlFlow::Continue(result) => {
487                                    self.messages.push(
488                                        ChatCompletionRequestUserMessage::from(result).into(),
489                                    );
490                                }
491                                ControlFlow::Break(val) => return val,
492                            }
493                        }
494                        Some(reason) => panic!("Unexpected stop reason: {reason:?}"),
495                        _ => (),
496                    }
497                }
498            }
499
500            if !execution_results.is_empty() {
501                let assistant_tool_calls: Vec<ChatCompletionMessageToolCalls> =
502                    tool_calls.iter().map(|tc| tc.clone().into()).collect();
503                self.messages.push(
504                    ChatCompletionRequestAssistantMessage {
505                        content: None,
506                        tool_calls: Some(assistant_tool_calls),
507                        ..Default::default()
508                    }
509                    .into(),
510                );
511
512                for (tool_call_id, response) in execution_results {
513                    self.messages.push(
514                        ChatCompletionRequestToolMessage {
515                            content: response.to_string().into(),
516                            tool_call_id,
517                        }
518                        .into(),
519                    );
520                }
521            }
522        }
523    }
524}
525
526fn get_message_len(m: &ChatCompletionRequestMessage) -> usize {
527    match m {
528        ChatCompletionRequestMessage::System(m) => match &m.content {
529            ChatCompletionRequestSystemMessageContent::Text(t) => t.len(),
530            ChatCompletionRequestSystemMessageContent::Array(a) => a
531                .iter()
532                .map(|m| match m {
533                    ChatCompletionRequestSystemMessageContentPart::Text(t) => t.text.len(),
534                })
535                .sum::<usize>(),
536        },
537        ChatCompletionRequestMessage::User(m) => match &m.content {
538            ChatCompletionRequestUserMessageContent::Text(t) => t.len(),
539            ChatCompletionRequestUserMessageContent::Array(parts) => parts
540                .iter()
541                .map(|p| match p {
542                    ChatCompletionRequestUserMessageContentPart::Text(t) => t.text.len(),
543                    _ => 0,
544                })
545                .sum(),
546        },
547        ChatCompletionRequestMessage::Assistant(m) => m
548            .content
549            .as_ref()
550            .map(|c| match c {
551                ChatCompletionRequestAssistantMessageContent::Text(t) => t.len(),
552                ChatCompletionRequestAssistantMessageContent::Array(a) => a
553                    .iter()
554                    .map(|m| match m {
555                        ChatCompletionRequestAssistantMessageContentPart::Text(t) => t.text.len(),
556                        ChatCompletionRequestAssistantMessageContentPart::Refusal(_) => 0,
557                    })
558                    .sum::<usize>(),
559            })
560            .unwrap_or(0),
561        ChatCompletionRequestMessage::Tool(m) => match &m.content {
562            ChatCompletionRequestToolMessageContent::Text(t) => t.len(),
563            ChatCompletionRequestToolMessageContent::Array(a) => a
564                .iter()
565                .map(|m| match m {
566                    ChatCompletionRequestToolMessageContentPart::Text(t) => t.text.len(),
567                })
568                .sum::<usize>(),
569        },
570        ChatCompletionRequestMessage::Function(m) => {
571            m.content.as_ref().map(|c| c.len()).unwrap_or(0)
572        }
573        ChatCompletionRequestMessage::Developer(m) => match &m.content {
574            ChatCompletionRequestDeveloperMessageContent::Text(t) => t.len(),
575            ChatCompletionRequestDeveloperMessageContent::Array(a) => a
576                .iter()
577                .map(|m| match m {
578                    ChatCompletionRequestDeveloperMessageContentPart::Text(t) => t.text.len(),
579                })
580                .sum::<usize>(),
581        },
582    }
583}
584
585/// Invokes the LLM once, generating an output object directly.
586/// No tool calls are supported.
587pub async fn one_shot<C: Config, R: JsonSchema + DeserializeOwned>(
588    client: &Client<C>,
589    model: &str,
590    prompt: &str,
591) -> R {
592    let request = CreateChatCompletionRequestArgs::default()
593        .messages(vec![ChatCompletionRequestUserMessage::from(prompt).into()])
594        .model(model)
595        .response_format(ResponseFormat::JsonSchema {
596            json_schema: ResponseFormatJsonSchema {
597                name: format!("Result"),
598                description: None,
599                schema: Some(make_schema::<R>()),
600                strict: Some(true),
601            },
602        })
603        .build()
604        .unwrap();
605    let response = client.chat().create(request).await.unwrap();
606    let text = response
607        .choices
608        .into_iter()
609        .map(|choice| choice.message.content.unwrap())
610        .collect::<String>();
611
612    serde_json::from_str(&text).unwrap()
613}