autogpt 0.1.15

🦀 A Pure Rust Framework For Building AGIs.
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
//! # `AgentGPT` agent.
//!

use crate::common::utils::{
    Capability, Communication, ContextManager, Knowledge, Persona, Planner, Reflection, Status,
    Task, TaskScheduler, Tool, default_eval_fn,
};
use crate::traits::agent::Agent;
use derivative::Derivative;
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
#[cfg(feature = "net")]
use {
    crate::collaboration::{AgentNet, Collaborator, RemoteAgent, delegate_task},
    crate::common::utils::AgentMessage,
    crate::traits::functions::Collaborate,
    anyhow::{Result, anyhow},
    async_trait::async_trait,
    iac_rs::prelude::*,
    std::collections::VecDeque,
    std::sync::Arc,
    std::time::Duration,
    tokio::sync::Mutex,
};

/// Represents an agent with memory, tools, and other autonomous capabilities.
#[derive(Derivative)]
#[derivative(PartialEq, Debug, Clone)]
pub struct AgentGPT {
    /// Unique identifier for the agent.
    pub id: Cow<'static, str>,

    /// The objective or mission of the agent.
    pub objective: Cow<'static, str>,

    /// The logical or physical position of the agent.
    pub position: Cow<'static, str>,

    /// The current operational status of the agent.
    pub status: Status,

    /// Hot memory containing past communications.
    pub memory: Vec<Communication>,

    /// Tools available to the agent.
    pub tools: Vec<Tool>,

    /// Structured knowledge base used for reasoning or retrieval.
    pub knowledge: Knowledge,

    /// Optional planner to manage goal sequencing.
    pub planner: Option<Planner>,

    /// Persona defines behavior style and traits.
    pub persona: Persona,

    /// Optional self-reflection module for introspection or evaluation.
    pub reflection: Option<Reflection>,

    /// Optional task scheduler for time-based goal management.
    pub scheduler: Option<TaskScheduler>,

    /// Capabilities this agent has access to (e.g. CodeGen, WebSearch).
    pub capabilities: HashSet<Capability>,

    /// Manages context for conversation and topic focus.
    pub context: ContextManager,

    /// List of tasks assigned to this agent.
    pub tasks: Vec<Task>,

    /// Cryptographic signer for agent authentication and message integrity.
    #[cfg(feature = "net")]
    pub signer: Signer,

    /// Map of verifier instances used to verify signatures from peers.
    #[cfg(feature = "net")]
    pub verifiers: HashMap<String, Verifier>,

    /// Network address this agent binds to for communication (e.g., "0.0.0.0:8080").
    #[cfg(feature = "net")]
    pub addr: String,

    /// Connected client sessions to peer agents.
    #[cfg(feature = "net")]
    #[derivative(PartialEq = "ignore")]
    pub clients: HashMap<String, Arc<Mutex<Client>>>,

    /// Optional server instance handling incoming peer connections.
    #[cfg(feature = "net")]
    #[derivative(PartialEq = "ignore")]
    pub server: Option<Arc<Mutex<Server>>>,

    /// Interval for sending heartbeat signals to peers for liveness detection.
    #[cfg(feature = "net")]
    pub heartbeat_interval: Duration,

    /// Map of peer agent identifiers to their network addresses.
    #[cfg(feature = "net")]
    pub peer_addresses: HashMap<String, String>,

    /// Other agents this agent collaborates with, running in the same memory
    /// space/thread or within the same runtime.
    #[cfg(feature = "net")]
    #[derivative(PartialEq = "ignore")]
    pub local_collaborators: HashMap<String, Collaborator>,

    /// Other agents this agent collaborates with via the network, using
    /// inter/intra-agent communication (IAC) protocols.
    #[cfg(feature = "net")]
    #[derivative(PartialEq = "ignore")]
    pub remote_collaborators: HashMap<String, Collaborator>,

