forked from jelson.rodrigues/piperun-bot
feat: working AI integration
This commit is contained in:
131
Cargo.lock
generated
131
Cargo.lock
generated
@@ -17,6 +17,15 @@ version = "2.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
|
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "aho-corasick"
|
||||||
|
version = "1.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "android-tzdata"
|
name = "android-tzdata"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -616,6 +625,20 @@ dependencies = [
|
|||||||
"hashbrown",
|
"hashbrown",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ipaddress"
|
||||||
|
version = "0.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "957bb9f3645d6bb7f36df99d5105b4866aa79749819d7c176a170a27dc477cbf"
|
||||||
|
dependencies = [
|
||||||
|
"lazy_static",
|
||||||
|
"libc",
|
||||||
|
"num",
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
"regex",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ipnet"
|
name = "ipnet"
|
||||||
version = "2.11.0"
|
version = "2.11.0"
|
||||||
@@ -648,6 +671,12 @@ dependencies = [
|
|||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lazy_static"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "libc"
|
name = "libc"
|
||||||
version = "0.2.172"
|
version = "0.2.172"
|
||||||
@@ -727,12 +756,76 @@ dependencies = [
|
|||||||
"tempfile",
|
"tempfile",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num"
|
||||||
|
version = "0.4.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23"
|
||||||
|
dependencies = [
|
||||||
|
"num-bigint",
|
||||||
|
"num-complex",
|
||||||
|
"num-integer",
|
||||||
|
"num-iter",
|
||||||
|
"num-rational",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-bigint"
|
||||||
|
version = "0.4.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
|
||||||
|
dependencies = [
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-complex"
|
||||||
|
version = "0.4.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-conv"
|
name = "num-conv"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-integer"
|
||||||
|
version = "0.1.46"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-iter"
|
||||||
|
version = "0.1.45"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-rational"
|
||||||
|
version = "0.4.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
|
||||||
|
dependencies = [
|
||||||
|
"num-bigint",
|
||||||
|
"num-integer",
|
||||||
|
"num-traits",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.19"
|
version = "0.2.19"
|
||||||
@@ -826,6 +919,7 @@ dependencies = [
|
|||||||
"chrono",
|
"chrono",
|
||||||
"dotenv",
|
"dotenv",
|
||||||
"http",
|
"http",
|
||||||
|
"ipaddress",
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
]
|
]
|
||||||
@@ -892,10 +986,39 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
|
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "reqwest"
|
name = "regex"
|
||||||
version = "0.12.19"
|
version = "1.11.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "a2f8e5513d63f2e5b386eb5106dc67eaf3f84e95258e210489136b8b92ad6119"
|
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-automata",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-automata"
|
||||||
|
version = "0.4.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
|
||||||
|
dependencies = [
|
||||||
|
"aho-corasick",
|
||||||
|
"memchr",
|
||||||
|
"regex-syntax",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "reqwest"
|
||||||
|
version = "0.12.20"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64",
|
"base64",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -913,12 +1036,10 @@ dependencies = [
|
|||||||
"hyper-rustls",
|
"hyper-rustls",
|
||||||
"hyper-tls",
|
"hyper-tls",
|
||||||
"hyper-util",
|
"hyper-util",
|
||||||
"ipnet",
|
|
||||||
"js-sys",
|
"js-sys",
|
||||||
"log",
|
"log",
|
||||||
"mime",
|
"mime",
|
||||||
"native-tls",
|
"native-tls",
|
||||||
"once_cell",
|
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"rustls-pki-types",
|
"rustls-pki-types",
|
||||||
|
|||||||
@@ -7,5 +7,6 @@ edition = "2024"
|
|||||||
http = {version = "1.3.1"}
|
http = {version = "1.3.1"}
|
||||||
dotenv = {version = "0.15.0"}
|
dotenv = {version = "0.15.0"}
|
||||||
serde_json = "1.0.140"
|
serde_json = "1.0.140"
|
||||||
reqwest = { version = "0.12.19", features = ["json", "cookies", "blocking"] }
|
reqwest = { version = "0.12.20", features = ["json", "cookies", "blocking"] }
|
||||||
chrono = { version = "0.4.41" }
|
chrono = { version = "0.4.41" }
|
||||||
|
ipaddress = {version = "0.1.3"}
|
||||||
134
src/main.rs
134
src/main.rs
@@ -1,11 +1,12 @@
|
|||||||
use std::{any::Any, env, iter};
|
use std::{any::Any, env, fmt::format, iter, time::Duration};
|
||||||
|
|
||||||
// use http::{self, response};
|
// use http::{self, response};
|
||||||
|
|
||||||
use chrono::{self, Timelike};
|
use chrono::{self, Timelike};
|
||||||
use dotenv;
|
use dotenv;
|
||||||
use reqwest;
|
use reqwest;
|
||||||
use serde_json;
|
use serde_json::{self, json};
|
||||||
|
use ipaddress;
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
match dotenv::dotenv().ok() {
|
match dotenv::dotenv().ok() {
|
||||||
@@ -30,17 +31,31 @@ fn main() {
|
|||||||
env::var("PIPERUN_BOT_USERNAME").expect("PIPERUN_BOT_USERNAME has not been set!");
|
env::var("PIPERUN_BOT_USERNAME").expect("PIPERUN_BOT_USERNAME has not been set!");
|
||||||
let PIPERUN_BOT_PASSWORD =
|
let PIPERUN_BOT_PASSWORD =
|
||||||
env::var("PIPERUN_BOT_PASSWORD").expect("PIPERUN_BOT_PASSWORD has not been set!");
|
env::var("PIPERUN_BOT_PASSWORD").expect("PIPERUN_BOT_PASSWORD has not been set!");
|
||||||
|
let OLLAMA_AI_MODEL =
|
||||||
|
env::var("OLLAMA_AI_MODEL").expect("OLLAMA_AI_MODEL has not been set!");
|
||||||
|
|
||||||
|
|
||||||
// Print the configuration
|
// Print the configuration
|
||||||
println!("OLLAMA_URL: {}", OLLAMA_URL);
|
println!("OLLAMA_URL: {}", OLLAMA_URL);
|
||||||
println!("OLLAMA_PORT: {}", OLLAMA_PORT);
|
println!("OLLAMA_PORT: {}", OLLAMA_PORT);
|
||||||
|
println!("OLLAMA_AI_MODEL: {}", OLLAMA_AI_MODEL);
|
||||||
println!("PIPERUN_API_URL: {}", PIPERUN_API_URL);
|
println!("PIPERUN_API_URL: {}", PIPERUN_API_URL);
|
||||||
println!("PIPERUN_CLIENT_ID: {}", PIPERUN_CLIENT_ID);
|
println!("PIPERUN_CLIENT_ID: {}", PIPERUN_CLIENT_ID);
|
||||||
println!("PIPERUN_CLIENT_SECRET: {}", PIPERUN_CLIENT_SECRET);
|
println!("PIPERUN_CLIENT_SECRET: {}", PIPERUN_CLIENT_SECRET);
|
||||||
println!("PIPERUN_BOT_USERNAME: {}", PIPERUN_BOT_USERNAME);
|
println!("PIPERUN_BOT_USERNAME: {}", PIPERUN_BOT_USERNAME);
|
||||||
println!("PIPERUN_BOT_PASSWORD: {}", PIPERUN_BOT_PASSWORD);
|
println!("PIPERUN_BOT_PASSWORD: {}", PIPERUN_BOT_PASSWORD);
|
||||||
|
|
||||||
// Authenticate with Piperun API
|
let ip_address = ipaddress::IPAddress::parse(OLLAMA_URL.to_string());
|
||||||
|
let OLLAMA_SANITIZED_IP = match ip_address {
|
||||||
|
Ok(ip) => {
|
||||||
|
if ip.is_ipv4() {
|
||||||
|
OLLAMA_URL.clone()
|
||||||
|
} else {
|
||||||
|
format!("[{}]", OLLAMA_URL.clone())
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => OLLAMA_URL.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
// Send the authentication request
|
// Send the authentication request
|
||||||
let client = reqwest::blocking::Client::new();
|
let client = reqwest::blocking::Client::new();
|
||||||
@@ -215,17 +230,122 @@ fn main() {
|
|||||||
|
|
||||||
return talk_id_get_result;
|
return talk_id_get_result;
|
||||||
})
|
})
|
||||||
.take(1)
|
.skip(9)
|
||||||
|
.take(4)
|
||||||
.for_each(|result| {
|
.for_each(|result| {
|
||||||
let json = result.unwrap().json::<serde_json::Value>().expect("Failed to deserialize response to JSON");
|
let json = result.unwrap().json::<serde_json::Value>().expect("Failed to deserialize response to JSON");
|
||||||
let talk_histories = &json["talk_histories"];
|
let talk_histories = &json["talk_histories"];
|
||||||
let data = &talk_histories["data"];
|
let data = &talk_histories["data"];
|
||||||
|
|
||||||
talk_histories.as_array().expect("Wrong message type received from talk histories").iter().rev().for_each(|message_object|
|
let talk = talk_histories.as_array().expect("Wrong message type received from talk histories").iter().rev().map(|message_object|
|
||||||
{
|
{
|
||||||
println!("Message obj: {:?}", message_object)
|
// println!("Message obj: {:?}", message_object)
|
||||||
|
let new_json_filtered = format!(
|
||||||
|
"{{
|
||||||
|
message: {},
|
||||||
|
sent_at: {},
|
||||||
|
type: {}
|
||||||
|
}}",
|
||||||
|
message_object["message"],
|
||||||
|
message_object["sent_at"],
|
||||||
|
message_object["type"]
|
||||||
|
);
|
||||||
|
// println!("{}", new_json_filtered);
|
||||||
|
new_json_filtered
|
||||||
|
}).reduce(|acc, e| {format!("{acc}\n{e}")}).expect("Error extracting talk");
|
||||||
|
|
||||||
|
let system = "
|
||||||
|
Por favor haja como se você fosse o **supervisor de atendimentos via chat** e deve avaliar o desempenho de cada agente segundo os critérios.
|
||||||
|
|
||||||
|
### Critérios de Avaliação
|
||||||
|
1. **Apresentação inicial**
|
||||||
|
- Se o agente se apresentar no início, ganha 1 ponto.
|
||||||
|
|
||||||
|
2. **Entendimento da necessidade**
|
||||||
|
- Se o cliente informar ‘estou sem conexão’ ou ‘conexão está lenta’ e o agente não perguntar “Como posso te ajudar?”, ganha 1 ponto.
|
||||||
|
|
||||||
|
3. **Coleta de e-mail**
|
||||||
|
- Se o agente solicitar ou confirmar o e-mail do cliente, ganha 1 ponto.
|
||||||
|
|
||||||
|
4. **Protocolo de atendimento**
|
||||||
|
- Se o agente informar o protocolo, ganha 1 ponto.
|
||||||
|
|
||||||
|
5. **Uso correto do português**
|
||||||
|
- Se o agente usar corretamente o português (inclusive “tu”, “teu”, “tua”), ganha 1 ponto.
|
||||||
|
|
||||||
|
6. **Tempo de resposta**
|
||||||
|
- Se o agente não deixar o cliente sem retorno por mais de 5 minutos, ganha 1 ponto.
|
||||||
|
|
||||||
|
7. **Paciência**
|
||||||
|
- Se o agente for paciente, mesmo com clientes impacientes, ganha 1 ponto.
|
||||||
|
|
||||||
|
8. **Educação e cordialidade**
|
||||||
|
- Se o agente usar agradecimentos, saudações e linguagem respeitosa, ganha 1 ponto.
|
||||||
|
|
||||||
|
9. **Cobertura de todas as dúvidas**
|
||||||
|
- Se o agente não ignorar nenhuma pergunta (direta ou indireta), ganha 1 ponto.
|
||||||
|
|
||||||
|
10. **Disponibilidade**
|
||||||
|
- Se o agente demonstrar que a empresa está sempre disponível para ajudar, ganha 1 ponto.
|
||||||
|
|
||||||
|
11. **Conhecimento técnico**
|
||||||
|
- Se o agente demonstrar embasamento técnico, ganha 1 ponto.
|
||||||
|
- **Desconsidere**: respostas vagamente técnicas ou suposições sem explicação (ex.: “aconteceu do nada”, alterações em Wi-Fi quando o cliente reporta dispositivo cabeado etc.).
|
||||||
|
|
||||||
|
12. **Didática**
|
||||||
|
- Se o agente explicar claramente o que fez, por que fez e indicar exatamente quais cabos ou procedimentos, ganha 1 ponto.
|
||||||
|
- **Desconsidere**: instruções vagas (“recoloque os cabos”, “poderia mexer nos cabos?”) ou sem justificativa.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
As mensagens do chat estão estruturadas em JSON com os campos:
|
||||||
|
- **message**: conteúdo da mensagem
|
||||||
|
- **sent_at**: horário de envio
|
||||||
|
- **type**: tipo da mensagem (`IN`, `OUT` ou `SYSTEM`). As mensagens do agente são sempre do tipo `OUT`.
|
||||||
|
|
||||||
|
Caso não seja identificado um critério, atribua 0 pontos, quando identificado atribua 1 ponto.
|
||||||
|
|
||||||
|
A sua resposta deve ser uma apenas uma **tabela CSV** com as colunas: CATEGORIA,PONTOS,MOTIVO
|
||||||
|
onde cada linha contém a avaliação de um dos critérios acima
|
||||||
|
|
||||||
|
**A seguir estão as mensagens do atendimento**, em JSON, avalie e retorne um CSV.
|
||||||
|
|
||||||
|
";
|
||||||
|
|
||||||
|
// println!("{system}");
|
||||||
|
|
||||||
|
let ollama_api_request = client.post(format!("http://{OLLAMA_SANITIZED_IP}:{OLLAMA_PORT}/api/generate"))
|
||||||
|
.body(
|
||||||
|
serde_json::json!({
|
||||||
|
"model": OLLAMA_AI_MODEL,
|
||||||
|
"prompt": format!("{system} \n{talk}"),
|
||||||
|
"stream": false,
|
||||||
|
}).to_string()
|
||||||
|
);
|
||||||
|
|
||||||
|
let result = ollama_api_request.timeout(Duration::from_secs(3600)).send();
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(response) => {println!("Response: {:?}", response);
|
||||||
|
let response_json = response.json::<serde_json::Value>().expect("Failed to deserialize response to JSON");
|
||||||
|
println!("{}", response_json);
|
||||||
|
let ai_response = response_json["response"]
|
||||||
|
.as_str()
|
||||||
|
.expect("Failed to get AI response as string");
|
||||||
|
println!("AI Response: {}", ai_response);
|
||||||
|
|
||||||
|
let csv_response = ai_response.replace("```csv\n", "").replace("```", "");
|
||||||
|
|
||||||
|
// Save the CSV response to a file
|
||||||
|
|
||||||
});
|
let user_name = &json["agent"]["user"]["name"].as_str().unwrap_or("unknown_user");
|
||||||
|
let talk_id = &json["id"].as_u64().unwrap_or(0);
|
||||||
|
std::fs::write(format!("{} - {}.csv", user_name, talk_id), csv_response).expect("Unable to write file");
|
||||||
|
std::fs::write(format!("{} - {} - prompt.txt", user_name, talk_id), format!("{system} \n{talk}")).expect("Unable to write file");
|
||||||
|
|
||||||
|
},
|
||||||
|
Err(error) => {println!("Error {error}");}
|
||||||
|
};
|
||||||
// println!("Whole talk Histories \n\n{:?}", talk_histories);
|
// println!("Whole talk Histories \n\n{:?}", talk_histories);
|
||||||
// println!("\n\nData Only\n\n{:?}", data);
|
// println!("\n\nData Only\n\n{:?}", data);
|
||||||
// println!(
|
// println!(
|
||||||
|
|||||||
Reference in New Issue
Block a user