791c782606
- postgres_db.rs: CAST source_weight to ::float8 (NUMERIC→FLOAT8) - rerank.rs: char-based truncation for UTF-8 safety - Both fixes prevent tokio worker panics that killed search requests Bug root causes: - keyword/BM25: sqlx decode f64 from NUMERIC panicked at postgres_db.rs:3758 - llm-smart: &text[..100] byte slice panicked at rerank.rs:52 on Chinese text Verified: both /api/v1/search/keyword and /api/v1/search/llm-smart now return 200
231 lines
6.4 KiB
Rust
231 lines
6.4 KiB
Rust
use std::collections::HashSet;
|
|
|
|
use anyhow::Result;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::time::Duration;
|
|
use tracing::{debug, warn};
|
|
|
|
use crate::core::config;
|
|
use crate::core::llm::function_calling::LLM_CLIENT;
|
|
|
|
#[derive(Debug, Serialize)]
|
|
struct ChatRequest {
|
|
model: String,
|
|
messages: Vec<ChatMessage>,
|
|
temperature: f32,
|
|
max_tokens: u32,
|
|
stream: bool,
|
|
}
|
|
|
|
#[derive(Debug, Serialize, Deserialize)]
|
|
struct ChatMessage {
|
|
role: String,
|
|
content: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct ChatResponse {
|
|
choices: Vec<Choice>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct Choice {
|
|
message: ChatMessage,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize)]
|
|
struct RerankResponse {
|
|
ranked: Vec<usize>,
|
|
}
|
|
|
|
pub async fn rerank_search_results(
|
|
query: &str,
|
|
candidates: &[(usize, &str)],
|
|
) -> Result<Vec<usize>> {
|
|
if candidates.is_empty() {
|
|
return Ok(vec![]);
|
|
}
|
|
|
|
let mut chunks_text = String::new();
|
|
for (i, (_, text)) in candidates.iter().enumerate() {
|
|
let display = if text.chars().count() > 100 {
|
|
let truncated: String = text.chars().take(100).collect();
|
|
format!("{}...", truncated)
|
|
} else {
|
|
text.to_string()
|
|
};
|
|
chunks_text.push_str(&format!("[{}] {}\n", i + 1, display));
|
|
}
|
|
|
|
let prompt = format!(
|
|
r#"You are a search relevance judge. Rank ALL chunks by relevance to the query.
|
|
|
|
Query: "{}"
|
|
|
|
Chunks:
|
|
{}
|
|
|
|
Return a JSON object with ALL chunk numbers in order of relevance (most relevant first).
|
|
Example: {{"ranked": [5, 1, 3, 2, 4, 6, 7, 8, 9, 10]}}
|
|
Include every chunk number exactly once. Only respond with the JSON."#,
|
|
query, chunks_text
|
|
);
|
|
|
|
let req = ChatRequest {
|
|
model: config::llm::CHAT_MODEL.clone(),
|
|
messages: vec![
|
|
ChatMessage {
|
|
role: "system".to_string(),
|
|
content: "You are a precise search relevance judge.".to_string(),
|
|
},
|
|
ChatMessage {
|
|
role: "user".to_string(),
|
|
content: prompt,
|
|
},
|
|
],
|
|
temperature: 0.1,
|
|
max_tokens: 512,
|
|
stream: false,
|
|
};
|
|
|
|
debug!(
|
|
"LLM rerank: {} candidates for query '{}'",
|
|
candidates.len(),
|
|
query
|
|
);
|
|
|
|
let res = LLM_CLIENT
|
|
.post(&*config::llm::CHAT_URL)
|
|
.json(&req)
|
|
.timeout(Duration::from_secs(15))
|
|
.send()
|
|
.await?;
|
|
|
|
if !res.status().is_success() {
|
|
let status = res.status();
|
|
let body = res.text().await.unwrap_or_default();
|
|
warn!("LLM rerank API error: {} — body: {}", status, body);
|
|
return Ok(candidates.iter().map(|(idx, _)| *idx).collect());
|
|
}
|
|
|
|
let chat_res: ChatResponse = res.json().await?;
|
|
let content = chat_res
|
|
.choices
|
|
.into_iter()
|
|
.next()
|
|
.map(|c| c.message.content)
|
|
.unwrap_or_default();
|
|
|
|
let content = content.trim();
|
|
|
|
// Strip markdown code fences if present
|
|
let content = if content.starts_with("```") {
|
|
let lines: Vec<&str> = content.lines().collect();
|
|
let start = if lines.first().map(|l| l.contains("```")).unwrap_or(false) {
|
|
1
|
|
} else {
|
|
0
|
|
};
|
|
let end = if lines.last().map(|l| l.contains("```")).unwrap_or(false) {
|
|
lines.len().saturating_sub(1)
|
|
} else {
|
|
lines.len()
|
|
};
|
|
lines[start..end].join("\n").trim().to_string()
|
|
} else {
|
|
content.to_string()
|
|
};
|
|
|
|
let json_start = content.find('{');
|
|
let json_end = content.rfind('}');
|
|
|
|
if let (Some(start), Some(end)) = (json_start, json_end) {
|
|
let json_str = &content[start..=end];
|
|
match serde_json::from_str::<RerankResponse>(json_str) {
|
|
Ok(parsed) => {
|
|
let mut ranked: Vec<usize> = parsed
|
|
.ranked
|
|
.into_iter()
|
|
.filter_map(|i| {
|
|
if i > 0 && i <= candidates.len() {
|
|
Some(candidates[i - 1].0)
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect();
|
|
|
|
if !ranked.is_empty() {
|
|
let seen: HashSet<usize> = ranked.iter().cloned().collect();
|
|
for (orig_idx, _) in candidates {
|
|
if !seen.contains(orig_idx) {
|
|
ranked.push(*orig_idx);
|
|
}
|
|
}
|
|
return Ok(ranked);
|
|
}
|
|
warn!("LLM rerank returned empty ranked list");
|
|
}
|
|
Err(e) => {
|
|
warn!("Failed to parse LLM rerank JSON: {}", e);
|
|
}
|
|
}
|
|
}
|
|
|
|
warn!(
|
|
"LLM rerank: could not parse response — content: {}",
|
|
&content[..content.len().min(200)]
|
|
);
|
|
Ok((0..candidates.len()).collect())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn test_utf8_truncation_safe() {
|
|
let long_chinese = "這是一段很長的中文文字,用來測試字元截斷是否正確運作,避免在多位元組字元中間切割造成恐慌。".repeat(3);
|
|
let text = long_chinese.as_str();
|
|
|
|
let display = if text.chars().count() > 100 {
|
|
let truncated: String = text.chars().take(100).collect();
|
|
format!("{}...", truncated)
|
|
} else {
|
|
text.to_string()
|
|
};
|
|
|
|
assert!(display.chars().count() <= 103);
|
|
assert!(display.starts_with("這是一段很長"));
|
|
assert!(display.ends_with("..."));
|
|
}
|
|
|
|
#[test]
|
|
fn test_utf8_truncation_short() {
|
|
let short_text = "短文字";
|
|
let display = if short_text.chars().count() > 100 {
|
|
let truncated: String = short_text.chars().take(100).collect();
|
|
format!("{}...", truncated)
|
|
} else {
|
|
short_text.to_string()
|
|
};
|
|
|
|
assert_eq!(display, "短文字");
|
|
assert!(!display.ends_with("..."));
|
|
}
|
|
|
|
#[test]
|
|
fn test_utf8_truncation_mixed() {
|
|
let mixed = "Mixed 中英文 text 混合 content".repeat(10);
|
|
let display = if mixed.chars().count() > 100 {
|
|
let truncated: String = mixed.chars().take(100).collect();
|
|
format!("{}...", truncated)
|
|
} else {
|
|
mixed.to_string()
|
|
};
|
|
|
|
assert!(display.chars().count() <= 103);
|
|
assert!(display.ends_with("..."));
|
|
}
|
|
}
|