autoagents-core 0.3.7

Agent Framework for Building Autonomous Agents
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
pub mod event_helper;
pub mod memory_helper;
pub mod memory_policy;
pub mod tool_processor;
pub mod turn_engine;

use crate::agent::context::Context;
use crate::agent::task::Task;
use async_trait::async_trait;
use futures::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::error::Error;
use std::fmt::Debug;
use std::sync::Arc;

/// Result of processing a single turn in the agent's execution
#[derive(Debug)]
pub enum TurnResult<T> {
    /// Continue processing with optional intermediate data
    Continue(Option<T>),
    /// Final result obtained
    Complete(T),
}

/// Configuration for executors
#[derive(Debug, Clone)]
pub struct ExecutorConfig {
    pub max_turns: usize,
}

impl Default for ExecutorConfig {
    fn default() -> Self {
        Self { max_turns: 10 }
    }
}

/// Base trait for agent execution strategies
///
/// Executors are responsible for implementing the specific execution logic
/// for agents, such as ReAct loops, chain-of-thought, or custom patterns.
#[async_trait]
pub trait AgentExecutor: Send + Sync + 'static {
    type Output: Serialize + DeserializeOwned + Clone + Send + Sync + Debug;
    type Error: Error + Send + Sync + 'static;

    fn config(&self) -> ExecutorConfig;

    async fn execute(
        &self,
        task: &Task,
        context: Arc<Context>,
    ) -> Result<Self::Output, Self::Error>;

    async fn execute_stream(
        &self,
        task: &Task,
        context: Arc<Context>,
    ) -> Result<
        std::pin::Pin<Box<dyn Stream<Item = Result<Self::Output, Self::Error>> + Send>>,
        Self::Error,
    > {
        // Default fallback to self.execute with final result as a single-item stream
        let context_clone = context.clone();
        let result = self.execute(task, context_clone).await;
        let stream = futures::stream::iter(vec![result]);
        Ok(Box::pin(stream))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::context::Context;
    use crate::agent::task::Task;
    use async_trait::async_trait;
    use autoagents_llm::{
        LLMProvider, ToolCall,
        chat::{ChatMessage, ChatProvider, ChatResponse, StructuredOutputFormat},
        completion::{CompletionProvider, CompletionRequest, CompletionResponse},
        embedding::EmbeddingProvider,
        error::LLMError,
        models::ModelsProvider,
    };
    use futures::stream;
    use serde::{Deserialize, Serialize};
    use serde_json::Value;
    use std::sync::Arc;
    use tokio::sync::mpsc;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    struct TestOutput {
        message: String,
    }

    impl From<TestOutput> for Value {
        fn from(output: TestOutput) -> Self {
            serde_json::to_value(output).unwrap_or(Value::Null)
        }
    }

    #[derive(Debug, thiserror::Error)]
    enum TestError {
        #[error("Test error: {0}")]
        TestError(String),
    }

    struct MockExecutor {
        should_fail: bool,
        max_turns: usize,
    }

    impl MockExecutor {
        fn new(should_fail: bool) -> Self {
            Self {
                should_fail,
                max_turns: 5,
            }
        }

        fn with_max_turns(max_turns: usize) -> Self {
            Self {
                should_fail: false,
                max_turns,
            }
        }
    }

    #[async_trait]
    impl AgentExecutor for MockExecutor {
        type Output = TestOutput;
        type Error = TestError;

        fn config(&self) -> ExecutorConfig {
            ExecutorConfig {
                max_turns: self.max_turns,
            }
        }

        async fn execute(
            &self,
            task: &Task,
            _context: Arc<Context>,
        ) -> Result<Self::Output, Self::Error> {
            if self.should_fail {
                return Err(TestError::TestError("Mock execution failed".to_string()));
            }

            Ok(TestOutput {
                message: format!("Processed: {}", task.prompt),
            })
        }
        async fn execute_stream(
            &self,
            task: &Task,
            context: Arc<Context>,
        ) -> Result<
            std::pin::Pin<Box<dyn Stream<Item = Result<Self::Output, Self::Error>> + Send>>,
            Self::Error,
        > {
            // Use the default implementation from the trait
            let context_clone = context.clone();
            let result = self.execute(task, context_clone).await;
            let stream = stream::once(async move { result });
            Ok(Box::pin(stream))
        }
    }

    // Mock LLM Provider
    struct MockLLMProvider;

    #[async_trait]
    impl ChatProvider for MockLLMProvider {
        async fn chat(
            &self,
            _messages: &[ChatMessage],
            _json_schema: Option<StructuredOutputFormat>,
        ) -> Result<Box<dyn ChatResponse>, LLMError> {
            Ok(Box::new(MockChatResponse {
                text: Some("Mock response".to_string()),
            }))
        }
        async fn chat_with_tools(
            &self,
            _messages: &[ChatMessage],
            _tools: Option<&[autoagents_llm::chat::Tool]>,
            _json_schema: Option<StructuredOutputFormat>,
        ) -> Result<Box<dyn ChatResponse>, LLMError> {
            Ok(Box::new(MockChatResponse {
                text: Some("Mock response".to_string()),
            }))
        }
    }

    #[async_trait]
    impl CompletionProvider for MockLLMProvider {
        async fn complete(
            &self,
            _req: &CompletionRequest,
            _json_schema: Option<StructuredOutputFormat>,
        ) -> Result<CompletionResponse, LLMError> {
            Ok(CompletionResponse {
                text: "Mock completion".to_string(),
            })
        }
    }

    #[async_trait]
    impl EmbeddingProvider for MockLLMProvider {
        async fn embed(&self, _text: Vec<String>) -> Result<Vec<Vec<f32>>, LLMError> {
            Ok(vec![vec![0.1, 0.2, 0.3]])
        }
    }

    #[async_trait]
    impl ModelsProvider for MockLLMProvider {}

    impl LLMProvider for MockLLMProvider {}

    struct MockChatResponse {
        text: Option<String>,
    }

    impl ChatResponse for MockChatResponse {
        fn text(&self) -> Option<String> {
            self.text.clone()
        }

        fn tool_calls(&self) -> Option<Vec<ToolCall>> {
            None
        }
    }

    impl std::fmt::Debug for MockChatResponse {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "MockChatResponse")
        }
    }

    impl std::fmt::Display for MockChatResponse {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "{}", self.text.as_deref().unwrap_or(""))
        }
    }

    #[test]
    fn test_executor_config_default() {
        let config = ExecutorConfig::default();
        assert_eq!(config.max_turns, 10);
    }

    #[test]
    fn test_executor_config_custom() {
        let config = ExecutorConfig { max_turns: 5 };
        assert_eq!(config.max_turns, 5);
    }

    #[test]
    fn test_executor_config_clone() {
        let config = ExecutorConfig { max_turns: 15 };
        let cloned = config.clone();
        assert_eq!(config.max_turns, cloned.max_turns);
    }

    #[test]
    fn test_executor_config_debug() {
        let config = ExecutorConfig { max_turns: 20 };
        let debug_str = format!("{config:?}");
        assert!(debug_str.contains("ExecutorConfig"));
        assert!(debug_str.contains("20"));
    }

    #[test]
    fn test_turn_result_continue() {
        let result = TurnResult::<String>::Continue(Some("partial".to_string()));
        match result {
            TurnResult::Continue(Some(data)) => assert_eq!(data, "partial"),
            _ => panic!("Expected Continue variant"),
        }
    }

    #[test]
    fn test_turn_result_continue_none() {
        let result = TurnResult::<String>::Continue(None);
        match result {
            TurnResult::Continue(None) => {}
            _ => panic!("Expected Continue(None) variant"),
        }
    }

    #[test]
    fn test_turn_result_complete() {
        let result = TurnResult::Complete("final".to_string());
        match result {
            TurnResult::Complete(data) => assert_eq!(data, "final"),
            _ => panic!("Expected Complete variant"),
        }
    }

    #[test]
    fn test_turn_result_debug() {
        let result = TurnResult::Complete("test".to_string());
        let debug_str = format!("{result:?}");
        assert!(debug_str.contains("Complete"));
        assert!(debug_str.contains("test"));
    }

    #[tokio::test]
    async fn test_mock_executor_success() {
        let executor = MockExecutor::new(false);
        let llm = Arc::new(MockLLMProvider);
        let task = Task::new("test task");
        let (tx_event, _rx_event) = mpsc::channel(100);
        let context = Context::new(llm, Some(tx_event));

        let result = executor.execute(&task, Arc::new(context)).await;

        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output.message, "Processed: test task");
    }

    #[tokio::test]
    async fn test_mock_executor_failure() {
        let executor = MockExecutor::new(true);
        let llm = Arc::new(MockLLMProvider);
        let task = Task::new("test task");
        let (tx_event, _rx_event) = mpsc::channel(100);
        let context = Context::new(llm, Some(tx_event));

        let result = executor.execute(&task, Arc::new(context)).await;

        assert!(result.is_err());
        let error = result.unwrap_err();
        assert_eq!(error.to_string(), "Test error: Mock execution failed");
    }

    #[test]
    fn test_mock_executor_config() {
        let executor = MockExecutor::with_max_turns(3);
        let config = executor.config();
        assert_eq!(config.max_turns, 3);
    }

    #[test]
    fn test_mock_executor_config_default() {
        let executor = MockExecutor::new(false);
        let config = executor.config();
        assert_eq!(config.max_turns, 5);
    }

    #[test]
    fn test_test_output_serialization() {
        let output = TestOutput {
            message: "test message".to_string(),
        };
        let serialized = serde_json::to_string(&output).unwrap();
        assert!(serialized.contains("test message"));
    }

    #[test]
    fn test_test_output_deserialization() {
        let json = r#"{"message":"test message"}"#;
        let output: TestOutput = serde_json::from_str(json).unwrap();
        assert_eq!(output.message, "test message");
    }

    #[test]
    fn test_test_output_clone() {
        let output = TestOutput {
            message: "original".to_string(),
        };
        let cloned = output.clone();
        assert_eq!(output.message, cloned.message);
    }

    #[test]
    fn test_test_output_debug() {
        let output = TestOutput {
            message: "debug test".to_string(),
        };
        let debug_str = format!("{output:?}");
        assert!(debug_str.contains("TestOutput"));
        assert!(debug_str.contains("debug test"));
    }

    #[test]
    fn test_test_output_into_value() {
        let output = TestOutput {
            message: "value test".to_string(),
        };
        let value: Value = output.into();
        assert_eq!(value["message"], "value test");
    }

    #[test]
    fn test_test_error_display() {
        let error = TestError::TestError("display test".to_string());
        assert_eq!(error.to_string(), "Test error: display test");
    }

    #[test]
    fn test_test_error_debug() {
        let error = TestError::TestError("debug test".to_string());
        let debug_str = format!("{error:?}");
        assert!(debug_str.contains("TestError"));
        assert!(debug_str.contains("debug test"));
    }

    #[test]
    fn test_test_error_source() {
        let error = TestError::TestError("source test".to_string());
        assert!(error.source().is_none());
    }
}