    /// Maps capabilities to a round-robin queue of peer agent IDs
    /// for distributing tasks across collaborators.
    #[cfg(feature = "net")]
    pub cap_index: HashMap<Capability, VecDeque<String>>,

    /// Round-robin index used to evenly distribute workload among peers.
    #[cfg(feature = "net")]
    pub rr_idx: usize,
}

impl Default for AgentGPT {
    fn default() -> Self {
        Self {
            id: Cow::Owned(Uuid::new_v4().to_string()),
            objective: Cow::Borrowed(""),
            position: Cow::Borrowed(""),
            status: Status::default(),
            memory: vec![],
            tools: vec![],
            knowledge: Knowledge::default(),
            planner: None,
            persona: Persona {
                name: Cow::Borrowed("Default"),
                traits: vec![],
                behavior_script: None,
            },
            reflection: None,
            scheduler: None,
            capabilities: HashSet::new(),
            context: ContextManager {
                recent_messages: vec![],
                focus_topics: vec![],
            },
            tasks: vec![],
            #[cfg(feature = "net")]
            signer: Signer::new(KeyPair::generate()),
            #[cfg(feature = "net")]
            verifiers: HashMap::new(),
            #[cfg(feature = "net")]
            addr: "0.0.0.0:0".to_string(),
            #[cfg(feature = "net")]
            clients: HashMap::new(),
            #[cfg(feature = "net")]
            server: None,
            #[cfg(feature = "net")]
            heartbeat_interval: Duration::from_secs(30),
            #[cfg(feature = "net")]
            peer_addresses: HashMap::new(),
            #[cfg(feature = "net")]
            local_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            remote_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            cap_index: HashMap::new(),
            #[cfg(feature = "net")]
            rr_idx: 0,
        }
    }
}

impl AgentGPT {
    /// Adds a communication to the memory of the agent.
    ///
    /// # Arguments
    ///
    /// * `communication` - The communication to be added to the memory.
    pub fn add_communication(&mut self, communication: Communication) {
        self.memory.push(communication);
    }

    /// Creates a new instance of `AgentGPT` with owned strings.
    ///
    /// # Arguments
    ///
    /// * `objective` - The objective of the agent.
    /// * `position` - The position of the agent.
    ///
    /// # Returns
    ///
    /// A new fully initialized instance of `AgentGPT`.
    pub fn new_owned(objective: String, position: String) -> Self {
        Self {
            id: Cow::Owned(Uuid::new_v4().to_string()),
            objective: Cow::Owned(objective),
            position: Cow::Owned(position.clone()),
            status: Status::Idle,

            memory: vec![],

            tools: vec![],

            knowledge: Knowledge {
                facts: HashMap::default(),
            },

            planner: Some(Planner {
                current_plan: vec![],
            }),

            persona: Persona {
                name: position.into(),
                traits: vec![],
                behavior_script: None,
            },

            reflection: Some(Reflection {
                recent_logs: vec![],
                evaluation_fn: default_eval_fn,
            }),

            scheduler: Some(TaskScheduler {
                scheduled_tasks: vec![],
            }),

            capabilities: HashSet::default(),

            context: ContextManager {
                recent_messages: vec![],
                focus_topics: vec![],
            },

            tasks: vec![],
            #[cfg(feature = "net")]
            signer: Signer::new(KeyPair::generate()),
            #[cfg(feature = "net")]
            verifiers: HashMap::new(),
            #[cfg(feature = "net")]
            addr: "0.0.0.0:0".to_string(),
            #[cfg(feature = "net")]
            clients: HashMap::new(),
            #[cfg(feature = "net")]
            server: None,
            #[cfg(feature = "net")]
            heartbeat_interval: Duration::from_secs(30),
            #[cfg(feature = "net")]
            peer_addresses: HashMap::new(),
            #[cfg(feature = "net")]
            local_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            remote_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            cap_index: HashMap::new(),
            #[cfg(feature = "net")]
            rr_idx: 0,
        }
    }

