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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
//! # `BackendGPT` agent.
//!
//! This module provides functionality for generating backend code for web servers
//! and JSON databases based on prompts using Gemini or OpenAI API. The `BackendGPT` agent
//! understands user requirements and produces code snippets in various programming
//! languages commonly used for backend development.
//!
//! # Example - Generating backend code:
//!
//! ```rust
//! use autogpt::agents::backend::BackendGPT;
//! use autogpt::common::utils::Task;
//! use autogpt::traits::functions::Functions;
//! use autogpt::traits::functions::AsyncFunctions;
//!
//! #[tokio::main]
//! async fn main() {
//!     let mut backend_agent = BackendGPT::new(
//!         "Generate backend code",
//!         "Backend Developer",
//!         "rust",
//!     ).await;
//!
//!     let mut tasks = Task {
//!         description: "Create REST API endpoints for user authentication".into(),
//!         scope: None,
//!         urls: None,
//!         frontend_code: None,
//!         backend_code: None,
//!         api_schema: None,
//!     };
//!
//!     if let Err(err) = backend_agent.execute(&mut tasks, true, false, 3).await {
//!         eprintln!("Error executing backend tasks: {:?}", err);
//!     }
//! }
//! ```
//!
#![allow(unreachable_code)]

use crate::agents::agent::AgentGPT;
#[cfg(feature = "net")]
use crate::collaboration::Collaborator;
#[cfg(feature = "cli")]
use crate::common::utils::spinner;
#[allow(unused_imports)]
use crate::common::utils::{
    Capability, ClientType, Communication, ContextManager, GenerationOutput, Goal, Knowledge,
    OutputKind, Persona, Planner, Reflection, Route, Scope, Status, Task, TaskScheduler, Tool,
    extract_array, strip_code_blocks,
};
use crate::prompts::backend::{
    API_ENDPOINTS_PROMPT, FIX_CODE_PROMPT, IMPROVED_WEBSERVER_CODE_PROMPT, WEBSERVER_CODE_PROMPT,
};
use crate::traits::agent::Agent;
use crate::traits::functions::{AsyncFunctions, Executor, Functions};
use auto_derive::Auto;
use std::path::Path;
use std::process::Stdio;
// use std::thread::sleep;

use anyhow::{Result, anyhow};
use async_trait::async_trait;
use colored::*;
use reqwest::Client as ReqClient;
use std::borrow::Cow;
use std::env::var;
use std::time::Duration;
use tokio::fs;
use tokio::io::AsyncReadExt;
use tokio::process::Child;
use tokio::process::Command;
use tracing::{debug, error, info, warn};
use webbrowser::{Browser, BrowserOptions, open_browser_with_options};

#[cfg(feature = "mem")]
use {
    crate::common::memory::load_long_term_memory, crate::common::memory::long_term_memory_context,
    crate::common::memory::save_long_term_memory,
};

#[cfg(feature = "oai")]
use {openai_dive::v1::models::FlagshipModel, openai_dive::v1::resources::chat::*};

#[cfg(feature = "cld")]
use anthropic_ai_sdk::types::message::{
    ContentBlock, CreateMessageParams, Message as AnthMessage, MessageClient,
    RequiredMessageParams, Role,
};

#[cfg(feature = "gem")]
use gems::{
    chat::ChatBuilder,
    imagen::ImageGenBuilder,
    messages::{Content, Message},
    models::Model,
    stream::StreamBuilder,
    traits::CTrait,
};

#[cfg(any(feature = "oai", feature = "gem", feature = "cld", feature = "xai"))]
use crate::traits::functions::ReqResponse;

#[cfg(feature = "xai")]
use x_ai::{
    chat_compl::{ChatCompletionsRequestBuilder, Message as XaiMessage},
    traits::ChatCompletionsFetcher,
};

/// Struct representing a BackendGPT, which manages backend development tasks using GPT.
#[derive(Debug, Clone, Default, Auto)]
#[allow(dead_code)]
pub struct BackendGPT {
    /// Represents the workspace directory path for BackendGPT.
    workspace: Cow<'static, str>,
    /// Represents the GPT agent responsible for handling backend tasks.
    agent: AgentGPT,
    /// Represents an OpenAI or Gemini client for interacting with their API.
    client: ClientType,
    /// Represents a client for making HTTP requests.
    req_client: ReqClient,
    /// Represents the bugs found in the codebase, if any.
    bugs: Option<Cow<'static, str>>,
    /// Represents the programming language used for backend development.
    language: &'static str,
    /// Represents the number of bugs found in the codebase.
    nb_bugs: u64,
}

