Skip to content

Commit

Permalink
Refactor code to load API keys from JSON config instead of env variables
Browse files Browse the repository at this point in the history
  • Loading branch information
oleander committed Feb 1, 2024
1 parent 5098f41 commit cea714e
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
7 changes: 2 additions & 5 deletions src/bin/websocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,11 @@ async fn main() {
tools.push(tool);
}

// read /data/options.json as json
let options = std::fs::read_to_string("/data/options.json").expect("Error reading options");
let options: serde_json::Value = serde_json::from_str(&options).expect("Error parsing options");
println!("Loaded options: {}", options);
println!("Loaded {} tools", tools.len());
println!("Supervisor token: {}", *shared::SUPERVISOR_TOKEN);
println!("Loaded options: {}", *shared::OPENAI_API_KEY);
println!("OpenAi API key: {}", *shared::OPENAI_API_KEY);
println!("Socket port: {}", *shared::SOCKET_PORT);
println!("Loaded {} tools", tools.len());

let instructions = std::fs::read_to_string("resources/instructions.txt").expect("Error reading instructions");
let env = Environment::new(tools, instructions);
Expand Down
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ pub mod openai;
pub mod socket;
pub mod files;
pub mod shared;

29 changes: 28 additions & 1 deletion src/shared.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,36 @@
use std::env::var;

#[derive(Debug, serde::Deserialize)]
struct Options {
pub openai_api_key: String
}

lazy_static::lazy_static! {
pub static ref SUPERVISOR_TOKEN: String = var("SUPERVISOR_TOKEN").expect("please set up the SUPERVISOR_TOKEN env variable before running this");
pub static ref OPENAI_API_KEY: String = var("OPTIONS_OPENAI_API_KEY").expect("please set up the OPENAI_API_KEY env variable before running this");
pub static ref SOCKET_PORT: String = var("SOCKET_PORT").expect("please set up the SOCKET_PORT env variable before running this");

pub static ref OPENAI_API_KEY: String = {
if let Ok(key) = var("OPENAI_API_KEY") {
return key
}

match std::fs::read_to_string("/data/options.json") {
Ok(content) => {
match serde_json::from_str::<Options>(&content) {
Ok(options) => {
std::env::set_var("OPENAI_API_KEY", &options.openai_api_key);
return options.openai_api_key;
},
Err(err) => {
panic!("Error parsing /data/options.json file: {}", err);
}
}
},
Err(err) => {
panic!("Error reading /data/options.json file: {}", err);
}
}
};
}

pub static MODEL: &str = "gpt-3.5-turbo-1106";
Expand Down

0 comments on commit cea714e

Please sign in to comment.