Skip to content

Commit

Permalink
Better Response time, Intervals fixed, Better Replies, Better BAIChat…
Browse files Browse the repository at this point in the history
… API
  • Loading branch information
Day-OS committed Jul 9, 2023
1 parent bb6e057 commit ecc7c88
Show file tree
Hide file tree
Showing 9 changed files with 318 additions and 204 deletions.
16 changes: 16 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "lldb",
"request": "launch",
"name": "Debug",
"program": "${workspaceFolder}/<executable file>",
"args": [],
"cwd": "${workspaceFolder}"
}
]
}
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,4 @@ simplelog = "0.12.1"
stop-words = { version="0.7.2", features = ["nltk", "iso"] }
rand = "0.8.5"
async-recursion = "1.0.4"
json-gettext = "4.0.5"
10 changes: 7 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
- [ ] APAGAR O QUE JÁ FOI LIDO
- [ ] INCLUDE DB
- [ ] REORGANIZE
- [ ] DO SO THE BOT REPLIES WHEN SOMEONE IS REFERENCING HIM.
- [ ] MARK AS ALREADY READ
- [x] TYPING STATE
- [X] DO SO THE BOT REPLIES WHEN SOMEONE IS REFERENCING HIM.
- [ ] ALTERNABLE STATES (COUNTDOWN)
-MAKE THE BOT ASNWER THE RIGHT PERSON

ERROR BAICHAT:104:60 thread 'tokio-runtime-worker' panicked at 'called `Result::unwrap()` on an `Err` value: Error("expected value", line: 1, column: 1)', src/baichat_rs.rs:104:60
30 changes: 18 additions & 12 deletions src/ai.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{baichat_rs::{self, ThebAI, Delta}, ai};

use serde::{Serialize, Deserialize};
use std::env;
use lazy_static;

#[derive(Debug)]
pub enum Error{
Expand Down Expand Up @@ -33,16 +34,21 @@ pub async fn reply(mut logs: String, memories: Option<String>) -> Result<ai::Res
logs
);

let mut ai: baichat_rs::ThebAI = get_ai();
let answer: Vec<Delta> = match ai.ask(&prompt, Some(env::var("PARENT_MESSAGE_ID_GPT").unwrap())).await {
Ok(message) => message,
Err(_) => {return Err(Error::CouldntGenerateResponseFromAI)}
};
let answer: String = answer[answer.len() - 1].text.clone();
println!("PROMPT: {}", answer);
let inputmsg: ai::ResponseMessage = match serde_json::from_str(&answer) {
Ok(memory)=>{memory}
Err(_)=>{return Err(Error::CouldntConvertToJSON)}
};
Ok(inputmsg)
let mut baichat: baichat_rs::ThebAI = get_ai();

for i in 0..3 {
log::info!("GENERATING MESSAGE - try #{}", i);
println!("GENERATING MESSAGE - try #{}", i);
let answer = match baichat.ask_single(&prompt, Some(env::var("PARENT_MESSAGE_ID_GPT").unwrap())).await {
Ok(message) => message,
Err(_) => continue
};
//let answer: String = baichat_rs::delta_to_string(answer).await;
let inputmsg: ai::ResponseMessage = match serde_json::from_str(&answer.text) {
Ok(memory)=>{memory}
Err(_)=> continue
};
return Ok(inputmsg)
}
return Err(Error::CouldntGenerateResponseFromAI)
}
107 changes: 79 additions & 28 deletions src/baichat_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,17 @@ use ratmom::{prelude::*, Request, config::SslOption};
use serde::{Serialize, Deserialize};
use serde_json::json;

