Skip to content

Commit

Permalink
add minor changes
Browse files Browse the repository at this point in the history
  • Loading branch information
maltsev-dev committed Dec 27, 2024
1 parent ff2d800 commit 439bc08
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 69 deletions.
54 changes: 45 additions & 9 deletions src/helpers/general.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,35 @@ use crate::helpers::command_lines::PrintCommand;
use crate::models::general::llm::Message;
use reqwest::Client;
use serde::de::DeserializeOwned;
use std::fs;
use std::path::PathBuf;
use std::{env, fs};

pub const WEB_SERVER_PROJECT_PATH: &str = r#"C:\Users\Anatolii Maltsev\Documents\Coding\Rust\Projects\RustAgent\auto_gpt_agent"#;
const EXEC_MAIN_PATH: &str = r#"C:\Users\Anatolii Maltsev\Documents\Coding\Rust\Projects\RustAgent\auto_gpt_agent\src\main2.rs"#;
const API_SCHEMA_PATH: &str = r#"C:\Users\Anatolii Maltsev\Documents\Coding\Rust\Projects\RustAgent\auto_gpt_agent\source\schemas\api_schema.json"#;
const CODE_TEMPLATE_PATH: &str = r#"C:\Users\Anatolii Maltsev\Documents\Coding\Rust\Projects\RustAgent\auto_gpt_agent\source\web_server_code_template.rs"#;
fn get_project_root() -> PathBuf {
env::current_dir().expect("Failed to get current directory")
}
const EXEC_MAIN_PATH: &str = r#"src\main2.rs"#;
const API_SCHEMA_PATH: &str = r#"source\schemas\api_schema.json"#;
const CODE_TEMPLATE_PATH: &str = r#"source\web_server_code_template.rs"#;

pub fn get_web_server_project_path() -> String {
// let project_root = get_project_root();
get_project_root().to_str().unwrap().to_string()
}

pub fn get_exec_main_path() -> String {
let project_root = get_project_root();
project_root.join(EXEC_MAIN_PATH).to_str().unwrap().to_string()
}

pub fn get_api_schema_path() -> String {
let project_root = get_project_root();
project_root.join(API_SCHEMA_PATH).to_str().unwrap().to_string()
}

pub fn get_code_template_path() -> String {
let project_root = get_project_root();
project_root.join(CODE_TEMPLATE_PATH).to_str().unwrap().to_string()
}

/// Extends an AI function by formatting the input and creating a system message.
/// This function prepares a message in the format expected by GPT models.
Expand Down Expand Up @@ -87,7 +110,7 @@ pub async fn check_status_code(client: &Client, url: &str) -> Result<u16, reqwes
/// # Returns
/// The contents of the code template as a `String`.
pub fn read_code_template_contents() -> String {
let path: String = String::from(CODE_TEMPLATE_PATH);
let path: String = String::from(get_code_template_path());
fs::read_to_string(path).expect("Failed to read code template")
}

