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
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
use crate::agent::executor::event_helper::EventHelper;
use crate::agent::executor::turn_engine::{
    TurnDelta, TurnEngine, TurnEngineConfig, TurnEngineError, TurnEngineOutput, record_task_state,
};
use crate::agent::hooks::HookOutcome;
use crate::agent::task::Task;
use crate::agent::{AgentDeriveT, AgentExecutor, AgentHooks, Context, ExecutorConfig};
use crate::channel::channel;
use crate::tool::{ToolCallResult, ToolT};
use crate::utils::{receiver_into_stream, spawn_future};
use async_trait::async_trait;
use autoagents_llm::ToolCall;
use autoagents_llm::error::LLMError;
use futures::Stream;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::ops::Deref;
use std::pin::Pin;
use std::sync::Arc;

/// Output of the Basic executor
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BasicAgentOutput {
    pub response: String,
    pub done: bool,
}

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

impl BasicAgentOutput {
    /// Try to parse the response string as structured JSON of type `T`.
    /// Returns `serde_json::Error` if parsing fails.
    pub fn try_parse<T: for<'de> serde::Deserialize<'de>>(&self) -> Result<T, serde_json::Error> {
        serde_json::from_str::<T>(&self.response)
    }

    /// Parse the response string as structured JSON of type `T`, or map the raw
    /// text into `T` using the provided fallback function if parsing fails.
    pub fn parse_or_map<T, F>(&self, fallback: F) -> T
    where
        T: for<'de> serde::Deserialize<'de>,
        F: FnOnce(&str) -> T,
    {
        self.try_parse::<T>()
            .unwrap_or_else(|_| fallback(&self.response))
    }
}

/// Error type for Basic executor
#[derive(Debug, thiserror::Error)]
pub enum BasicExecutorError {
    #[error("LLM error: {0}")]
    LLMError(
        #[from]
        #[source]
        LLMError,
    ),

    #[error("Other error: {0}")]
    Other(String),
}

impl From<TurnEngineError> for BasicExecutorError {
    fn from(error: TurnEngineError) -> Self {
        match error {
            TurnEngineError::LLMError(err) => err.into(),
            TurnEngineError::Aborted => {
                BasicExecutorError::Other("Run aborted by hook".to_string())
            }
            TurnEngineError::Other(err) => BasicExecutorError::Other(err),
        }
    }
}

/// Wrapper type for the single-turn Basic executor.
///
/// Use `BasicAgent<T>` when you want a single request/response interaction
/// with optional streaming but without tool calling or multi-turn loops.
#[derive(Debug)]
pub struct BasicAgent<T: AgentDeriveT> {
    inner: Arc<T>,
}

impl<T: AgentDeriveT> Clone for BasicAgent<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<T: AgentDeriveT> BasicAgent<T> {
    pub fn new(inner: T) -> Self {
        Self {
            inner: Arc::new(inner),
        }
    }
}

impl<T: AgentDeriveT> Deref for BasicAgent<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

/// Implement AgentDeriveT for the wrapper by delegating to the inner type
#[async_trait]
impl<T: AgentDeriveT> AgentDeriveT for BasicAgent<T> {
    type Output = <T as AgentDeriveT>::Output;

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

    fn output_schema(&self) -> Option<Value> {
        self.inner.output_schema()
    }

    fn name(&self) -> &str {
        self.inner.name()
    }

    fn tools(&self) -> Vec<Box<dyn ToolT>> {
        self.inner.tools()
    }
}

