tiny-agent-loop 0.1.0

A tiny LLM agent loop library for simple one-off projects with LLMs.
Documentation
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#![doc = include_str!("../README.md")]

use std::{iter::once, marker::PhantomData, ops::ControlFlow};

use async_openai::{
    Client,
    config::Config,
    error::OpenAIError,
    types::chat::{
        ChatCompletionMessageToolCall, ChatCompletionMessageToolCalls,
        ChatCompletionRequestAssistantMessage, ChatCompletionRequestAssistantMessageContent,
        ChatCompletionRequestSystemMessage, ChatCompletionRequestToolMessage,
        ChatCompletionRequestUserMessage, ChatCompletionTool, ChatCompletionTools,
        CreateChatCompletionRequestArgs, FinishReason, FunctionObjectArgs, ResponseFormat,
        ResponseFormatJsonSchema,
    },
};
use futures_util::StreamExt;
use log::{debug, trace};
use schemars::{JsonSchema, generate::SchemaSettings, transform::RestrictFormats};
use serde::de::DeserializeOwned;
use serde_json::Value;

macro_rules! impl_tools {
    ($($name:ident),*) => {
        impl<R, $($name: Tool<R>),*> Tools<R> for ($($name,)*) {
            #[allow(non_snake_case)]
            fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
                where R: 'r
            {
                let ($($name,)*) = self;

                [
                    $($name as &mut dyn Tool<R>,)*
                ].into_iter()
            }
        }
    }
}

impl_tools!(T0);
impl_tools!(T0, T1);
impl_tools!(T0, T1, T2);
impl_tools!(T0, T1, T2, T3);
impl_tools!(T0, T1, T2, T3, T4);
impl_tools!(T0, T1, T2, T3, T4, T5);
impl_tools!(T0, T1, T2, T3, T4, T5, T6);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_tools!(
    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
);
impl_tools!(
    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
);

impl<
    D: JsonSchema + DeserializeOwned,
    R,
    Fut: Future<Output = ControlFlow<R, String>>,
    F: FnMut(D) -> Fut,
> Tools<R> for FnTool<D, R, Fut, F>
{
    fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
    where
        R: 'r,
    {
        once(self as &mut dyn Tool<R>)
    }
}

pub trait Tools<R> {
    fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
    where
        R: 'r;
}

pub trait Tool<R> {
    /// Returns the name of the tool. May not change between calls.
    fn name(&self) -> &str;

    /// The description of the tool, provided to the LLM.
    fn description(&self) -> &str;

    /// The JSON schema of the tool parameters.
    fn parameter_schema(&self) -> Value;

    /// Invokes the tool with `data` as the provided parameters.
    /// It is assumed that the LLM ensures that the parameters match the JSON schema.
    fn invoke<'lt>(
        &'lt mut self,
        data: &str,
    ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt>;
}

struct FnTool<D, R, Fut, F> {
    name: &'static str,
    description: &'static str,
    invoke: F,
    _phantom: PhantomData<(fn(D) -> R, Fut)>,
}

pub fn tool<
    'a,
    D: JsonSchema + DeserializeOwned,
    R,
    Fut: Future<Output = ControlFlow<R, String>>,
    F: FnMut(D) -> Fut,
>(
    name: &'static str,
    description: &'static str,
    invoke: F,
) -> impl Tool<R> {
    FnTool {
        name,
        description,
        invoke,
        _phantom: PhantomData,
    }
}

impl<
    D: JsonSchema + DeserializeOwned,
    R,
    Fut: Future<Output = ControlFlow<R, String>>,
    F: FnMut(D) -> Fut,
> Tool<R> for FnTool<D, R, Fut, F>
{
    fn name(&self) -> &str {
        self.name
    }

    fn description(&self) -> &str {
        self.description
    }

    fn parameter_schema(&self) -> Value {
        make_schema::<D>()
    }

    fn invoke<'lt>(
        &'lt mut self,
        data: &str,
    ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt> {
        let args = serde_json::from_str::<D>(data).unwrap();
        Box::new((self.invoke)(args)) as Box<dyn Future<Output = ControlFlow<R, String>>>
    }
}

fn make_schema<D: JsonSchema>() -> Value {
    let schema = SchemaSettings::draft2020_12()
        .with_transform(RestrictFormats::default())
        .with(|s| s.inline_subschemas = true)
        .into_generator()
        .into_root_schema_for::<D>();

    serde_json::to_value(&schema).unwrap()
}