    /// Creates a new instance of `AgentGPT` with borrowed string slices.
    ///
    /// # Arguments
    ///
    /// * `objective` - The objective of the agent.
    /// * `position` - The position of the agent.
    ///
    /// # Returns
    ///
    /// A new fully initialized instance of `AgentGPT`.
    pub fn new_borrowed(objective: &'static str, position: &'static str) -> Self {
        Self {
            id: Cow::Owned(Uuid::new_v4().to_string()),
            objective: Cow::Borrowed(objective),
            position: Cow::Borrowed(position),
            status: Status::Idle,

            memory: vec![],

            tools: vec![],

            knowledge: Knowledge {
                facts: HashMap::default(),
            },

            planner: Some(Planner {
                current_plan: vec![],
            }),

            persona: Persona {
                name: position.into(),
                traits: vec![],
                behavior_script: None,
            },

            reflection: Some(Reflection {
                recent_logs: vec![],
                evaluation_fn: default_eval_fn,
            }),

            scheduler: Some(TaskScheduler {
                scheduled_tasks: vec![],
            }),

            capabilities: HashSet::default(),

            context: ContextManager {
                recent_messages: vec![],
                focus_topics: vec![],
            },

            tasks: vec![],
            #[cfg(feature = "net")]
            signer: Signer::new(KeyPair::generate()),
            #[cfg(feature = "net")]
            verifiers: HashMap::new(),
            #[cfg(feature = "net")]
            addr: "0.0.0.0:0".to_string(),
            #[cfg(feature = "net")]
            clients: HashMap::new(),
            #[cfg(feature = "net")]
            server: None,
            #[cfg(feature = "net")]
            heartbeat_interval: Duration::from_secs(30),
            #[cfg(feature = "net")]
            peer_addresses: HashMap::new(),
            #[cfg(feature = "net")]
            local_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            remote_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            cap_index: HashMap::new(),
            #[cfg(feature = "net")]
            rr_idx: 0,
        }
    }

    #[cfg(feature = "net")]
    pub async fn register_local(&mut self, collab: Collaborator, caps: Vec<Capability>) {
        let id = collab.id().await;
        self.local_collaborators.insert(id.clone(), collab);
        for cap in caps {
            self.cap_index.entry(cap).or_default().push_back(id.clone());
        }
    }

    #[cfg(feature = "net")]
    pub fn register_remote(&mut self, id: Cow<'static, str>, caps: Vec<Capability>) {
        let remote = Collaborator::Remote(RemoteAgent {
            id: id.clone(),
            signer: self.signer.clone(),
            clients: self.clients.clone(),
        });

        self.remote_collaborators
            .insert(id.to_string(), remote.clone());

        for cap in caps {
            self.cap_index
                .entry(cap)
                .or_default()
                .push_back(id.to_string());
        }
    }

    #[cfg(feature = "net")]
    pub async fn assign_task_lb(&mut self, cap: &Capability, task: Task) -> Result<()> {
        let queue = self
            .cap_index
            .get_mut(cap)
            .ok_or_else(|| anyhow!("No agent has capability: {:?}", cap))?;

        let id = queue[self.rr_idx % queue.len()].clone();
        self.rr_idx += 1;

        let collab = self
            .local_collaborators
            .get(&id)
            .or(self.remote_collaborators.get(&id))
            .ok_or_else(|| anyhow!("Collaborator with id {} not found", id))?;

        delegate_task(collab.clone(), task).await
    }
    #[cfg(feature = "net")]
    pub fn as_agent_net(&self) -> AgentNet {
        AgentNet {
            id: self.id.clone(),
            signer: self.signer.clone(),
            verifiers: self.verifiers.clone(),
            addr: self.addr.clone(),
            clients: self.clients.clone(),
            server: self.server.clone(),
            heartbeat_interval: self.heartbeat_interval,
            peer_addresses: self.peer_addresses.clone(),
        }
    }
}

