Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Remove unused colored dependency, variables, and unused drops #70

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/api/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ fn create_llm_model(agent: HashMap<String, Value>) -> Result<Box<dyn LLMModel>,
.find(|el| el.get_name().to_ascii_lowercase() == model_name.to_ascii_lowercase())
.ok_or(NoLLMError)?;

Ok(llm_provider.create(model_config.clone())?)
llm_provider.create(model_config.clone())
}

fn create_memory_model(agent: HashMap<String, Value>) -> Result<Box<dyn MemorySystem>, Box<dyn Error>> {
Expand All @@ -119,7 +119,7 @@ fn create_memory_model(agent: HashMap<String, Value>) -> Result<Box<dyn MemorySy
.find(|el| el.get_name().to_ascii_lowercase() == model_name.to_ascii_lowercase())
.ok_or(NoMemorySystemError)?;

Ok(memory_provider.create(model_config.clone())?)
memory_provider.create(model_config.clone())
}

pub fn create_agent(agent: AgentConfig) -> Result<AgentInfo, Box<dyn Error>> {
Expand All @@ -142,7 +142,7 @@ pub fn load_config(config: &str) -> Result<(String, SmartGPT), Box<dyn Error>> {
let mut exit = false;
for (name, _) in &config.plugins {
let plugin = plugins.iter().find(|el| el.name.to_ascii_lowercase() == name.to_ascii_lowercase());
if let None = plugin {
if plugin.is_none() {
println!("{}: No plugin named \"{}\".", "Error".red(), name);
exit = true;
}
Expand Down
6 changes: 3 additions & 3 deletions src/api/smartgpt.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use std::{sync::{Mutex, Arc}, collections::HashMap, error::Error, vec, fmt::Display};
use std::{sync::{Mutex, Arc}, error::Error, fmt::Display};

use serde::Serialize;
use serde_json::Value;

use crate::{CommandContext, PluginStore, Agents, AgentInfo, LLMProvider, LLMModel, LLM, ChatGPTProvider, ChatGPTConfig, memory_from_provider, LocalProvider, auto::{run_auto, Action, DisallowedAction, Update}, GoogleData};

use crate::{CommandContext, auto::{run_auto, Action, DisallowedAction, Update}};

#[derive(Debug, Clone)]
pub struct NoPluginError(pub String);
Expand Down
2 changes: 1 addition & 1 deletion src/auto/agents/worker/actor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ pub fn use_tool(
let agent = get_agent(context);
agent.llm.clear_history();

return Ok(out);
Ok(out)
}
23 changes: 11 additions & 12 deletions src/auto/agents/worker/adept.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::{error::Error, ops::Deref, fmt::Display};
use colored::Colorize;

use serde::{Serialize, Deserialize};

use crate::{CommandContext, AgentInfo, Message, auto::{try_parse_json, agents::{worker::{log_yaml, run_method_agent}, prompt::{CONCISE_PLAN, ConcisePlanInfo, PersonalityInfo, PERSONALITY, THOUGHTS, ThoughtInfo, NewThoughtInfo, NEW_THOUGHTS}}, run::Action, DisallowedAction, DynamicUpdate}, ScriptValue};
use crate::{CommandContext, AgentInfo, Message, auto::{try_parse_json, agents::{worker::{run_method_agent}, prompt::{CONCISE_PLAN, ConcisePlanInfo, PersonalityInfo, PERSONALITY, THOUGHTS, ThoughtInfo, NewThoughtInfo, NEW_THOUGHTS}}, run::Action, DisallowedAction, DynamicUpdate}, ScriptValue};

use super::Update;

Expand Down Expand Up @@ -74,7 +74,7 @@ pub fn get_response(

let mut data: Option<String> = None;

if assets.len() > 0 {
if !assets.is_empty() {
data = Some(
assets.iter()
.map(|el| format!("## Asset `${el}`:\n{}", context.assets[el]))
Expand All @@ -87,15 +87,15 @@ pub fn get_response(
Ok(out)
},
"brainstorm" => {
Ok(format!("Successfully brainstormed."))
Ok("Successfully brainstormed.".to_string())
}
"final_response" => {
let FinalResponseArgs { response } = thoughts.decision.args.parse()?;

Ok(response)
},
decision_type => {
return Err(Box::new(NoDecisionTypeError(decision_type.to_string())))
Err(Box::new(NoDecisionTypeError(decision_type.to_string())))
}
}
}
Expand Down Expand Up @@ -136,13 +136,13 @@ pub fn run_brain_agent(

listen_to_update(&Update::DynamicAgent(DynamicUpdate::Thoughts(thoughts.clone())))?;

drop(agent);
let _ = agent;
let mut response = get_response(
context,
&|ctx| &mut ctx.agents.static_agent,
&|ctx| &mut ctx.agents.planner,
&thoughts,
&personality,
personality,
allow_action,
listen_to_update
)?;
Expand All @@ -153,12 +153,11 @@ pub fn run_brain_agent(

loop {
let cloned_assets = context.assets.clone();
let asset_list = if cloned_assets.len() == 0 {
format!("No assets.")
let _asset_list = if cloned_assets.is_empty() {
"No assets.".to_string()
} else {
cloned_assets
.keys()
.map(|asset| asset.clone())
.keys().cloned()
.collect::<Vec<_>>()
.join(", ")
};
Expand All @@ -182,7 +181,7 @@ pub fn run_brain_agent(
&|ctx| &mut ctx.agents.static_agent,
&|ctx| &mut ctx.agents.planner,
&thoughts,
&personality,
personality,
allow_action,
listen_to_update
)?;
Expand Down
22 changes: 11 additions & 11 deletions src/auto/agents/worker/methodical.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use std::{error::Error, collections::{HashSet}};

use colored::Colorize;

use serde::{Serialize, Deserialize};

use crate::{CommandContext, AgentInfo, Message, auto::{run::Action, try_parse_json, agents::{worker::create_tool_list, prompt::{SUMMARIZE_MEMORIES, NoData, PERSONALITY, PersonalityInfo, CREATE_PLAN, CreatePlanInfo, NextStepInfo, NEXT_STEP, SAVE_ASSET, SaveAssetInfo}}, DisallowedAction, StaticUpdate, Update, NamedAsset}, Weights, Tool};

use super::{log_yaml, use_tool};
use super::{use_tool};

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct MethodicalThoughts {
Expand Down Expand Up @@ -102,7 +102,7 @@ pub fn run_method_agent(
let tools = create_tool_list(&tools);

let cloned_assets = context.assets.clone();
let assets_before: HashSet<&String> = cloned_assets.keys().collect();
let _assets_before: HashSet<&String> = cloned_assets.keys().collect();

get_agent(context).llm.clear_history();

Expand All @@ -122,7 +122,7 @@ pub fn run_method_agent(
}, 30
)?;

let observations = if observations.len() == 0 {
let observations = if observations.is_empty() {
"None found.".to_string()
} else {
observations.iter()
Expand All @@ -131,7 +131,7 @@ pub fn run_method_agent(
.join("\n")
};

let data = assets.unwrap_or(format!("No assets."));
let data = assets.unwrap_or("No assets.".to_string());

planner.llm.prompt.push(Message::User(
CREATE_PLAN.fill(CreatePlanInfo {
Expand All @@ -151,7 +151,7 @@ pub fn run_method_agent(
let prompt = planner.llm.prompt.clone();
let message_history = planner.llm.message_history.clone();

drop(planner);
let _ = planner;

let agent = get_agent(context);
agent.llm.prompt = prompt;
Expand All @@ -173,7 +173,7 @@ pub fn run_method_agent(
agent.llm.message_history.push(Message::Assistant(thoughts.raw));
let thoughts = thoughts.data;

drop(agent);
let _ = agent;

listen_to_update(&Update::StaticAgent(StaticUpdate::Thoughts(thoughts.clone())))?;
allow_action(&thoughts.action)?;
Expand Down Expand Up @@ -220,7 +220,7 @@ pub fn run_method_agent(
let asset_content = agent.llm.model.get_response_sync(&agent.llm.get_messages(), Some(800), Some(0.3))?;
agent.llm.message_history.pop();

drop(agent);
let _ = agent;

*context.assets
.entry(asset.name.clone())
Expand All @@ -235,8 +235,8 @@ pub fn run_method_agent(

add_memories(agent, listen_to_update)?;

let asset_str = if changed_assets.len() == 0 {
format!("No assets changed.")
let asset_str = if changed_assets.is_empty() {
"No assets changed.".to_string()
} else {
changed_assets .iter()
.map(|el| format!("## Asset `{}`\n{}", el.0, el.1))
Expand All @@ -247,5 +247,5 @@ pub fn run_method_agent(
let resp = format!("Assets:\n\n{}", asset_str);


return Ok(resp);
Ok(resp)
}
2 changes: 1 addition & 1 deletion src/auto/agents/worker/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{error::Error};
use crate::{SmartGPT, AgentInfo, auto::{run::Action, DisallowedAction}};
use crate::{SmartGPT, auto::{run::Action, DisallowedAction}};
use serde::Serialize;

mod adept;
Expand Down
12 changes: 5 additions & 7 deletions src/auto/agents/worker/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,23 @@ pub fn create_filtered_tool_list(header: &str, tools: &[&Tool], tool_type: ToolT

let Tool { name, purpose, args, .. } = tool;

let mut schema = format!("{{ ");
let mut schema = "{ ".to_string();
for arg in args {
let ToolArgument { name, example } = arg;
schema.push_str(&format!(r#""{name}": {example}, "#))
}
schema = schema.trim_end_matches(", ").to_string();

schema.push_str(&format!(" }}"));
schema.push_str(" }");

prompt.push('\n');
prompt.push_str(&format!("{name} {schema} - {purpose}"));
}

return prompt;
prompt
}

pub fn create_tool_list(tools: &[&Tool]) -> String {
vec![
create_filtered_tool_list("Resources", tools, ToolType::Resource),
create_filtered_tool_list("Actions", tools, ToolType::Action { needs_permission: false })
].join("\n\n")
[create_filtered_tool_list("Resources", tools, ToolType::Resource),
create_filtered_tool_list("Actions", tools, ToolType::Action { needs_permission: false })].join("\n\n")
}
13 changes: 7 additions & 6 deletions src/auto/classify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub struct Classification {
classification: String,
}

#[allow(dead_code)]
pub fn is_task(smartgpt: &mut SmartGPT, task: &str) -> Result<bool, Box<dyn Error>> {
let SmartGPT {
context, ..
Expand All @@ -23,23 +24,23 @@ pub fn is_task(smartgpt: &mut SmartGPT, task: &str) -> Result<bool, Box<dyn Erro

context.agents.fast.llm.clear_history();

context.agents.fast.llm.prompt.push(Message::Assistant(format!(r#"
context.agents.fast.llm.prompt.push(Message::Assistant(r#"
Given a message respond with one of the following.

"conversational": A conversational message
"task": A task or request
"#)));
"#.to_string()));


context.agents.fast.llm.message_history.push(Message::User(format!(r#"
context.agents.fast.llm.message_history.push(Message::User(r#"
Respond in this format:

```json
{{
{
"thoughts on how to classify it": "...",
"message classification": "..."
}}
```"#)));
}
```"#.to_string()));

context.agents.fast.llm.message_history.push(Message::User(format!(
"Request to Classify: {task}"
Expand Down
13 changes: 7 additions & 6 deletions src/auto/mod.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
use std::{fmt::Display, error::Error};

use serde::{ Serialize, de::DeserializeOwned};
use json5;


use colored::Colorize;
use serde_json::ser::PrettyFormatter;

use crate::{LLM, SmartGPT};

#[allow(hidden_glob_reexports)]
use self::{agents::{processing::find_text_between_braces, worker::run_worker}};

mod agents;
mod run;
mod responses;
mod classify;

pub use run::{Action};
pub use run::Action;
pub use agents::worker::*;

#[derive(Debug)]
Expand Down Expand Up @@ -43,15 +44,15 @@ pub fn run_auto(

drop(context);

Ok(run_worker(smartgpt, task.clone(), &smartgpt.personality.clone(), allow_action, listen_to_update)?)
run_worker(smartgpt, task, &smartgpt.personality.clone(), allow_action, listen_to_update)
}

#[derive(Debug, Clone)]
pub struct CannotParseError;

impl Display for CannotParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", "could not parse.")
write!(f, "could not parse.")
}
}

Expand Down Expand Up @@ -104,9 +105,9 @@ pub fn try_parse_base<T : DeserializeOwned>(llm: &LLM, tries: usize, max_tokens:
let response = llm.model.get_response_sync(&llm.get_messages(), max_tokens, temperature)?;
let processed_response = response.trim();
let processed_response = processed_response.strip_prefix("```")
.unwrap_or(&processed_response)
.unwrap_or(processed_response)
.to_string();
let processed_response = processed_response.strip_prefix(&format!("{lang}"))
let processed_response = processed_response.strip_prefix(&lang.to_string())
.unwrap_or(&response)
.to_string();
let processed_response = processed_response.strip_suffix("```")
Expand Down
5 changes: 3 additions & 2 deletions src/auto/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@ pub struct Response {
response: String
}

#[allow(dead_code)]
pub fn create_runner_prompt() -> String {
format!(
r#"Now, please write a response back to the user. Tell the user, in detail, everything you did, the outcome, and any permanent changes that were carried out."#)
r#"Now, please write a response back to the user. Tell the user, in detail, everything you did, the outcome, and any permanent changes that were carried out."#.to_string()
}

#[allow(dead_code)]
pub fn ask_for_responses(agent: &mut AgentInfo) -> Result<String, Box<dyn Error>> {
agent.llm.message_history.push(Message::User(create_runner_prompt()));

Expand Down
4 changes: 3 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,14 @@ mod auto;
mod log;

pub use plugin::*;
pub use plugins::*;
pub use tools::*;
pub use chunk::*;
pub use llms::*;
pub use api::*;
pub use runner::*;
pub use memory::*;
#[allow(ambiguous_glob_reexports)]
pub use plugins::*;
#[allow(ambiguous_glob_reexports)]
pub use auto::*;
pub use log::*;
2 changes: 1 addition & 1 deletion src/llms/chatgpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use async_openai::{Client, types::{CreateChatCompletionResponse, CreateChatCompl
use async_trait::async_trait;
use serde::{Serialize, Deserialize};
use serde_json::Value;
use tiktoken_rs::{async_openai::{get_chat_completion_max_tokens, num_tokens_from_messages}, model::get_context_size, cl100k_base, r50k_base};
use tiktoken_rs::{async_openai::{get_chat_completion_max_tokens, num_tokens_from_messages}, model::get_context_size, r50k_base};

use crate::{LLMProvider, Message, LLMModel};

Expand Down
Loading