pub struct FinishHandler<R> {
    finish: Box<dyn FnMut() -> Box<dyn Future<Output = ControlFlow<R, String>>>>,
}

impl<R> FinishHandler<R> {
    fn invoke(&mut self) -> Box<dyn Future<Output = ControlFlow<R, String>>> {
        (self.finish)()
    }
}

impl<R, Fut: Future<Output = ControlFlow<R, String>> + 'static, F: FnMut() -> Fut + 'static> From<F>
    for FinishHandler<R>
{
    fn from(mut value: F) -> Self {
        Self {
            finish: Box::new(move || Box::new((value)())),
        }
    }
}

pub struct Agent<T, R> {
    tools: T,
    listen_content: Option<Box<dyn Fn(&str)>>,
    listen_tool_call: Option<Box<dyn Fn(&str)>>,
    _phantom: PhantomData<R>,
    finish: FinishHandler<R>,
}

impl<R, T: Tools<R>> Agent<T, R> {
    /// Creates a new agent with the provided `tools`.
    ///
    /// `finish` is invoked when the LLM finishes without a tool call.
    /// When `ControlFlow::Break` is returned, the loop will terminate with the provided return value.
    /// When `ControlFlow::Continue(message)` is returned, the loop continues with the returned message appended to the chat history.
    pub fn new(tools: T, finish: FinishHandler<R>) -> Self {
        Self {
            tools,
            finish,
            listen_content: None,
            listen_tool_call: None,
            _phantom: PhantomData,
        }
    }