#[async_trait]
impl<T> AgentHooks for BasicAgent<T>
where
    T: AgentDeriveT + AgentHooks + Send + Sync + 'static,
{
    async fn on_agent_create(&self) {
        self.inner.on_agent_create().await
    }

    async fn on_run_start(&self, task: &Task, ctx: &Context) -> HookOutcome {
        self.inner.on_run_start(task, ctx).await
    }

    async fn on_run_complete(&self, task: &Task, result: &Self::Output, ctx: &Context) {
        self.inner.on_run_complete(task, result, ctx).await
    }

    async fn on_turn_start(&self, turn_index: usize, ctx: &Context) {
        self.inner.on_turn_start(turn_index, ctx).await
    }

    async fn on_turn_complete(&self, turn_index: usize, ctx: &Context) {
        self.inner.on_turn_complete(turn_index, ctx).await
    }

    async fn on_tool_call(&self, tool_call: &ToolCall, ctx: &Context) -> HookOutcome {
        self.inner.on_tool_call(tool_call, ctx).await
    }

    async fn on_tool_start(&self, tool_call: &ToolCall, ctx: &Context) {
        self.inner.on_tool_start(tool_call, ctx).await
    }

    async fn on_tool_result(&self, tool_call: &ToolCall, result: &ToolCallResult, ctx: &Context) {
        self.inner.on_tool_result(tool_call, result, ctx).await
    }

    async fn on_tool_error(&self, tool_call: &ToolCall, err: Value, ctx: &Context) {
        self.inner.on_tool_error(tool_call, err, ctx).await
    }
    async fn on_agent_shutdown(&self) {
        self.inner.on_agent_shutdown().await
    }
}

/// Implementation of AgentExecutor for the BasicExecutorWrapper
#[async_trait]
impl<T: AgentDeriveT + AgentHooks> AgentExecutor for BasicAgent<T> {
    type Output = BasicAgentOutput;
    type Error = BasicExecutorError;

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

    async fn execute(
        &self,
        task: &Task,
        context: Arc<Context>,
    ) -> Result<Self::Output, Self::Error> {
        record_task_state(&context, task);
        let tx_event = context.tx().ok();
        EventHelper::send_task_started(
            &tx_event,
            task.submission_id,
            context.config().id,
            context.config().name.clone(),
            task.prompt.clone(),
        )
        .await;

        let engine = TurnEngine::new(TurnEngineConfig::basic(self.config().max_turns));
        let mut turn_state = engine.turn_state(&context);
        let turn_result = engine
            .run_turn(
                self,
                task,
                &context,
                &mut turn_state,
                0,
                self.config().max_turns,
            )
            .await?;

        let output = extract_turn_output(turn_result);

        Ok(BasicAgentOutput {
            response: output.response,
            done: true,
        })
    }