#[derive(Serialize, Deserialize, Debug)]
pub struct Input {
pub prompt: String,
pub options: Options,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Options {
#[serde(rename(serialize = "parentMessageId", deserialize = "parentMessageId"))]
pub parent_message_id: String,
}

#[derive(Serialize, Deserialize, Debug)]
pub struct Delta {
pub role: String,
Expand Down Expand Up @@ -41,7 +52,6 @@ pub struct DeltaChoice {
pub struct ThebAI {
pub parent_message_id: Option<String>,
}

impl ThebAI {
pub fn new(parent_message_id: Option<&str>) -> ThebAI {
if let Some(parent_message_id) = parent_message_id {
Expand All @@ -55,37 +65,69 @@ impl ThebAI {
}
}

pub async fn ask(&mut self, prompt: &str, parent_message_id: Option<String>) -> Result<Vec<Delta>, Box<dyn std::error::Error>> {

let mut body = String::new();
body.push_str(r#"{
"prompt": "#);
body.push_str(&json!(prompt).to_string());
if let Some(parent_message_id) = parent_message_id {
body.push_str(r#",
"options": {
"parentMessageId": ""#);
body.push_str(parent_message_id.as_str());
body.push_str(r#""
}
}"#);
pub async fn ask_single(&mut self, prompt: &str, parent_message_id: Option<String>) -> Result<Delta, Box<dyn std::error::Error>> {
let parent_message_id: String = if let Some(parent_message_id) = parent_message_id {
parent_message_id
} else {
body.push_str(r#"",
"options": {
"parentMessageId": ""#);
body.push_str(self.parent_message_id.as_ref().unwrap().as_str());
body.push_str(r#""
}
}"#);
self.parent_message_id.clone().unwrap()
};
let body: String = serde_json::to_string(&Input{ prompt:json!(prompt).to_string(), options: Options { parent_message_id: parent_message_id }}).unwrap();


//println!("{}", body);
let mut request = Request::builder()
.method("POST")
.uri("https://chatbot.theb.ai/api/chat-process")
.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Content-Type", "application/json")
.header("Referer", "https://chatbot.theb.ai")
.header("Origin", "https://chatbot.theb.ai")
.ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS | SslOption::DANGER_ACCEPT_INVALID_HOSTS | SslOption::DANGER_ACCEPT_REVOKED_CERTS)
.body(body)?
.send()?;

let result = request.text()?;

println!("BAICHAT RESULT: {}", result);
//println!("{:?}", result.lines());
let mut target_line: &str = "".into();
for line in result.lines() {
if line == "" {
continue;
}
target_line = line;
}
match serde_json::from_str(target_line) {
Ok (delta)=> {
return Ok(delta)
}
Err(err)=>{
println!("BAICHAT ERRROR: {} \n {}", err, result);
return Err(err.into())
}
}
//println!("{:?}", deltas);

;
}

pub async fn ask(&mut self, prompt: &str, parent_message_id: Option<String>) -> Result<Vec<Delta>, Box<dyn std::error::Error>> {
let parent_message_id: String = if let Some(parent_message_id) = parent_message_id {
parent_message_id
} else {
self.parent_message_id.clone().unwrap()
};
let body: String = serde_json::to_string(&Input{ prompt:json!(prompt).to_string(), options: Options { parent_message_id: parent_message_id }}).unwrap();


//println!("{}", body);
let mut request = Request::builder()
.method("POST")
.uri("https://chatbot.theb.ai/api/chat-process")
.header("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/112.0")
.header("Accept-Language", "en-US,en;q=0.5")
.header("Content-Type", "application/json")
//.header("Host", "chatbot.theb.ai")
.header("Referer", "https://chatbot.theb.ai")
.header("Origin", "https://chatbot.theb.ai")
.ssl_options(SslOption::DANGER_ACCEPT_INVALID_CERTS | SslOption::DANGER_ACCEPT_INVALID_HOSTS | SslOption::DANGER_ACCEPT_REVOKED_CERTS)
Expand All @@ -95,22 +137,31 @@ impl ThebAI {
let result = request.text()?;

let mut deltas: Vec<Delta> = Vec::new();
println!("BAICHAT RESULT: {}", result);
//println!("{:?}", result.lines());
for line in result.lines() {
if line == "" {
continue;
}

let delta: Delta = serde_json::from_str(line).unwrap();
deltas.push(delta);
match serde_json::from_str(line) {
Ok (delta)=> {
deltas.push(delta)
}
Err(err)=>{println!("BAICHAT ERRROR: {} | {} ", err, line)}
}
}
match deltas.last() {
Some(delta)=>{self.parent_message_id = Some(delta.id.clone())}
None => {return Err("Error::WrongFormat(result)".into())}
}

self.parent_message_id = Some(deltas.last().unwrap().id.clone());

//println!("{:?}", deltas);

return Ok(deltas);
}
}

pub async fn deltas_to_string(delta : Vec<Delta>) -> String{
delta[delta.len() - 1].text.clone()
}

Loading

0 comments on commit ecc7c88

Please sign in to comment.