    /// Adds a listener that is invoked when streamed message content is available.
    /// This is intended for debugging purposes only.
    pub fn with_content_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
        self.listen_content = Some(listener);
        self
    }

    /// Adds a listener that is invoked when tool calling content is available.
    /// This is intended for debugging purposes only.
    /// Tools are called automatically.
    pub fn with_tool_call_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
        self.listen_tool_call = Some(listener);
        self
    }

    /// Runs the agent loop. If tools were provided, they may be called.
    ///
    /// Terminates when a tool returns ControlFlow::Break.
    ///
    /// It is assumed that any single message or tool response always fits in the context window fully.
    /// If this is not the case, this function may crash.
    pub async fn run<C: Config>(&mut self, client: &Client<C>, prompt: &str) -> R {
        let mut messages = vec![ChatCompletionRequestUserMessage::from(prompt).into()];

        loop {
            let tools = self
                .tools
                .iter()
                .map(|tool| {
                    ChatCompletionTools::Function(ChatCompletionTool {
                        function: FunctionObjectArgs::default()
                            .name(tool.name())
                            .description(tool.description())
                            .parameters(tool.parameter_schema())
                            .build()
                            .unwrap(),
                    })
                })
                .collect::<Vec<_>>();

            let request = CreateChatCompletionRequestArgs::default()
                .messages(messages.clone())
                .tools(tools)
                .build()
                .unwrap();

            let mut stream = client.chat().create_stream(request).await.unwrap();
            let mut tool_calls = Vec::new();
            let mut execution_results = Vec::new();

            while let Some(result) = stream.next().await {
                let response = match result {
                    Ok(response) => response,
                    Err(OpenAIError::JSONDeserialize(e, json)) => {
                        let json: Value = serde_json::from_str(&json).unwrap();
                        if let Some(err) = json.get("error")
                            && let Some(ty) = err.get("type")
                            && let Some(ty) = ty.as_str()
                            && ty == "exceed_context_size_error"
                        {
                            // When we run out of context, we summarize older messages.
                            // It is assumed that a single message will always fit the context size.
                            let mut messages_to_summarize = messages
                                .drain(..messages.len().saturating_sub(3).min(1))
                                .collect::<Vec<_>>();
                            debug!(
                                "Context size exceeded ({err:?}), attempting summary of messages: {messages_to_summarize:#?}."
                            );

                            messages_to_summarize.push(
                                ChatCompletionRequestSystemMessage::from(include_str!(
                                    "summary.txt"
                                ))
                                .into(),
                            );

                            // TODO: This will panic if there is just a single message left that doesn't fit the context window.
                            let request = CreateChatCompletionRequestArgs::default()
                                .messages(messages_to_summarize)
                                .build()
                                .unwrap();
                            let response = client.chat().create(request).await.unwrap();
                            trace!("Summarized to: {response:#?}");
                            for (index, choice) in response.choices.into_iter().enumerate() {
                                messages.insert(
                                    index,
                                    ChatCompletionRequestAssistantMessage {
                                        content: Some(
                                            ChatCompletionRequestAssistantMessageContent::Text(
                                                choice.message.content.unwrap(),
                                            ),
                                        ),
                                        ..Default::default()
                                    }
                                    .into(),
                                );
                            }

                            break;
                        } else {
                            panic!("Unexpected error: failed to deserialize JSON: {e} in {json}");
                        }
                    }
                    Err(e) => panic!("Unexpected error: {e}"),
                };

                for choice in response.choices {
                    if let Some(content) = &choice.delta.content
                        && let Some(f) = &self.listen_content
                    {
                        (f)(&content);
                    }

                    if let Some(tool_call_chunks) = choice.delta.tool_calls {
                        for chunk in tool_call_chunks {
                            let index = chunk.index as usize;
                            if tool_calls.len() <= index {
                                tool_calls.resize(
                                    index + 1,
                                    ChatCompletionMessageToolCall {
                                        id: String::new(),
                                        function: Default::default(),
                                    },
                                );
                            }

                            let tool_call = &mut tool_calls[index];
                            if let Some(id) = chunk.id {
                                tool_call.id = id;
                            }

                            if let Some(function_chunk) = chunk.function {
                                if let Some(name) = function_chunk.name {
                                    if let Some(f) = &self.listen_tool_call {
                                        (f)(&name);
                                    }

                                    tool_call.function.name = name;
                                }
                                if let Some(arguments) = function_chunk.arguments {
                                    if let Some(f) = &self.listen_tool_call {
                                        (f)(&arguments);
                                    }

                                    tool_call.function.arguments.push_str(&arguments);
                                }
                            }
                        }
                    }

                    match choice.finish_reason {
                        Some(FinishReason::ToolCalls) => {
                            for tool_call in tool_calls.iter() {
                                let name = tool_call.function.name.clone();
                                let tool_call_id = tool_call.id.clone();
                                let result = {
                                    debug!("Executing tool: {name}");
                                    let tool = self.tools.iter().find(|tool| tool.name() == name);

                                    match tool {
                                        Some(tool) => {
                                            let future = tool.invoke(&tool_call.function.arguments);
                                            let pinned = Box::into_pin(future);
                                            pinned.await
                                        }
                                        None => ControlFlow::Continue(String::from(
                                            "ERROR: Tool not found",
                                        )),
                                    }
                                };

                                match result {
                                    ControlFlow::Continue(result) => {
                                        execution_results.push((tool_call_id, result))
                                    }
                                    ControlFlow::Break(val) => return val,
                                }
                            }
                        }
                        Some(FinishReason::Stop) => {
                            let future = self.finish.invoke();
                            let pinned = Box::into_pin(future);
                            let result = pinned.await;

                            match result {
                                ControlFlow::Continue(result) => {
                                    messages.push(
                                        ChatCompletionRequestUserMessage::from(result).into(),
                                    );
                                }
                                ControlFlow::Break(val) => return val,
                            }
                        }
                        Some(reason) => panic!("Unexpected stop reason: {reason:?}"),
                        _ => (),
                    }
                }
            }

            if !execution_results.is_empty() {
                let assistant_tool_calls: Vec<ChatCompletionMessageToolCalls> =
                    tool_calls.iter().map(|tc| tc.clone().into()).collect();
                messages.push(
                    ChatCompletionRequestAssistantMessage {
                        content: None,
                        tool_calls: Some(assistant_tool_calls),
                        ..Default::default()
                    }
                    .into(),
                );

                for (tool_call_id, response) in execution_results {
                    messages.push(
                        ChatCompletionRequestToolMessage {
                            content: response.to_string().into(),
                            tool_call_id,
                        }
                        .into(),
                    );
                }
            }
        }
    }
}

/// Invokes the LLM once, generating an output object directly.
/// No tool calls are supported.
pub async fn one_shot<C: Config, R: JsonSchema + DeserializeOwned>(
    client: &Client<C>,
    prompt: &str,
) -> R {
    let request = CreateChatCompletionRequestArgs::default()
        .messages(vec![ChatCompletionRequestUserMessage::from(prompt).into()])
        .response_format(ResponseFormat::JsonSchema {
            json_schema: ResponseFormatJsonSchema {
                name: format!("Result"),
                description: None,
                schema: Some(make_schema::<R>()),
                strict: Some(true),
            },
        })
        .build()
        .unwrap();
    let response = client.chat().create(request).await.unwrap();
    let text = response
        .choices
        .into_iter()
        .map(|choice| choice.message.content.unwrap())
        .collect::<String>();

    serde_json::from_str(&text).unwrap()
}