impl Agent for AgentGPT {
    /// Creates a new `AgentGPT` instance with the given objective and position.
    fn new(objective: Cow<'static, str>, position: Cow<'static, str>) -> Self {
        Self {
            id: Cow::Owned(Uuid::new_v4().to_string()),

            objective,
            position: position.clone(),
            status: Status::Idle,

            memory: vec![],

            tools: vec![],

            knowledge: Knowledge {
                facts: HashMap::default(),
            },

            planner: Some(Planner {
                current_plan: vec![],
            }),

            persona: Persona {
                name: position,
                traits: vec![],
                behavior_script: None,
            },

            reflection: Some(Reflection {
                recent_logs: vec![],
                evaluation_fn: default_eval_fn,
            }),

            scheduler: Some(TaskScheduler {
                scheduled_tasks: vec![],
            }),

            capabilities: HashSet::default(),

            context: ContextManager {
                recent_messages: vec![],
                focus_topics: vec![],
            },

            tasks: vec![],
            #[cfg(feature = "net")]
            signer: Signer::new(KeyPair::generate()),
            #[cfg(feature = "net")]
            verifiers: HashMap::new(),
            #[cfg(feature = "net")]
            addr: "0.0.0.0:0".to_string(),
            #[cfg(feature = "net")]
            clients: HashMap::new(),
            #[cfg(feature = "net")]
            server: None,
            #[cfg(feature = "net")]
            heartbeat_interval: Duration::from_secs(30),
            #[cfg(feature = "net")]
            peer_addresses: HashMap::new(),
            #[cfg(feature = "net")]
            local_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            remote_collaborators: HashMap::new(),
            #[cfg(feature = "net")]
            cap_index: HashMap::new(),
            #[cfg(feature = "net")]
            rr_idx: 0,
        }
    }

    /// Updates the agent's operational status.
    fn update(&mut self, status: Status) {
        self.status = status;
    }

    /// Returns the agent's objective.
    fn objective(&self) -> &Cow<'static, str> {
        &self.objective
    }

    /// Returns the agent's current position.
    fn position(&self) -> &Cow<'static, str> {
        &self.position
    }

    /// Returns the agent's current status.
    fn status(&self) -> &Status {
        &self.status
    }

    /// Returns the agent's memory log of communications.
    fn memory(&self) -> &Vec<Communication> {
        &self.memory
    }

    /// Returns the agent's available tools.
    fn tools(&self) -> &Vec<Tool> {
        &self.tools
    }

    /// Returns the agent's structured knowledge base.
    fn knowledge(&self) -> &Knowledge {
        &self.knowledge
    }

    /// Returns an optional reference to the agent's planner.
    fn planner(&self) -> Option<&Planner> {
        self.planner.as_ref()
    }

    /// Returns the agent's persona configuration.
    fn persona(&self) -> &Persona {
        &self.persona
    }

    /// Returns a list of agents this agent collaborates with.
    #[cfg(feature = "net")]
    fn collaborators(&self) -> Vec<Collaborator> {
        let mut all = Vec::new();
        all.extend(self.local_collaborators.values().cloned());
        all.extend(self.remote_collaborators.values().cloned());
        all
    }

    /// Returns an optional reference to the self-reflection module.
    fn reflection(&self) -> Option<&Reflection> {
        self.reflection.as_ref()
    }

    /// Returns an optional reference to the agent's task scheduler.
    fn scheduler(&self) -> Option<&TaskScheduler> {
        self.scheduler.as_ref()
    }

    /// Returns the agent's registered capabilities.
    fn capabilities(&self) -> &HashSet<Capability> {
        &self.capabilities
    }

    /// Returns the context manager tracking recent communication and focus.
    fn context(&self) -> &ContextManager {
        &self.context
    }

    /// Returns the list of current tasks or tasks.
    fn tasks(&self) -> &Vec<Task> {
        &self.tasks
    }

    fn memory_mut(&mut self) -> &mut Vec<Communication> {
        &mut self.memory
    }

    fn planner_mut(&mut self) -> Option<&mut Planner> {
        self.planner.as_mut()
    }

    fn context_mut(&mut self) -> &mut ContextManager {
        &mut self.context
    }
}

