feat: working AI integration

This commit is contained in:
Jelson Stoelben Rodrigues
2025-06-18 10:12:20 -03:00
parent 33101951bc
commit 59eb18d0de
3 changed files with 256 additions and 14 deletions

View File

@@ -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 chrono::{self, Timelike};
use dotenv;
use reqwest;
use serde_json;
use serde_json::{self, json};
use ipaddress;
fn main() {
match dotenv::dotenv().ok() {
@@ -30,17 +31,31 @@ fn main() {
env::var("PIPERUN_BOT_USERNAME").expect("PIPERUN_BOT_USERNAME has not been set!");
let PIPERUN_BOT_PASSWORD =
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
println!("OLLAMA_URL: {}", OLLAMA_URL);
println!("OLLAMA_PORT: {}", OLLAMA_PORT);
println!("OLLAMA_AI_MODEL: {}", OLLAMA_AI_MODEL);
println!("PIPERUN_API_URL: {}", PIPERUN_API_URL);
println!("PIPERUN_CLIENT_ID: {}", PIPERUN_CLIENT_ID);
println!("PIPERUN_CLIENT_SECRET: {}", PIPERUN_CLIENT_SECRET);
println!("PIPERUN_BOT_USERNAME: {}", PIPERUN_BOT_USERNAME);
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
let client = reqwest::blocking::Client::new();
@@ -215,17 +230,122 @@ fn main() {
return talk_id_get_result;
})
.take(1)
.skip(9)
.take(4)
.for_each(|result| {
let json = result.unwrap().json::<serde_json::Value>().expect("Failed to deserialize response to JSON");
let talk_histories = &json["talk_histories"];
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!("\n\nData Only\n\n{:?}", data);
// println!(