impl BackendGPT {
    /// Constructor function to create a new instance of `BackendGPT`.
    ///
    /// # Arguments
    ///
    /// * `objective` - Objective description for `BackendGPT`.
    /// * `position` - Position description for `BackendGPT`.
    /// * `language` - Programming language used for backend development.
    ///
    /// # Returns
    ///
    /// (`BackendGPT`): A new instance of `BackendGPT`.
    ///
    /// # Business Logic
    ///
    /// - Constructs the workspace directory path for `BackendGPT`.
    /// - Initializes backend projects based on the specified language.
    /// - Initializes the GPT agent with the given objective and position.
    /// - Creates clients for interacting with Gemini or OpenAI API and making HTTP requests.
    #[allow(unused)]
    pub async fn new(
        objective: &'static str,
        position: &'static str,
        language: &'static str,
    ) -> Self {
        let base_workspace = var("AUTOGPT_WORKSPACE").unwrap_or_else(|_| "workspace".to_string());
        let workspace = format!("{base_workspace}/backend");

        if !fs::try_exists(&workspace).await.unwrap_or(false) {
            match fs::create_dir_all(&workspace).await {
                Ok(_) => debug!("Directory '{}' created successfully!", workspace),
                Err(e) => error!("Error creating directory '{}': {}", workspace, e),
            }
        } else {
            debug!("Workspace directory '{}' already exists.", workspace);
        }

        info!(
            "{}",
            format!("[*] {position:?}: 🛠️  Getting ready!")
                .bright_white()
                .bold()
        );

        match language {
            "rust" => {
                if !Path::new(&format!("{workspace}/Cargo.toml")).exists() {
                    let cargo_new = Command::new("cargo").arg("init").arg(&workspace).spawn();

                    match cargo_new {
                        Ok(_) => debug!("Cargo project initialized successfully."),
                        Err(e) => error!("Error initializing Cargo project: {}", e),
                    }
                }

                let template_path = format!("{workspace}/src/template.rs");
                if !Path::new(&template_path).exists() {
                    if let Err(e) = fs::write(&template_path, "").await {
                        error!("Error creating file '{}': {}", template_path, e);
                    } else {
                        debug!("File '{}' created successfully.", template_path);
                    }
                }
            }

            "python" => {
                let files = ["main.py", "template.py"];
                for file in files.iter() {
                    let full_path = format!("{workspace}/{file}");
                    if !Path::new(&full_path).exists() {
                        if let Err(e) = fs::write(&full_path, "").await {
                            error!("Error creating file '{}': {}", full_path, e);
                        } else {
                            debug!("File '{}' created successfully.", full_path);
                        }
                    }
                }
            }

            "javascript" => {
                if !Path::new(&format!("{workspace}/package.json")).exists() {
                    let npx_install = Command::new("npx")
                        .arg("create-react-app")
                        .arg(&workspace)
                        .stdout(Stdio::inherit())
                        .stderr(Stdio::inherit())
                        .spawn();

                    match npx_install {
                        Ok(mut child) => match child.wait().await {
                            Ok(status) => {
                                if status.success() {
                                    debug!("React JS project initialized successfully.");
                                } else {
                                    error!("Failed to initialize React JS project.");
                                }
                            }
                            Err(e) => {
                                error!("Error waiting for process: {}", e);
                            }
                        },
                        Err(e) => {
                            error!("Error initializing React JS project: {}", e);
                        }
                    }
                }

                let template_path = format!("{workspace}/src/template.js");
                if !Path::new(&template_path).exists() {
                    if let Err(e) = fs::write(&template_path, "").await {
                        error!("Error creating file '{}': {}", template_path, e);
                    } else {
                        debug!("File '{}' created successfully.", template_path);
                    }
                }
            }

            _ => panic!("Unsupported language '{language}'. Consider opening an issue/PR.",),
        }

        let mut agent: AgentGPT = AgentGPT::new_borrowed(objective, position);
        agent.id = agent.position().to_string().into();

        let client = ClientType::from_env();

        let req_client: ReqClient = ReqClient::builder()
            .timeout(Duration::from_secs(3))
            .build()
            .unwrap();

        Self {
            workspace: workspace.into(),
            agent,
            client,
            req_client,
            bugs: None,
            language,
            nb_bugs: 0,
        }
    }
    pub async fn build_request(
        &mut self,
        prompt: &str,
        tasks: &mut Task,
        output_type: OutputKind,
    ) -> Result<GenerationOutput> {
        #[cfg(feature = "mem")]
        {
            self.agent.memory = self.get_ltm().await?;
        }

        let request: String = format!(
            "{}\n\nTask Description: {}\nPrevious Conversation: {:?}",
            prompt,
            tasks.description,
            self.agent.memory(),
        );

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("user"),
            content: Cow::Owned(request.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("user"),
                    content: Cow::Owned(request.clone()),
                })
                .await;
        }

        #[allow(unused)]
        let mut response_text = String::new();

        #[cfg(any(feature = "oai", feature = "gem", feature = "cld", feature = "xai"))]
        {
            response_text = self.generate(&request).await?;
        }
        self.agent.add_communication(Communication {
            role: Cow::Borrowed("assistant"),
            content: Cow::Owned(response_text.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("assistant"),
                    content: Cow::Owned(response_text.clone()),
                })
                .await;
        }

        debug!("[*] {:?}: {:?}", self.agent.position(), self.agent);

        match output_type {
            OutputKind::Text => Ok(GenerationOutput::Text(strip_code_blocks(&response_text))),
            OutputKind::UrlList => {
                let urls: Vec<Cow<'static, str>> =
                    serde_json::from_str(&extract_array(&response_text).unwrap_or_default())?;
                tasks.urls = Some(urls.clone());
                self.agent.update(Status::InUnitTesting);
                Ok(GenerationOutput::UrlList(urls))
            }
            OutputKind::Scope => {
                let scope: Scope = serde_json::from_str(&strip_code_blocks(&response_text))?;
                Ok(GenerationOutput::Scope(scope))
            }
        }
    }

    /// Asynchronously generates backend code based on tasks and logs the interaction.
    ///
    /// # Arguments
    ///
    /// * `tasks` - A mutable reference to tasks to be processed.
    ///
    /// # Returns
    ///
    /// (`Result<String>`): Result containing the generated backend code.
    ///
    /// # Errors
    ///
    /// Returns an error if there's a failure in reading the template file,
    /// generating content via the Gemini or OpenAI API, or writing the output file.
    ///
    /// # Business Logic
    ///
    /// - Determines the file path based on the specified language.
    /// - Reads the template code from the specified file.
    /// - Constructs a request using the template code and project description.
    /// - Sends the request to the Gemini or OpenAI API to generate backend code.
    /// - Logs the user request and assistant response as communication history in the agent's memory.
    /// - Writes the generated backend code to the appropriate file based on language.
    /// - Updates the task's backend code and the agent's status to `Completed`.
    pub async fn generate_backend_code(&mut self, tasks: &mut Task) -> Result<String> {
        let path = self.workspace.clone();

        let backend_path = match self.language {
            "rust" => format!("{}/{}", path, "src/main.rs"),
            "python" => format!("{}/{}", path, "main.py"),
            "javascript" => format!("{}/{}", path, "src/index.js"),
            _ => panic!("Unsupported language, consider opening an Issue/PR"),
        };

        let template = fs::read_to_string(&backend_path).await?;

        let prompt = format!(
            "{}\n\nCode Template: {}\nProject Description: {}",
            WEBSERVER_CODE_PROMPT, template, tasks.description
        );

        let output = self.build_request(&prompt, tasks, OutputKind::Text).await?;

        let code = match output {
            GenerationOutput::Text(code) => code,
            _ => {
                return Err(anyhow!("Expected text output for backend code generation"));
            }
        };

        fs::write(&backend_path, &code).await?;
        tasks.backend_code = Some(code.clone().into());

        self.agent.update(Status::Completed);
        debug!("[*] {:?}: {:?}", self.agent.position(), self.agent);

        Ok(code)
    }

    /// Asynchronously improves existing backend code based on tasks,
    /// while logging communication between the agent and the AI.
    ///
    /// # Arguments
    ///
    /// * `tasks` - A mutable reference to tasks to be processed.
    ///
    /// # Returns
    ///
    /// (`Result<String>`): Result containing the improved backend code.
    ///
    /// # Errors
    ///
    /// Returns an error if there's a failure in improving the backend code.
    ///
    /// # Business Logic
    ///
    /// - Constructs a request based on the existing backend code and project description.
    /// - Logs the user's request as a `Communication`.
    /// - Sends the request to the Gemini or OpenAI API to generate improved code.
    /// - Logs the AI's response as a `Communication`.
    /// - Writes the improved backend code to the appropriate file.
    /// - Updates tasks and agent status accordingly.
    pub async fn improve_backend_code(&mut self, tasks: &mut Task) -> Result<String> {
        #[cfg(feature = "mem")]
        {
            self.agent.memory = self.get_ltm().await?;
        }

        let code_template = tasks.backend_code.clone().unwrap_or_default();
        let request = format!(
            "{}\n\nCode Template: {}\nProject Description: {}",
            IMPROVED_WEBSERVER_CODE_PROMPT, code_template, tasks.description
        );

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("user"),
            content: Cow::Owned(request.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("user"),
                    content: Cow::Owned(request.clone()),
                })
                .await;
        }

        #[allow(unused)]
        let mut response_text = String::new();

        #[cfg(any(feature = "oai", feature = "gem", feature = "cld", feature = "xai"))]
        {
            response_text = self.generate(&request).await?;
        }

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("assistant"),
            content: Cow::Owned(response_text.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("assistant"),
                    content: Cow::Owned(response_text.clone()),
                })
                .await;
        }

        let cleaned_code = strip_code_blocks(&response_text);

        let backend_path = match self.language {
            "rust" => format!("{}/src/main.rs", self.workspace),
            "python" => format!("{}/main.py", self.workspace),
            "javascript" => format!("{}/src/index.js", self.workspace),
            _ => return Err(anyhow!("Unsupported language")),
        };

        debug!(
            "[*] {:?}: Writing to {}",
            self.agent.position(),
            backend_path
        );

        fs::write(&backend_path, &cleaned_code).await?;

        tasks.backend_code = Some(cleaned_code.clone().into());

        self.agent.update(Status::Completed);

        debug!("[*] {:?}: {:?}", self.agent.position(), self.agent);

        Ok(cleaned_code)
    }

    /// Asynchronously fixes bugs in the backend code based on tasks,
    /// while logging communication between the agent and the AI.
    ///
    /// # Arguments
    ///
    /// * `tasks` - A mutable reference to tasks to be processed.
    ///
    /// # Returns
    ///
    /// (`Result<String>`): Result containing the fixed backend code.
    ///
    /// # Errors
    ///
    /// Returns an error if there's a failure in fixing the backend code bugs.
    ///
    /// # Business Logic
    ///
    /// - Constructs a request based on the buggy backend code and project description.
    /// - Logs the request as a user `Communication`.
    /// - Sends the request to the Gemini or OpenAI API to generate content for fixing bugs.
    /// - Logs the response or any errors as assistant `Communication`s.
    /// - Writes the fixed backend code to the appropriate file.
    /// - Updates tasks and agent status accordingly.
    pub async fn fix_code_bugs(&mut self, tasks: &mut Task) -> Result<String> {
        #[cfg(feature = "mem")]
        {
            self.agent.memory = self.get_ltm().await?;
        }

        let buggy_code = tasks.backend_code.clone().unwrap_or_default();
        let bugs = self.bugs.clone().unwrap_or_default();
        let request =
            format!("{FIX_CODE_PROMPT}\n\nBuggy Code: {buggy_code}\nBugs: {bugs}\n\nFix all bugs.");

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("user"),
            content: Cow::Owned(request.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("user"),
                    content: Cow::Owned(request.clone()),
                })
                .await;
        }

        #[allow(unused)]
        let mut response_text = String::new();

        #[cfg(any(feature = "oai", feature = "gem", feature = "cld", feature = "xai"))]
        {
            response_text = self.generate(&request).await?;
        }

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("assistant"),
            content: Cow::Owned(response_text.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("assistant"),
                    content: Cow::Owned(response_text.clone()),
                })
                .await;
        }

        let cleaned_code = strip_code_blocks(&response_text);

        let workspace = &self.workspace;
        let backend_path = match self.language {
            "rust" => format!("{workspace}/src/main.rs"),
            "python" => format!("{workspace}/main.py"),
            "javascript" => format!("{workspace}/src/index.js"),
            _ => return Err(anyhow!("Unsupported language")),
        };

        debug!(
            "[*] {:?}: Writing to {}",
            self.agent.position(),
            backend_path
        );

        fs::write(&backend_path, &cleaned_code).await?;

        tasks.backend_code = Some(cleaned_code.clone().into());

        self.agent.update(Status::Completed);
        debug!("[*] {:?}: {:?}", self.agent.position(), self.agent);

        Ok(cleaned_code)
    }

    /// Asynchronously retrieves routes JSON from the backend code,
    /// while logging communication between the agent and the AI.
    ///
    /// # Returns
    ///
    /// (`Result<String>`): Result containing the routes JSON.
    ///
    /// # Errors
    ///
    /// Returns an error if there's a failure in retrieving routes JSON.
    ///
    /// # Business Logic
    ///
    /// - Reads the backend code from the appropriate file.
    /// - Constructs a request with the backend code.
    /// - Logs the user's request as a `Communication`.
    /// - Sends the request to the Gemini or OpenAI API to generate content for routes JSON.
    /// - Logs the AI's response as a `Communication`.
    /// - Updates agent status accordingly.
    pub async fn get_routes_json(&mut self) -> Result<String> {
        #[cfg(feature = "mem")]
        {
            self.agent.memory = self.get_ltm().await?;
        }

        let path = self.workspace.clone();
        let full_path = match self.language {
            "rust" => format!("{path}/src/main.rs"),
            "python" => format!("{path}/main.py"),
            "javascript" => format!("{path}/src/index.js"),
            _ => return Err(anyhow!("Unsupported language")),
        };

        debug!(
            "[*] {:?}: Reading from {}",
            self.agent.position(),
            full_path
        );

        let backend_code = fs::read_to_string(full_path).await?;
        let request = format!(
            "{API_ENDPOINTS_PROMPT}\n\nHere is the backend code with all routes:{backend_code}"
        );

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("user"),
            content: Cow::Owned(request.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("user"),
                    content: Cow::Owned(request.clone()),
                })
                .await;
        }
        #[allow(unused)]
        let mut response_text = String::new();

        #[cfg(any(feature = "oai", feature = "gem", feature = "cld", feature = "xai"))]
        {
            response_text = self.generate(&request).await?;
        }

        self.agent.add_communication(Communication {
            role: Cow::Borrowed("assistant"),
            content: Cow::Owned(response_text.clone()),
        });

        #[cfg(feature = "mem")]
        {
            let _ = self
                .save_ltm(Communication {
                    role: Cow::Borrowed("assistant"),
                    content: Cow::Owned(response_text.clone()),
                })
                .await;
        }

        self.agent.update(Status::Completed);
        debug!("[*] {:?}: {:?}", self.agent.position(), self.agent);

        Ok(strip_code_blocks(&response_text))
    }

    pub fn think(&self) -> String {
        let objective = self.agent.objective();
        format!("How to build and test backend for '{objective}'")
    }

    pub fn plan(&mut self, _context: String) -> Goal {
        let mut goals = vec![
            Goal {
                description: "Generate backend code".into(),
                priority: 1,
                completed: false,
            },
            Goal {
                description: "Fix code bugs if any".into(),
                priority: 2,
                completed: false,
            },
            Goal {
                description: "Run unit tests and backend server".into(),
                priority: 3,
                completed: false,
            },
        ];

        goals.sort_by_key(|g| g.priority);

        if let Some(planner) = self.agent.planner_mut() {
            if planner.current_plan.is_empty() {
                for g in goals.into_iter().rev() {
                    planner.current_plan.push(g);
                }
            }

            if let Some(next_goal) = planner.current_plan.iter().rev().find(|g| !g.completed) {
                return next_goal.clone();
            }
        }

        Goal {
            description: "Default backend task".into(),
            priority: 1,
            completed: false,
        }
    }

    pub async fn act(
        &mut self,
        goal: Goal,
        tasks: &mut Task,
        execute: bool,
        max_tries: u64,
    ) -> Result<()> {
        info!(
            "{}",
            format!(
                "[*] {:?}: Executing goal: {}",
                self.agent.position(),
                goal.description
            )
            .cyan()
            .bold()
        );

        match goal.description.as_str() {
            "Generate backend code" => {
                self.generate_or_improve_code(tasks).await?;
                self.agent.update(Status::Active);
            }
            "Fix code bugs if any" => {
                if self.nb_bugs > 0 {
                    self.fix_code_bugs(tasks).await?;
                } else {
                    self.improve_backend_code(tasks).await?;
                }
                self.agent.update(Status::InUnitTesting);
            }
            "Run unit tests and backend server" => {
                self.unit_test_and_run_backend(tasks, execute, max_tries)
                    .await?;
                self.agent.update(Status::Completed);
            }
            _ => {
                warn!(
                    "{}",
                    format!(
                        "[*] {:?}: Unknown goal: {}",
                        self.agent.position(),
                        goal.description
                    )
                    .yellow()
                );
            }
        }

        Ok(())
    }

    pub fn reflect(&mut self) {
        let entry = format!(
            "Reflection on backend task for '{}'",
            self.agent.objective()
        );

        self.agent.memory_mut().push(Communication {
            role: Cow::Borrowed("assistant"),
            content: entry.clone().into(),
        });

        self.agent
            .context_mut()
            .recent_messages
            .push(Communication {
                role: Cow::Borrowed("assistant"),
                content: entry.into(),
            });

        if let Some(reflection) = self.agent.reflection() {
            let feedback = (reflection.evaluation_fn)(&self.agent);
            info!(
                "{}",
                format!(
                    "[*] {:?}: Self Reflection: {}",
                    self.agent.position(),
                    feedback
                )
                .blue()
            );
        }
    }

    pub fn has_completed_objective(&self) -> bool {
        if let Some(planner) = self.planner() {
            planner.current_plan.iter().all(|g| g.completed)
        } else {
            false
        }
    }

    pub fn mark_goal_complete(&mut self, goal: Goal) {
        if let Some(planner) = self.planner_mut() {
            for g in &mut planner.current_plan {
                if g.description == goal.description {
                    g.completed = true;
                }
            }
        }
    }

    fn display_task_info(&self, tasks: &Task) {
        for task in tasks.clone().description.clone().split("- ") {
            if !task.trim().is_empty() {
                info!("{} {}", "".bright_white().bold(), task.trim().cyan());
            }
        }
    }

    async fn open_docs_in_browser(&self) {
        let _ = open_browser_with_options(
            Browser::Default,
            "http://127.0.0.1:8000/docs",
            BrowserOptions::new().with_suppress_output(false),
        );
    }

    async fn generate_or_improve_code(&mut self, tasks: &mut Task) -> Result<()> {
        if self.nb_bugs == 0 {
            self.generate_backend_code(tasks).await?;
        } else {
            self.improve_backend_code(tasks).await?;
        }
        Ok(())
    }

    async fn unit_test_and_run_backend(
        &mut self,
        tasks: &mut Task,
        execute: bool,
        max_tries: u64,
    ) -> Result<()> {
        info!(
            "{}",
            format!(
                "[*] {:?}: Backend Code Unit Testing...",
                self.agent.position()
            )
            .bright_white()
            .bold()
        );

        if !execute {
            warn!(
                "{}",
                format!(
                    "[*] {:?}: Code not safe to proceed, skipping execution...",
                    self.agent.position()
                )
                .bright_yellow()
                .bold()
            );
            return Ok(());
        }

        let path = &self.workspace.to_string();

        let result = self.build_and_run_backend(path).await?;

        if let Some(mut child) = result {
            let mut stderr_output = String::new();
            if let Some(mut stderr) = child.stderr.take() {
                stderr.read_to_string(&mut stderr_output).await?;
            }

            if !stderr_output.trim().is_empty() {
                self.nb_bugs += 1;
                self.bugs = Some(stderr_output.into());

                if self.nb_bugs > max_tries {
                    error!(
                        "{}",
                        format!(
                            "[*] {:?}: Too many bugs detected. Please debug manually.",
                            self.agent.position()
                        )
                        .bright_red()
                        .bold()
                    );
                    return Ok(());
                }

                self.agent.update(Status::Active);
                return Ok(());
            } else {
                self.nb_bugs = 0;
                info!(
                    "{}",
                    format!(
                        "[*] {:?}: Backend server build successful...",
                        self.agent.position()
                    )
                    .bright_white()
                    .bold()
                );
            }

            let endpoints = self.get_routes_json().await?;

            let api_endpoints: Vec<Route> =
                serde_json::from_str(&endpoints).expect("Failed to decode API Endpoints");

            let filtered_endpoints: Vec<Route> = api_endpoints
                .iter()
                .filter(|&route| route.method == "get" && route.dynamic == "false")
                .cloned()
                .collect();

            tasks.api_schema = Some(filtered_endpoints.clone());

            info!(
                "{}",
                format!(
                    "[*] {:?}: Starting web server to test endpoints...",
                    self.agent.position()
                )
                .bright_white()
                .bold()
            );

            for endpoint in filtered_endpoints {
                info!(
                    "{}",
                    format!(
                        "[*] {:?}: Testing endpoint: {}",
                        self.agent.position(),
                        endpoint.path
                    )
                    .bright_white()
                    .bold()
                );

                let url = format!("http://127.0.0.1:8080{}", endpoint.path);
                let status_code = self.req_client.get(url).send().await?.status();

                if status_code != 200 {
                    info!(
                        "{}",
                        format!(
                            "[*] {:?}: Endpoint failed: {}. Needs further investigation.",
                            self.agent.position(),
                            endpoint.path
                        )
                        .bright_white()
                        .bold()
                    );
                }
            }

            let _ = child.kill().await;

            let backend_path = format!("{path}/api.json");
            fs::write(&backend_path, endpoints).await?;

            info!(
                "{}",
                format!(
                    "[*] {:?}: Backend testing complete. Results saved to api.json",
                    self.agent.position()
                )
                .bright_white()
                .bold()
            );
        } else {
            error!(
                "{}",
                format!(
                    "[*] {:?}: Failed to build or run backend project.",
                    self.agent.position()
                )
                .bright_red()
                .bold()
            );
        }

        Ok(())
    }

    async fn build_and_run_backend(&self, path: &str) -> Result<Option<Child>> {
        match self.language {
            "rust" => self.build_and_run_rust_backend(path).await,
            "python" => self.build_and_run_python_backend(path).await,
            "javascript" => self.build_and_run_js_backend(path).await,
            _ => Ok(None),
        }
    }

    async fn build_and_run_rust_backend(&self, path: &str) -> Result<Option<Child>> {
        let build_output = Command::new("cargo")
            .arg("build")
            .arg("--release")
            .arg("--verbose")
            .current_dir(path)
            .output()
            .await
            .expect("Failed to build backend");

        if build_output.status.success() {
            let child = Command::new("timeout")
                .arg("10s")
                .arg("cargo")
                .arg("run")
                .arg("--release")
                .arg("--verbose")
                .current_dir(path)
                .stdout(Stdio::piped())
                .stderr(Stdio::piped())
                .spawn()
                .expect("Failed to run backend");
            Ok(Some(child))
        } else {
            Ok(None)
        }
    }

    async fn build_and_run_python_backend(&self, path: &str) -> Result<Option<Child>> {
        let venv_path = format!("{path}/.venv");
        let pip_path = format!("{venv_path}/bin/pip");
        let venv_exists = Path::new(&venv_path).exists();

        if !venv_exists {
            let create_venv = Command::new("python3")
                .arg("-m")
                .arg("venv")
                .arg(&venv_path)
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status();

            if let Ok(status) = create_venv.await {
                if status.success() {
                    let main_py_path = format!("{path}/main.py");
                    let main_py_content = fs::read_to_string(&main_py_path)
                        .await
                        .expect("Failed to read main.py");

                    let mut packages = vec![];

                    for line in main_py_content.lines() {
                        if line.starts_with("from ") || line.starts_with("import ") {
                            let parts: Vec<&str> = line.split_whitespace().collect();

                            if let Some(pkg) = parts.get(1) {
                                let root_pkg = pkg.split('.').next().unwrap_or(pkg);
                                if !packages.contains(&root_pkg) {
                                    packages.push(root_pkg);
                                }
                            }
                        }
                    }
                    if !packages.is_empty() {
                        if !packages.contains(&"uvicorn") {
                            packages.push("uvicorn");
                        }
                        if !packages.contains(&"httpx") {
                            packages.push("httpx");
                        }
                        for pkg in &packages {
                            let install_status = Command::new(&pip_path)
                                .arg("install")
                                .arg(pkg)
                                .stdout(Stdio::null())
                                .stderr(Stdio::null())
                                .status();

                            match install_status.await {
                                Ok(status) if status.success() => {
                                    info!(
                                        "{}",
                                        format!(
                                            "[*] {:?}: Successfully installed Python package '{}'",
                                            self.agent.position(),
                                            pkg
                                        )
                                        .bright_white()
                                        .bold()
                                    );
                                }
                                Err(e) => {
                                    error!(
                                        "{}",
                                        format!(
                                            "[*] {:?}: Failed to install Python package '{}': {}",
                                            self.agent.position(),
                                            pkg,
                                            e
                                        )
                                        .bright_red()
                                        .bold()
                                    );
                                }
                                _ => {
                                    error!(
                                        "{}",
                                        format!(
                                            "[*] {:?}: Installation of package '{}' exited with an error",
                                            self.agent.position(),
                                            pkg
                                        )
                                        .bright_red()
                                        .bold()
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        let run_output = Command::new("sh")
            .arg("-c")
            .arg(format!(
                "timeout {} '.venv/bin/python' -m uvicorn main:app --host 0.0.0.0 --port 8000",
                10
            ))
            .current_dir(path)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to run the backend application");

        Ok(Some(run_output))
    }

    async fn build_and_run_js_backend(&self, path: &str) -> Result<Option<Child>> {
        let child = Command::new("timeout")
            .arg("10s")
            .arg("node")
            .arg("app.js")
            .current_dir(path)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .expect("Failed to run js backend");
        Ok(Some(child))
    }
    /// Updates the bugs found in the codebase.
    ///
    /// # Arguments
    ///
    /// * `bugs` - Optional description of bugs found in the codebase.
    ///
    /// # Business Logic
    ///
    /// - Updates the bugs field with the provided description.
    ///
    pub fn update_bugs(&mut self, bugs: Option<Cow<'static, str>>) {
        self.bugs = bugs;
    }
}

/// Implementation of the trait `Executor` for `BackendGPT`.
/// Contains additional methods related to backend tasks.
///
/// This trait provides methods for:
///
/// - Retrieving the agent associated with `BackendGPT`.
/// - Executing tasks asynchronously.
///
/// # Business Logic
///
/// - Provides access to the agent associated with the `BackendGPT` instance.
/// - Executes tasks asynchronously based on the current status of the agent.
/// - Handles task execution including code generation, bug fixing, and testing.
/// - Manages retries and error handling during task execution.
#[async_trait]
impl Executor for BackendGPT {
    /// Asynchronously executes tasks associated with BackendGPT.
    ///
    /// # Arguments
    ///
    /// * `tasks` - A mutable reference to tasks to be executed.
    /// * `execute` - A boolean indicating whether to execute the tasks.
    /// * `browse` - Whether to open the API docs in a browser.
    /// * `max_tries` - Maximum number of attempts to execute tasks.
    ///
    /// # Returns
    ///
    /// (`Result<()>`): Result indicating success or failure of task execution.
    ///
    /// # Errors
    ///
    /// Returns an error if there's a failure in executing tasks.
    ///
    /// # Business Logic
    ///
    /// - Executes tasks asynchronously based on the current status of the agent.
    /// - Handles task execution including code generation, bug fixing, and testing.
    /// - Manages retries and error handling during task execution.
    ///
    async fn execute<'a>(
        &'a mut self,
        tasks: &'a mut Task,
        execute: bool,
        browse: bool,
        max_tries: u64,
    ) -> Result<()> {
        self.agent.update(Status::Idle);
        info!(
            "{}",
            format!("[*] {:?}: Executing task:", self.agent.position())
                .bright_white()
                .bold()
        );

        self.display_task_info(tasks);

        if browse {
            #[cfg(feature = "cli")]
            let pb = spinner("Opening documentation in browser...");
            self.open_docs_in_browser().await;
            #[cfg(feature = "cli")]
            pb.finish_with_message("Documentation opened.");
        }

        while self.agent.status() != &Status::Completed {
            #[cfg(feature = "cli")]
            let pb = spinner("Thinking...");
            let context = self.think();
            #[cfg(feature = "cli")]
            pb.finish_with_message("Thinking complete!");

            #[cfg(feature = "cli")]
            let pb = spinner("Planning...");
            let goal = self.plan(context);
            #[cfg(feature = "cli")]
            pb.finish_with_message("Planning complete!");

            #[cfg(feature = "cli")]
            let pb = spinner("Acting on goal...");
            self.act(goal.clone(), tasks, execute, max_tries).await?;
            #[cfg(feature = "cli")]
            pb.finish_with_message("Action complete!");

            #[cfg(feature = "cli")]
            let pb = spinner("Marking goal complete...");
            self.mark_goal_complete(goal);
            #[cfg(feature = "cli")]
            pb.finish_with_message("Goal marked complete!");

            #[cfg(feature = "cli")]
            let pb = spinner("Reflecting...");
            self.reflect();
            #[cfg(feature = "cli")]
            pb.finish_with_message("Reflection complete!");

            if self.has_completed_objective() {
                info!(
                    "{}",
                    format!("[*] {:?}: Objective complete!", self.agent.position())
                        .green()
                        .bold()
                );
                self.agent.update(Status::Completed);
                break;
            }
        }

        self.agent.update(Status::Idle);
        Ok(())
    }
}