#[cfg(feature = "net")]
impl AgentGPT {
    pub async fn broadcast_capabilities(&self) -> Result<()> {
        let msg = AgentMessage::CapabilityAdvert {
            sender_id: self.id.to_string(),
            capabilities: self.capabilities.iter().cloned().collect(),
        };

        let payload = serde_json::to_vec(&msg)?;

        for (peer_id, client) in &self.clients {
            let mut message = Message {
                from: self.id.clone().into(),
                to: peer_id.clone(),
                msg_type: MessageType::Broadcast,
                extra_data: payload.clone(),
                ..Default::default()
            };

            message.sign(&self.signer)?;
            client.lock().await.send(message).await?;
        }

        Ok(())
    }
}

#[async_trait]
#[cfg(feature = "net")]
impl Collaborate for AgentGPT {
    async fn handle_task(&mut self, task: Task) -> Result<()> {
        // TODO: implement this func
        let mut this = self.clone();
        this.tasks.push(task);
        Ok(())
    }

    async fn receive_message(&mut self, msg: AgentMessage) -> Result<()> {
        match msg {
            AgentMessage::Task(task) => self.handle_task(task).await,

            AgentMessage::CapabilityAdvert {
                sender_id,
                capabilities,
            } => {
                self.register_remote(sender_id.into(), capabilities);
                Ok(())
            }

            _ => Ok(()),
        }
    }

    fn get_id(&self) -> &str {
        &self.id
    }
}

#[async_trait]
#[cfg(feature = "net")]
impl Network for AgentGPT {
    async fn heartbeat(&self) {
        let clients = self.clients.clone();
        let peer_addresses = self.peer_addresses.clone();
        let signer = self.signer.clone();
        let id = self.id.to_string();
        let interval = self.heartbeat_interval;

        tokio::spawn(async move {
            loop {
                for (peer_id, client) in &clients {
                    let msg = Message::ping(&id, peer_id, 0);
                    let result = {
                        let client = client.lock().await;
                        client.send(msg).await
                    };

                    if let Err(e) = result {
                        debug!("Heartbeat failed to {peer_id}: {e}");

                        if let Some(addr) = peer_addresses.get(peer_id) {
                            debug!("Attempting to reconnect to {peer_id} at {addr}...");

                            match Client::connect(addr, signer.clone()).await {
                                Ok(new_client) => {
                                    debug!("Reconnected to {peer_id}");
                                    let mut locked = client.lock().await;
                                    *locked = new_client;
                                }
                                Err(err) => {
                                    debug!("Failed to reconnect to {peer_id}: {err}");
                                }
                            }
                        } else {
                            debug!("No known address for {peer_id}, cannot reconnect.");
                        }
                    }
                }

                tokio::time::sleep(interval).await;
            }
        });
    }

    async fn broadcast(&self, payload: &str) -> anyhow::Result<()> {
        let tasks = self.clients.iter().map(|(peer_id, client)| {
            let mut msg = Message::broadcast(&self.id, payload, 0);
            msg.to = peer_id.clone();
            let client = client.clone();
            async move {
                let send_result = {
                    let client_guard = client.lock().await;
                    client_guard.clone()
                }
                .send(msg)
                .await;

                if let Err(e) = send_result {
                    debug!("Broadcast to {peer_id} failed: {e}");
                } else {
                    debug!("Broadcast to {peer_id} succeeded");
                }
            }
        });

        futures::future::join_all(tasks).await;
        Ok(())
    }
}