Expand All @@ -96,7 +119,7 @@ pub fn read_code_template_contents() -> String {
/// # Returns
/// The contents of the `main2.rs` file as a `String`.
pub fn read_exec_main_contents() -> String {
let path: String = String::from(EXEC_MAIN_PATH);
let path: String = String::from(get_exec_main_path());
fs::read_to_string(path).expect("Failed to read code template")
}

Expand All @@ -105,7 +128,7 @@ pub fn read_exec_main_contents() -> String {
/// # Arguments
/// - `contents`: The code to write into the file.
pub fn save_backend_code(contents: &String) {
let path: String = String::from(EXEC_MAIN_PATH);
let path: String = String::from(get_exec_main_path());
fs::write(path, contents).expect("Failed to write main2.rs file");
}

Expand All @@ -114,10 +137,23 @@ pub fn save_backend_code(contents: &String) {
/// # Arguments
/// - `api_endpoints`: The API endpoints to save as a JSON string.
pub fn save_api_endpoints(api_endpoints: &String) {
let path: String = String::from(API_SCHEMA_PATH);
let path: String = String::from(get_api_schema_path());
fs::write(path, api_endpoints).expect("Failed to write API Endpoints to file");
}

// #[cfg(test)]
// mod tests {
// use super::*;
// #[test]
// fn tests_paths() {
// println!("{:?}", get_api_schema_path());
// println!("{:?}", get_code_template_path());
// println!("{:?}", get_exec_main_path());
// println!("{:?}", get_web_server_project_path());
// }
// }


// #[cfg(test)]
// mod tests {
// use super::*;
Expand Down
8 changes: 8 additions & 0 deletions src/main2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::collections::HashMap;
use std::fs;
use std::io::Write;
use ::std::sync::Mutex;
use reqwest::Error;

#[derive(Serialize, Deserialize, Debug, Clone)]
struct News {
Expand Down Expand Up @@ -94,6 +95,13 @@ async fn delete_news(app_state: web::Data<AppState>, id: web::Path<u64>) -> impl
HttpResponse::Ok().finish()
}

async fn fetch_external_news() -> Result<Vec<News>, Error> {
let url = "https://api.gdeltproject.org/api/v2/summary/summary?d=day";
let response = reqwest::get(url).await?;
let news: Vec<News> = response.json().await?;
Ok(news)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
let db: Database = Database::load_from_file().unwrap_or_else(|_| Database::new());
Expand Down
3 changes: 0 additions & 3 deletions src/models/agents/agent_architecture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,6 @@ impl SpecialFunctions for AgentSolutionArchitect {
}

AgentState::UnitTesting => {
/// Filters and verifies external URLs for the project
///
/// This section ensures only valid URLs with a status code of 200 are retained.
let mut excluded_external_urls: Vec<String> = vec![];

let client: Client = Client::builder()
Expand Down
96 changes: 40 additions & 56 deletions src/models/agents/agent_backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,11 @@ use crate::ai_functions::ai_func_backend::{
print_backend_webserver_code, print_fixed_code, print_improved_webserver_code,
print_rest_api_endpoints,
};
use crate::helpers::general::{
check_status_code, read_code_template_contents, read_exec_main_contents, save_api_endpoints,
save_backend_code,
};
use crate::helpers::general::{check_status_code, get_web_server_project_path, read_code_template_contents, read_exec_main_contents, save_api_endpoints, save_backend_code};
use std::path::Path;

use crate::helpers::command_lines::{confirm_safe_code, PrintCommand};
use crate::helpers::general::{ai_task_request, WEB_SERVER_PROJECT_PATH};
use crate::helpers::general::ai_task_request;
use crate::models::agent_basic::basic_agent::{AgentState, BasicAgent};
use crate::models::agents::agent_traits::{FactSheet, RouteObject, SpecialFunctions};

Expand Down Expand Up @@ -54,7 +51,7 @@ impl AgentBackendDeveloper {
/// - `fact_sheet`: A mutable reference to the fact sheet containing project information
async fn call_initial_backend_code(&mut self, fact_sheet: &mut FactSheet) {
let code_template_str: String = read_code_template_contents();
// Concatenate Instruction

let msg_context: String = format!(
"CODE TEMPLATE: {} \n PROJECT_DESCRIPTION: {} \n",
code_template_str, fact_sheet.project_description
Expand Down Expand Up @@ -172,7 +169,6 @@ impl SpecialFunctions for AgentBackendDeveloper {
}

AgentState::UnitTesting => {
// API SAFETY GUARD
PrintCommand::UnitTest.print_agent_message(
&self.attributes.position.as_str(),
"Backend Code Unit Testing: Ensuring Safe Code",
Expand All @@ -184,21 +180,19 @@ impl SpecialFunctions for AgentBackendDeveloper {
panic!("Better go work on some AI alignment instead...");
}

// Build and testing code
PrintCommand::UnitTest.print_agent_message(
&self.attributes.position.as_str(),
"Backend Code Unit Testing: Building web server...",
);

let build_backend_server = Command::new("cargo")
.args(&["build", "--bin", "main2"])
.current_dir(WEB_SERVER_PROJECT_PATH)
.current_dir(get_web_server_project_path())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("Failed to build backend application");

// determine errors
if build_backend_server.status.success() {
self.bug_count = 0;
PrintCommand::UnitTest.print_agent_message(
Expand Down Expand Up @@ -246,28 +240,17 @@ impl SpecialFunctions for AgentBackendDeveloper {


let binary_name = "main2";
// Путь к собранному бинарнику
let binary_path = Path::new("target/debug").join(binary_name);
if binary_path.exists() {
println!("Running binary: {:?}", binary_path);
}

// Запуск бинарника
let mut run_backend_server: std::process::Child = Command::new(binary_path)
.stdout(Stdio::inherit()) // Наследуем stdout для прямого вывода в консоль
.stderr(Stdio::inherit()) // Наследуем stderr для прямого вывода ошибок
.spawn() // Используем spawn, чтобы запустить в текущем процессе
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.spawn()
.expect("Failed to run backend application");


// let mut run_backend_server: std::process::Child = Command::new("cargo")
// .arg("run")
// .current_dir(WEB_SERVER_PROJECT_PATH)
// .stdout(Stdio::piped())
// .stderr(Stdio::piped())
// .spawn()
// .expect("Failed to run backend application");

PrintCommand::UnitTest.print_agent_message(
&self.attributes.position.as_str(),
"Backend Code Unit Testing: Launching test on server in 5 sec...",
Expand Down Expand Up @@ -335,6 +318,7 @@ impl SpecialFunctions for AgentBackendDeveloper {
}
}


// #[cfg(test)]
// mod tests {
// use super::*;
Expand Down Expand Up @@ -369,35 +353,35 @@ impl SpecialFunctions for AgentBackendDeveloper {
// }
// }


#[cfg(test)]
mod tests {
use super::*;

#[tokio::test]
async fn tests_backend_developer() {
let mut agent: AgentBackendDeveloper = AgentBackendDeveloper::new();

let fact_sheet_str: &str = r#"
{
"project_description": "build a website that fetches and tracks fitness progress with timezone information",
"project_scope": {
"is_crud_required": false,
"is_user_login_and_logout": false,
"is_external_urls_required": false
},
"external_urls": [],
"backend_code": null,
"api_endpoint_schema": null
}"#;

let mut factsheet: FactSheet = serde_json::from_str(fact_sheet_str).unwrap();

// agent.attributes.state = AgentState::Discovery;
agent.attributes.state = AgentState::UnitTesting;
agent
.execute(&mut factsheet)
.await
.expect("Failed to execute Backend Developer agent");
}
}
//
// #[cfg(test)]
// mod tests {
// use super::*;
//
// #[tokio::test]
// async fn tests_backend_developer() {
// let mut agent: AgentBackendDeveloper = AgentBackendDeveloper::new();
//
// let fact_sheet_str: &str = r#"
// {
// "project_description": "build a website that fetches and tracks fitness progress with timezone information",
// "project_scope": {
// "is_crud_required": false,
// "is_user_login_and_logout": false,
// "is_external_urls_required": false
// },
// "external_urls": [],
// "backend_code": null,
// "api_endpoint_schema": null
// }"#;
//
// let mut factsheet: FactSheet = serde_json::from_str(fact_sheet_str).unwrap();
//
// agent.attributes.state = AgentState::Discovery;
// // agent.attributes.state = AgentState::UnitTesting;
// agent
// .execute(&mut factsheet)
// .await
// .expect("Failed to execute Backend Developer agent");
// }
// }
2 changes: 1 addition & 1 deletion src/models/agents_manager/managing_agents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl ManagingAgent {

let agents: Vec<Box<dyn SpecialFunctions>> = vec![];

let mut fact_sheet: FactSheet = FactSheet {
let fact_sheet: FactSheet = FactSheet {
project_description,
project_scope: None,
external_urls: None,
Expand Down

0 comments on commit 439bc08

Please sign in to comment.