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
use crate::{
history::{History, InfiniteHistory},
llm::LLMProvider,
tool::{ClosureTool, ParallelExecutor, ToolArgs, ToolExecutor},
types::ToolDefinition,
};
/// Agent loop that coordinates LLM calls and tool execution.
/// Uses [`ParallelExecutor`] by default.
pub struct Agent {
pub history: Box<dyn History>,
llm: Box<dyn LLMProvider>,
executor: Box<dyn ToolExecutor>,
tools: Vec<ToolDefinition>,
}
impl Agent {
/// Create a new agent loop
pub fn new(llm: impl LLMProvider + 'static) -> Self {
Self {
llm: Box::new(llm),
history: Box::new(InfiniteHistory::new()),
executor: Box::new(ParallelExecutor::new()),
tools: Vec::new(),
}
}
/// Set custom history manager (default: [`InfiniteHistory`])
///
/// # Example
/// ```
/// use tiny_loop::{Agent, history::InfiniteHistory, llm::OpenAIProvider};
///
/// let agent = Agent::new(OpenAIProvider::new())
/// .history(InfiniteHistory::new());
/// ```
pub fn history(mut self, history: impl History + 'static) -> Self {
self.history = Box::new(history);
self
}
/// Append a system message
///
/// # Example
/// ```
/// use tiny_loop::{Agent, llm::OpenAIProvider};
///
/// let agent = Agent::new(OpenAIProvider::new())
/// .system("You are a helpful assistant");
/// ```
pub fn system(mut self, content: impl Into<String>) -> Self {
self.history.add(crate::types::TimedMessage {
message: crate::types::SystemMessage {
content: content.into(),
}
.into(),
timestamp: std::time::SystemTime::now(),
elapsed: std::time::Duration::ZERO,
});
self
}
/// Get reference to registered tool definitions
pub fn tools(&self) -> &[ToolDefinition] {
&self.tools
}
/// Set a custom tool executor (default: [`ParallelExecutor`])
///
/// # Example
/// ```
/// use tiny_loop::{Agent, tool::SequentialExecutor, llm::OpenAIProvider};
///
/// let agent = Agent::new(OpenAIProvider::new())
/// .executor(SequentialExecutor::new());
/// ```
pub fn executor(mut self, executor: impl ToolExecutor + 'static) -> Self {
self.executor = Box::new(executor);
self
}
/// Register a tool function created by [`#[tool]`](crate::tool::tool)
///
/// To register a tool method with an instance, use [`Self::bind`].
/// To register external tools (e.g. from MCP servers) use [`Self::external`]
///
/// # Example
/// ```
/// use tiny_loop::{Agent, tool::tool, llm::OpenAIProvider};
///
/// #[tool]
/// async fn fetch(
/// /// URL to fetch
/// url: String,
/// ) -> String {
/// todo!()
/// }
///
/// let agent = Agent::new(OpenAIProvider::new())
/// .tool(fetch);
/// ```
pub fn tool<Args, Fut>(mut self, tool: fn(Args) -> Fut) -> Self
where
Fut: Future<Output = String> + Send + 'static,
Args: ToolArgs + 'static,
{
self.tools.push(Args::definition());
self.executor.add(
Args::TOOL_NAME.into(),
Box::new(ClosureTool::boxed(move |s: String| {
Box::pin(async move {
let args = match serde_json::from_str::<Args>(&s) {
Ok(args) => args,
Err(e) => return e.to_string(),
};
tool(args).await
})
})),
);
self
}
/// Bind an instance to a tool method created by [`#[tool]`](crate::tool::tool)
///
/// To register a standalone tool function, use [`Self::tool`].
/// To register external tools (e.g. from MCP servers) use [`Self::external`]
///
/// # Example
/// ```
/// use tiny_loop::{Agent, tool::tool, llm::OpenAIProvider};
/// use std::sync::Arc;
///
/// #[derive(Clone)]
/// struct Database {
/// data: Arc<String>,
/// }
///
/// #[tool]
/// impl Database {
/// /// Fetch data from database
/// async fn fetch(
/// self,
/// /// Data key
/// key: String,
/// ) -> String {
/// todo!()
/// }
/// }
///
/// let db = Database { data: Arc::new("data".into()) };
/// let agent = Agent::new(OpenAIProvider::new())
/// .bind(db, Database::fetch);
/// ```
pub fn bind<T, Args, Fut>(mut self, ins: T, tool: fn(T, Args) -> Fut) -> Self
where
T: Send + Sync + Clone + 'static,
Fut: Future<Output = String> + Send + 'static,
Args: ToolArgs + 'static,
{
self.tools.push(Args::definition());
self.executor.add(
Args::TOOL_NAME.into(),
Box::new(ClosureTool::boxed(move |s: String| {
let ins = ins.clone();
Box::pin(async move {
let args = match serde_json::from_str::<Args>(&s) {
Ok(args) => args,
Err(e) => return e.to_string(),
};
tool(ins, args).await
})
})),
);
self
}
/// Register external tools (e.g. from MCP servers)
///
/// To register a standalone tool function, use [`tool`](Self::tool).
/// To register a tool method with an instance, use [`bind`](Self::bind).
///
/// # Example
/// ```
/// use tiny_loop::{Agent, llm::OpenAIProvider, types::{Parameters, ToolDefinition, ToolFunction}};
/// use serde_json::{json, Value};
///
/// let defs = vec![ToolDefinition {
/// tool_type: "function".into(),
/// function: ToolFunction {
/// name: "get_weather".into(),
/// description: "Get weather information".into(),
/// parameters: Parameters::from_object(
/// json!({
/// "type": "object",
/// "properties": {
/// "city": {
/// "type": "string",
/// "description": "City name"
/// }
/// },
/// "required": ["city"]
/// }).as_object().unwrap().clone()
/// ),
/// },
/// }];
///
/// let external_executor = move |name: String, args: String| {
/// async move {
/// let _args = serde_json::from_str::<Value>(&args).unwrap();
/// "result".into()
/// }
/// };
///
/// let agent = Agent::new(OpenAIProvider::new())
/// .external(defs, external_executor);
/// ```
pub fn external<Fut>(
mut self,
defs: Vec<ToolDefinition>,
exec: impl Fn(String, String) -> Fut + Clone + Send + Sync + 'static,
) -> Self
where
Fut: Future<Output = String> + Send + 'static,
{
for d in &defs {
let name = d.function.name.clone();
let exec = exec.clone();
self.executor.add(
name.clone(),
Box::new(ClosureTool::boxed(move |s: String| {
let name = name.clone();
let exec = exec.clone();
Box::pin(async move { exec(name.clone(), s).await })
})),
);
}
self.tools.extend(defs);
self
}
/// Execute one iteration of the agent loop.
/// Returns `Ok(Some(content))` if loop should terminate, `Ok(None)` to continue
///
/// This is usually used to customize the agent loop.
///
/// # Example
/// ```
/// use tiny_loop::{Agent, llm::OpenAIProvider};
///
/// # async fn example() -> tiny_loop::Result<()> {
/// let mut agent = Agent::new(OpenAIProvider::new())
/// .system("You are a helpful assistant");
///
/// // Custom loop with early break
/// let mut iterations = 0;
/// loop {
/// println!("Before step {}", iterations);
///
/// if let Some(content) = agent.step().await? {
/// println!("Completed: {}", content);
/// break;
/// }
///
/// iterations += 1;
/// if iterations > 10 {
/// println!("Max iterations reached");
/// break;
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub async fn step(&mut self) -> crate::Result<Option<String>> {
tracing::trace!("Calling LLM with {} messages", self.history.get_all().len());
let messages: Vec<_> = self
.history
.get_all()
.iter()
.map(|tm| tm.message.clone())
.collect();
let start = std::time::SystemTime::now();
let response = self.llm.call(&messages, &self.tools).await?;
let elapsed = start.elapsed().unwrap();
self.history.add(crate::types::TimedMessage {
message: response.message.clone().into(),
timestamp: start + elapsed,
elapsed,
});
// Execute tool calls if any
if let Some(calls) = &response.message.tool_calls {
tracing::debug!("Executing {} tool calls", calls.len());
let results = self.executor.execute(calls.clone()).await;
self.history.add_batch(
results
.into_iter()
.map(|r| crate::types::TimedMessage {
message: r.tool_message.into(),
timestamp: r.timestamp,
elapsed: r.elapsed,
})
.collect(),
);
}
// Break loop if finish reason is not tool_calls
if !matches!(
response.finish_reason,
crate::types::FinishReason::ToolCalls
) {
tracing::debug!(
"Agent loop completed, finish_reason: {:?}",
response.finish_reason
);
return Ok(Some(response.message.content));
}
Ok(None)
}
/// Run the agent loop until completion.
/// Return the last AI's response
pub async fn run(&mut self) -> crate::Result<String> {
tracing::debug!("Starting agent loop");
loop {
if let Some(content) = self.step().await? {
return Ok(content);
}
}
}
/// Run the agent loop with a new user input appended.
/// Return the last AI's response
pub async fn chat(&mut self, prompt: impl Into<String>) -> crate::Result<String> {
let prompt = prompt.into();
tracing::debug!("Chat request, prompt length: {}", prompt.len());
self.history.add(crate::types::TimedMessage {
message: crate::types::UserMessage { content: prompt }.into(),
timestamp: std::time::SystemTime::now(),
elapsed: std::time::Duration::ZERO,
});
self.run().await
}
}