feat(chat): implement adaptive timeout and enhanced search functionality
- Introduced adaptive timeout logic for web searches and chat streaming, improving responsiveness and efficiency. - Updated `smartSearchRag` method to support timeout adjustments based on search rounds. - Enhanced `executeProgressiveSearch` to utilize adaptive timeouts and improve search result handling. - Added new utility functions for calculating adaptive timeouts based on rounds and attempts. - Integrated event listeners for chat session management, improving user experience during chat interactions. - Refactored chat message handling to accommodate new streaming and timeout features.
This commit is contained in:
1 parent
f2e8a1b933
commit
8c546f6474
13 files changed
+1547
-271
No files matched your search
@@ -29,8 +29,8 @@ struct OllamaMessageResponse {
|
||||
|
||||
/// Cliente Ollama headless (para execução em background)
|
||||
pub struct OllamaClient {
|
||||
base_url: String,
|
||||
client: reqwest::Client,
|
||||
pub(crate) base_url: String,
|
||||
pub(crate) client: reqwest::Client,
|
||||
}
|
||||
|
||||
impl OllamaClient {
|
||||
@@ -148,5 +148,109 @@ impl OllamaClient {
|
||||
|
||||
Ok(full_response.trim().to_string())
|
||||
}
|
||||
|
||||
/// Gera um título curto (3-5 palavras) para a pergunta do usuário
|
||||
pub async fn generate_title(&self, model: &str, user_input: &str) -> Result<String, String> {
|
||||
let system_prompt = "Você é um gerador de títulos. Responda APENAS com um título de 3-5 palavras que resuma a pergunta. Nada mais, sem explicações.";
|
||||
|
||||
let messages = vec![
|
||||
OllamaMessage {
|
||||
role: "system".to_string(),
|
||||
content: system_prompt.to_string(),
|
||||
},
|
||||
OllamaMessage {
|
||||
role: "user".to_string(),
|
||||
content: format!("Gere um título para: {}", user_input),
|
||||
},
|
||||
];
|
||||
|
||||
let request = OllamaChatRequest {
|
||||
model: model.to_string(),
|
||||
messages,
|
||||
stream: true,
|
||||
};
|
||||
|
||||
let url = format!("{}/api/chat", self.base_url);
|
||||
let response = self.client
|
||||
.post(&url)
|
||||
.json(&request)
|
||||
.timeout(std::time::Duration::from_secs(10)) // Timeout curto para resposta rápida
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("Failed to send title request: {}", e))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(format!("Ollama returned status: {}", response.status()));
|
||||
}
|
||||
|
||||
// Ler stream e acumular resposta (limitado a ~50 caracteres)
|
||||
let mut full_response = String::new();
|
||||
let mut stream = response.bytes_stream();
|
||||
|
||||
use futures_util::StreamExt;
|
||||
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk.map_err(|e| format!("Failed to read chunk: {}", e))?;
|
||||
let text = String::from_utf8_lossy(&chunk);
|
||||
|
||||
for line in text.lines() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match serde_json::from_str::<OllamaChunk>(line) {
|
||||
Ok(chunk_data) => {
|
||||
if let Some(message) = chunk_data.message {
|
||||
full_response.push_str(&message.content);
|
||||
|
||||
// Limitar tamanho para evitar respostas longas
|
||||
if full_response.len() > 50 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if chunk_data.done == Some(true) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
|
||||
// Se já temos resposta suficiente, parar
|
||||
if full_response.len() > 30 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let title = full_response.trim().to_string();
|
||||
|
||||
// Fallback se título estiver vazio ou muito longo
|
||||
if title.is_empty() || title.len() > 50 {
|
||||
// Extrair primeiras palavras da pergunta como fallback
|
||||
let words: Vec<&str> = user_input.split_whitespace().take(5).collect();
|
||||
Ok(words.join(" "))
|
||||
} else {
|
||||
Ok(title)
|
||||
}
|
||||
}
|
||||
|
||||
/// Gera emoji baseado no título
|
||||
pub fn generate_emoji(title: &str) -> String {
|
||||
let title_lower = title.to_lowercase();
|
||||
|
||||
// Keywords para emojis
|
||||
if title_lower.contains("código") || title_lower.contains("program") || title_lower.contains("code") {
|
||||
"💻".to_string()
|
||||
} else if title_lower.contains("pergunta") || title_lower.contains("question") || title_lower.contains("como") {
|
||||
"❓".to_string()
|
||||
} else if title_lower.contains("explica") || title_lower.contains("explain") {
|
||||
"📚".to_string()
|
||||
} else if title_lower.contains("ajuda") || title_lower.contains("help") {
|
||||
"🆘".to_string()
|
||||
} else {
|
||||
"💬".to_string() // Default
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user