    async fn execute_stream(
        &self,
        task: &Task,
        context: Arc<Context>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<Self::Output, Self::Error>> + Send>>, Self::Error>
    {
        record_task_state(&context, task);
        let tx_event = context.tx().ok();
        EventHelper::send_task_started(
            &tx_event,
            task.submission_id,
            context.config().id,
            context.config().name.clone(),
            task.prompt.clone(),
        )
        .await;

        let engine = TurnEngine::new(TurnEngineConfig::basic(self.config().max_turns));
        let mut turn_state = engine.turn_state(&context);
        let context_clone = context.clone();
        let task = task.clone();
        let executor = self.clone();

        let (tx, rx) = channel::<Result<BasicAgentOutput, BasicExecutorError>>(100);

        spawn_future(async move {
            let turn_stream = engine
                .run_turn_stream(
                    executor,
                    &task,
                    context_clone.clone(),
                    &mut turn_state,
                    0,
                    1,
                )
                .await;

            let mut final_response = String::default();
            match turn_stream {
                Ok(mut stream) => {
                    use futures::StreamExt;
                    while let Some(delta_result) = stream.next().await {
                        match delta_result {
                            Ok(TurnDelta::Text(content)) => {
                                let _ = tx
                                    .send(Ok(BasicAgentOutput {
                                        response: content,
                                        done: false,
                                    }))
                                    .await;
                            }
                            Ok(TurnDelta::ReasoningContent(_)) => {}
                            Ok(TurnDelta::ToolResults(_)) => {}
                            Ok(TurnDelta::Done(result)) => {
                                let output = extract_turn_output(result);
                                final_response = output.response.clone();
                                let _ = tx
                                    .send(Ok(BasicAgentOutput {
                                        response: output.response,
                                        done: true,
                                    }))
                                    .await;
                                break;
                            }
                            Err(err) => {
                                let _ = tx.send(Err(err.into())).await;
                                return;
                            }
                        }
                    }
                }
                Err(err) => {
                    let _ = tx.send(Err(err.into())).await;
                    return;
                }
            }

            let tx_event = context_clone.tx().ok();
            EventHelper::send_stream_complete(&tx_event, task.submission_id).await;
            let output = BasicAgentOutput {
                response: final_response,
                done: true,
            };
            let result =
                serde_json::to_string_pretty(&output).unwrap_or_else(|_| output.response.clone());
            EventHelper::send_task_completed(
                &tx_event,
                task.submission_id,
                context_clone.config().id,
                context_clone.config().name.clone(),
                result,
            )
            .await;
        });

        Ok(receiver_into_stream(rx))
    }
}

fn extract_turn_output(
    result: crate::agent::executor::TurnResult<TurnEngineOutput>,
) -> TurnEngineOutput {
    match result {
        crate::agent::executor::TurnResult::Complete(output) => output,
        crate::agent::executor::TurnResult::Continue(Some(output)) => output,
        crate::agent::executor::TurnResult::Continue(None) => TurnEngineOutput {
            response: String::default(),
            reasoning_content: String::default(),
            tool_calls: Vec::default(),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::AgentDeriveT;
    use crate::tests::{ConfigurableLLMProvider, MockAgentImpl, MockLLMProvider};
    use async_trait::async_trait;
    use autoagents_llm::chat::{StreamChoice, StreamDelta, StreamResponse};
    use std::sync::Arc;

    #[derive(Debug, Clone)]
    struct AbortAgent;

    #[async_trait]
    impl AgentDeriveT for AbortAgent {
        type Output = String;

        fn description(&self) -> &str {
            "abort"
        }

        fn output_schema(&self) -> Option<Value> {
            None
        }

        fn name(&self) -> &str {
            "abort_agent"
        }

        fn tools(&self) -> Vec<Box<dyn ToolT>> {
            vec![]
        }
    }

    #[async_trait]
    impl AgentHooks for AbortAgent {
        async fn on_run_start(&self, _task: &Task, _ctx: &Context) -> HookOutcome {
            HookOutcome::Abort
        }
    }

    #[tokio::test]
    async fn test_basic_agent_execute() {
        use crate::agent::task::Task;
        use crate::agent::{AgentConfig, Context};
        use autoagents_protocol::ActorID;

        let mock_agent = MockAgentImpl::new("test_agent", "Test agent description");
        let basic_agent = BasicAgent::new(mock_agent);

        let llm = Arc::new(MockLLMProvider {});
        let config = AgentConfig {
            id: ActorID::new_v4(),
            name: "test_agent".to_string(),
            description: "Test agent description".to_string(),
            output_schema: None,
        };

        let context = Context::new(llm, None).with_config(config);

        let context_arc = Arc::new(context);
        let task = Task::new("Test task");
        let result = basic_agent.execute(&task, context_arc).await;

        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output.response, "Mock response");
        assert!(output.done);
    }

    #[test]
    fn test_basic_agent_metadata_and_output_conversion() {
        let mock_agent = MockAgentImpl::new("test_agent", "Test agent description");
        let basic_agent = BasicAgent::new(mock_agent);

        let config = basic_agent.config();
        assert_eq!(config.max_turns, 1);

        let cloned = basic_agent.clone();
        assert_eq!(cloned.name(), "test_agent");
        assert_eq!(cloned.description(), "Test agent description");

        let output = BasicAgentOutput {
            response: "Test response".to_string(),
            done: true,
        };
        let value: Value = output.clone().into();
        assert_eq!(value["response"], "Test response");
        let string: String = output.into();
        assert_eq!(string, "Test response");
    }

    #[test]
    fn test_basic_agent_output_try_parse_success() {
        let output = BasicAgentOutput {
            response: r#"{"name":"test","value":42}"#.to_string(),
            done: true,
        };
        #[derive(serde::Deserialize, PartialEq, Debug)]
        struct Data {
            name: String,
            value: i32,
        }
        let parsed: Data = output.try_parse().unwrap();
        assert_eq!(
            parsed,
            Data {
                name: "test".to_string(),
                value: 42
            }
        );
    }

    #[test]
    fn test_basic_agent_output_try_parse_failure() {
        let output = BasicAgentOutput {
            response: "not json".to_string(),
            done: true,
        };
        let result = output.try_parse::<serde_json::Value>();
        assert!(result.is_err());
    }

    #[test]
    fn test_basic_agent_output_parse_or_map_fallback() {
        let output = BasicAgentOutput {
            response: "plain text".to_string(),
            done: true,
        };
        let result: String = output.parse_or_map(|s| s.to_uppercase());
        assert_eq!(result, "PLAIN TEXT");
    }

    #[test]
    fn test_basic_agent_output_parse_or_map_success() {
        let output = BasicAgentOutput {
            response: r#""hello""#.to_string(),
            done: true,
        };
        let result: String = output.parse_or_map(|s| s.to_uppercase());
        assert_eq!(result, "hello");
    }

    #[test]
    fn test_error_from_turn_engine_llm() {
        let err: BasicExecutorError =
            TurnEngineError::LLMError(LLMError::Generic("bad".to_string())).into();
        assert!(matches!(err, BasicExecutorError::LLMError(_)));
        assert!(err.to_string().contains("bad"));
    }

    #[test]
    fn test_error_from_turn_engine_aborted() {
        let err: BasicExecutorError = TurnEngineError::Aborted.into();
        assert!(matches!(err, BasicExecutorError::Other(_)));
        assert!(err.to_string().contains("aborted"));
    }

    #[test]
    fn test_error_from_turn_engine_other() {
        let err: BasicExecutorError = TurnEngineError::Other("misc".to_string()).into();
        assert!(matches!(err, BasicExecutorError::Other(_)));
        assert!(err.to_string().contains("misc"));
    }

    #[test]
    fn test_extract_turn_output_complete() {
        let result = crate::agent::executor::TurnResult::Complete(
            crate::agent::executor::turn_engine::TurnEngineOutput {
                response: "done".to_string(),
                reasoning_content: String::default(),
                tool_calls: Vec::new(),
            },
        );
        let output = extract_turn_output(result);
        assert_eq!(output.response, "done");
    }

    #[test]
    fn test_extract_turn_output_continue_some() {
        let result = crate::agent::executor::TurnResult::Continue(Some(
            crate::agent::executor::turn_engine::TurnEngineOutput {
                response: "partial".to_string(),
                reasoning_content: String::default(),
                tool_calls: Vec::new(),
            },
        ));
        let output = extract_turn_output(result);
        assert_eq!(output.response, "partial");
    }

    #[test]
    fn test_extract_turn_output_continue_none() {
        let result = crate::agent::executor::TurnResult::Continue(None);
        let output = extract_turn_output(result);
        assert!(output.response.is_empty());
        assert!(output.tool_calls.is_empty());
    }

    #[tokio::test]
    async fn test_basic_agent_execute_stream_returns_output() {
        use crate::agent::{AgentConfig, Context};
        use autoagents_protocol::ActorID;
        use futures::StreamExt;

        let llm = Arc::new(ConfigurableLLMProvider {
            structured_stream: vec![
                StreamResponse {
                    choices: vec![StreamChoice {
                        delta: StreamDelta {
                            content: Some("Hello ".to_string()),
                            reasoning_content: None,
                            tool_calls: None,
                        },
                    }],
                    usage: None,
                },
                StreamResponse {
                    choices: vec![StreamChoice {
                        delta: StreamDelta {
                            content: Some("world".to_string()),
                            reasoning_content: None,
                            tool_calls: None,
                        },
                    }],
                    usage: None,
                },
            ],
            ..ConfigurableLLMProvider::default()
        });

        let mock_agent = MockAgentImpl::new("stream_agent", "desc");
        let basic_agent = BasicAgent::new(mock_agent);
        let config = AgentConfig {
            id: ActorID::new_v4(),
            name: "stream_agent".to_string(),
            description: "desc".to_string(),
            output_schema: None,
        };
        let context = Arc::new(Context::new(llm, None).with_config(config));
        let task = Task::new("Test task");

        let mut stream = basic_agent.execute_stream(&task, context).await.unwrap();
        let mut final_output = None;
        while let Some(item) = stream.next().await {
            let output = item.unwrap();
            if output.done {
                final_output = Some(output);
                break;
            }
        }

        let output = final_output.expect("final output");
        assert_eq!(output.response, "Hello world");
        assert!(output.done);
    }

    #[tokio::test]
    async fn test_basic_agent_execute_stream_ignores_reasoning_output() {
        use crate::agent::{AgentConfig, Context};
        use autoagents_protocol::ActorID;
        use futures::StreamExt;

        let llm = Arc::new(ConfigurableLLMProvider {
            structured_stream: vec![
                StreamResponse {
                    choices: vec![StreamChoice {
                        delta: StreamDelta {
                            content: None,
                            reasoning_content: Some("plan".to_string()),
                            tool_calls: None,
                        },
                    }],
                    usage: None,
                },
                StreamResponse {
                    choices: vec![StreamChoice {
                        delta: StreamDelta {
                            content: Some("done".to_string()),
                            reasoning_content: None,
                            tool_calls: None,
                        },
                    }],
                    usage: None,
                },
            ],
            ..ConfigurableLLMProvider::default()
        });

        let mock_agent = MockAgentImpl::new("stream_agent_reasoning", "desc");
        let basic_agent = BasicAgent::new(mock_agent);
        let config = AgentConfig {
            id: ActorID::new_v4(),
            name: "stream_agent_reasoning".to_string(),
            description: "desc".to_string(),
            output_schema: None,
        };
        let context = Arc::new(Context::new(llm, None).with_config(config));
        let task = Task::new("Test task");

        let mut stream = basic_agent.execute_stream(&task, context).await.unwrap();
        let mut outputs = Vec::new();
        while let Some(item) = stream.next().await {
            outputs.push(item.unwrap());
        }

        assert_eq!(outputs.len(), 2);
        assert_eq!(outputs[0].response, "done");
        assert!(!outputs[0].done);
        assert_eq!(outputs[1].response, "done");
        assert!(outputs[1].done);
    }

    #[tokio::test]
    async fn test_basic_agent_run_aborts_on_hook() {
        use crate::agent::AgentBuilder;
        use crate::agent::direct::DirectAgent;
        use crate::agent::error::RunnableAgentError;

        let agent = BasicAgent::new(AbortAgent);
        let llm = Arc::new(MockLLMProvider {});
        let handle = AgentBuilder::<_, DirectAgent>::new(agent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");
        let task = Task::new("abort");

        let err = handle.agent.run(task).await.expect_err("expected abort");
        assert!(matches!(err, RunnableAgentError::Abort));
    }

    #[tokio::test]
    async fn test_basic_agent_run_stream_aborts_on_hook() {
        use crate::agent::AgentBuilder;
        use crate::agent::direct::DirectAgent;
        use crate::agent::error::RunnableAgentError;

        let agent = BasicAgent::new(AbortAgent);
        let llm = Arc::new(MockLLMProvider {});
        let handle = AgentBuilder::<_, DirectAgent>::new(agent)
            .llm(llm)
            .build()
            .await
            .expect("build should succeed");
        let task = Task::new("abort");

        let err = match handle.agent.run_stream(task).await {
            Ok(_) => panic!("expected abort"),
            Err(err) => err,
        };
        assert!(matches!(err, RunnableAgentError::Abort));
    }
}