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 ChatCompletionRequestSystemMessage, ChatCompletionRequestToolMessage,
13 ChatCompletionRequestUserMessage, ChatCompletionTool, ChatCompletionTools,
14 CreateChatCompletionRequestArgs, FinishReason, FunctionObjectArgs, ResponseFormat,
15 ResponseFormatJsonSchema,
16 },
17};
18use futures_util::StreamExt;
19use log::{debug, trace};
20use schemars::{JsonSchema, generate::SchemaSettings, transform::RestrictFormats};
21use serde::de::DeserializeOwned;
22use serde_json::Value;
23
24macro_rules! impl_tools {
25 ($($name:ident),*) => {
26 impl<R, $($name: Tool<R>),*> Tools<R> for ($($name,)*) {
27 #[allow(non_snake_case)]
28 fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
29 where R: 'r
30 {
31 let ($($name,)*) = self;
32
33 [
34 $($name as &mut dyn Tool<R>,)*
35 ].into_iter()
36 }
37 }
38 }
39}
40
41impl_tools!(T0);
42impl_tools!(T0, T1);
43impl_tools!(T0, T1, T2);
44impl_tools!(T0, T1, T2, T3);
45impl_tools!(T0, T1, T2, T3, T4);
46impl_tools!(T0, T1, T2, T3, T4, T5);
47impl_tools!(T0, T1, T2, T3, T4, T5, T6);
48impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7);
49impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
50impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
51impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
52impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
53impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
54impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
55impl_tools!(
56 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
57);
58impl_tools!(
59 T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
60);
61
62impl<
63 D: JsonSchema + DeserializeOwned,
64 R,
65 Fut: Future<Output = ControlFlow<R, String>>,
66 F: FnMut(D) -> Fut,
67> Tools<R> for FnTool<D, R, Fut, F>
68{
69 fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
70 where
71 R: 'r,
72 {
73 once(self as &mut dyn Tool<R>)
74 }
75}
76
77pub trait Tools<R> {
78 fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
79 where
80 R: 'r;
81}
82
83pub trait Tool<R> {
84 fn name(&self) -> &str;
86
87 fn description(&self) -> &str;
89
90 fn parameter_schema(&self) -> Value;
92
93 fn invoke<'lt>(
96 &'lt mut self,
97 data: &str,
98 ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt>;
99}
100
101struct FnTool<D, R, Fut, F> {
102 name: &'static str,
103 description: &'static str,
104 invoke: F,
105 _phantom: PhantomData<(fn(D) -> R, Fut)>,
106}
107
108pub fn tool<
109 'a,
110 D: JsonSchema + DeserializeOwned,
111 R,
112 Fut: Future<Output = ControlFlow<R, String>>,
113 F: FnMut(D) -> Fut,
114>(
115 name: &'static str,
116 description: &'static str,
117 invoke: F,
118) -> impl Tool<R> {
119 FnTool {
120 name,
121 description,
122 invoke,
123 _phantom: PhantomData,
124 }
125}
126
127impl<
128 D: JsonSchema + DeserializeOwned,
129 R,
130 Fut: Future<Output = ControlFlow<R, String>>,
131 F: FnMut(D) -> Fut,
132> Tool<R> for FnTool<D, R, Fut, F>
133{
134 fn name(&self) -> &str {
135 self.name
136 }
137
138 fn description(&self) -> &str {
139 self.description
140 }
141
142 fn parameter_schema(&self) -> Value {
143 make_schema::<D>()
144 }
145
146 fn invoke<'lt>(
147 &'lt mut self,
148 data: &str,
149 ) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt> {
150 let args = serde_json::from_str::<D>(data).unwrap();
151 Box::new((self.invoke)(args)) as Box<dyn Future<Output = ControlFlow<R, String>>>
152 }
153}
154
155fn make_schema<D: JsonSchema>() -> Value {
156 let schema = SchemaSettings::draft2020_12()
157 .with_transform(RestrictFormats::default())
158 .with(|s| s.inline_subschemas = true)
159 .into_generator()
160 .into_root_schema_for::<D>();
161
162 serde_json::to_value(&schema).unwrap()
163}
164
165pub struct FinishHandler<R> {
166 finish: Box<dyn FnMut() -> Box<dyn Future<Output = ControlFlow<R, String>>>>,
167}
168
169impl<R> FinishHandler<R> {
170 fn invoke(&mut self) -> Box<dyn Future<Output = ControlFlow<R, String>>> {
171 (self.finish)()
172 }
173}
174
175impl<R, Fut: Future<Output = ControlFlow<R, String>> + 'static, F: FnMut() -> Fut + 'static> From<F>
176 for FinishHandler<R>
177{
178 fn from(mut value: F) -> Self {
179 Self {
180 finish: Box::new(move || Box::new((value)())),
181 }
182 }
183}
184
185pub struct Agent<T, R> {
186 tools: T,
187 listen_content: Option<Box<dyn Fn(&str)>>,
188 listen_tool_call: Option<Box<dyn Fn(&str)>>,
189 _phantom: PhantomData<R>,
190 finish: FinishHandler<R>,
191}
192
193impl<R, T: Tools<R>> Agent<T, R> {
194 pub fn new(tools: T, finish: FinishHandler<R>) -> Self {
200 Self {
201 tools,
202 finish,
203 listen_content: None,
204 listen_tool_call: None,
205 _phantom: PhantomData,
206 }
207 }
208
209 pub fn with_content_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
212 self.listen_content = Some(listener);
213 self
214 }
215
216 pub fn with_tool_call_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
220 self.listen_tool_call = Some(listener);
221 self
222 }
223
224 pub async fn run<C: Config>(&mut self, client: &Client<C>, prompt: &str) -> R {
231 let mut messages = vec![ChatCompletionRequestUserMessage::from(prompt).into()];
232
233 loop {
234 let tools = self
235 .tools
236 .iter()
237 .map(|tool| {
238 ChatCompletionTools::Function(ChatCompletionTool {
239 function: FunctionObjectArgs::default()
240 .name(tool.name())
241 .description(tool.description())
242 .parameters(tool.parameter_schema())
243 .build()
244 .unwrap(),
245 })
246 })
247 .collect::<Vec<_>>();
248
249 let request = CreateChatCompletionRequestArgs::default()
250 .messages(messages.clone())
251 .tools(tools)
252 .build()
253 .unwrap();
254
255 let mut stream = client.chat().create_stream(request).await.unwrap();
256 let mut tool_calls = Vec::new();
257 let mut execution_results = Vec::new();
258
259 while let Some(result) = stream.next().await {
260 let response = match result {
261 Ok(response) => response,
262 Err(OpenAIError::JSONDeserialize(e, json)) => {
263 let json: Value = serde_json::from_str(&json).unwrap();
264 if let Some(err) = json.get("error")
265 && let Some(ty) = err.get("type")
266 && let Some(ty) = ty.as_str()
267 && ty == "exceed_context_size_error"
268 {
269 let mut messages_to_summarize = messages
272 .drain(..messages.len().saturating_sub(3).min(1))
273 .collect::<Vec<_>>();
274 debug!(
275 "Context size exceeded ({err:?}), attempting summary of messages: {messages_to_summarize:#?}."
276 );
277
278 messages_to_summarize.push(
279 ChatCompletionRequestSystemMessage::from(include_str!(
280 "summary.txt"
281 ))
282 .into(),
283 );
284
285 let request = CreateChatCompletionRequestArgs::default()
287 .messages(messages_to_summarize)
288 .build()
289 .unwrap();
290 let response = client.chat().create(request).await.unwrap();
291 trace!("Summarized to: {response:#?}");
292 for (index, choice) in response.choices.into_iter().enumerate() {
293 messages.insert(
294 index,
295 ChatCompletionRequestAssistantMessage {
296 content: Some(
297 ChatCompletionRequestAssistantMessageContent::Text(
298 choice.message.content.unwrap(),
299 ),
300 ),
301 ..Default::default()
302 }
303 .into(),
304 );
305 }
306
307 break;
308 } else {
309 panic!("Unexpected error: failed to deserialize JSON: {e} in {json}");
310 }
311 }
312 Err(e) => panic!("Unexpected error: {e}"),
313 };
314
315 for choice in response.choices {
316 if let Some(content) = &choice.delta.content
317 && let Some(f) = &self.listen_content
318 {
319 (f)(&content);
320 }
321
322 if let Some(tool_call_chunks) = choice.delta.tool_calls {
323 for chunk in tool_call_chunks {
324 let index = chunk.index as usize;
325 if tool_calls.len() <= index {
326 tool_calls.resize(
327 index + 1,
328 ChatCompletionMessageToolCall {
329 id: String::new(),
330 function: Default::default(),
331 },
332 );
333 }
334
335 let tool_call = &mut tool_calls[index];
336 if let Some(id) = chunk.id {
337 tool_call.id = id;
338 }
339
340 if let Some(function_chunk) = chunk.function {
341 if let Some(name) = function_chunk.name {
342 if let Some(f) = &self.listen_tool_call {
343 (f)(&name);
344 }
345
346 tool_call.function.name = name;
347 }
348 if let Some(arguments) = function_chunk.arguments {
349 if let Some(f) = &self.listen_tool_call {
350 (f)(&arguments);
351 }
352
353 tool_call.function.arguments.push_str(&arguments);
354 }
355 }
356 }
357 }
358
359 match choice.finish_reason {
360 Some(FinishReason::ToolCalls) => {
361 for tool_call in tool_calls.iter() {
362 let name = tool_call.function.name.clone();
363 let tool_call_id = tool_call.id.clone();
364 let result = {
365 debug!("Executing tool: {name}");
366 let tool = self.tools.iter().find(|tool| tool.name() == name);
367
368 match tool {
369 Some(tool) => {
370 let future = tool.invoke(&tool_call.function.arguments);
371 let pinned = Box::into_pin(future);
372 pinned.await
373 }
374 None => ControlFlow::Continue(String::from(
375 "ERROR: Tool not found",
376 )),
377 }
378 };
379
380 match result {
381 ControlFlow::Continue(result) => {
382 execution_results.push((tool_call_id, result))
383 }
384 ControlFlow::Break(val) => return val,
385 }
386 }
387 }
388 Some(FinishReason::Stop) => {
389 let future = self.finish.invoke();
390 let pinned = Box::into_pin(future);
391 let result = pinned.await;
392
393 match result {
394 ControlFlow::Continue(result) => {
395 messages.push(
396 ChatCompletionRequestUserMessage::from(result).into(),
397 );
398 }
399 ControlFlow::Break(val) => return val,
400 }
401 }
402 Some(reason) => panic!("Unexpected stop reason: {reason:?}"),
403 _ => (),
404 }
405 }
406 }
407
408 if !execution_results.is_empty() {
409 let assistant_tool_calls: Vec<ChatCompletionMessageToolCalls> =
410 tool_calls.iter().map(|tc| tc.clone().into()).collect();
411 messages.push(
412 ChatCompletionRequestAssistantMessage {
413 content: None,
414 tool_calls: Some(assistant_tool_calls),
415 ..Default::default()
416 }
417 .into(),
418 );
419
420 for (tool_call_id, response) in execution_results {
421 messages.push(
422 ChatCompletionRequestToolMessage {
423 content: response.to_string().into(),
424 tool_call_id,
425 }
426 .into(),
427 );
428 }
429 }
430 }
431 }
432}
433
434pub async fn one_shot<C: Config, R: JsonSchema + DeserializeOwned>(
437 client: &Client<C>,
438 prompt: &str,
439) -> R {
440 let request = CreateChatCompletionRequestArgs::default()
441 .messages(vec![ChatCompletionRequestUserMessage::from(prompt).into()])
442 .response_format(ResponseFormat::JsonSchema {
443 json_schema: ResponseFormatJsonSchema {
444 name: format!("Result"),
445 description: None,
446 schema: Some(make_schema::<R>()),
447 strict: Some(true),
448 },
449 })
450 .build()
451 .unwrap();
452 let response = client.chat().create(request).await.unwrap();
453 let text = response
454 .choices
455 .into_iter()
456 .map(|choice| choice.message.content.unwrap())
457 .collect::<String>();
458
459 serde_json::from_str(&text).unwrap()
460}