feat: score-based search, LLM re-ranking endpoint, video title search, pipeline module
Core search changes: - Replace RRF with score-based merge (max of semantic/keyword/identity) - Add video title ILIKE search for brand/name queries (score 0.9) - Add /api/v1/search/llm-smart endpoint with Gemma 4 re-ranking - Fix LLM JSON parsing (markdown fences, empty responses) Infrastructure: - Rebuild Qdrant collection (clear 347K contaminated points) - Add dotenv loading to main.rs for config parity - Implement store_pre_chunk in postgres_db.rs Pipeline module (WordPress): - store-asrx, rule1, vectorize, phase1, complete endpoints - CLI commands for pipeline operations Docs: - SEARCH_SCORE_IMPROVEMENT.md (score-based merge proposal)
This commit is contained in:
@@ -1,2 +1,3 @@
|
||||
pub mod client;
|
||||
pub mod function_calling;
|
||||
pub mod rerank;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::Result;
|
||||
use reqwest::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::time::Duration;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::core::config;
|
||||
|
||||
#[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.len() > 100 {
|
||||
format!("{}...", &text[..100])
|
||||
} 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 client = Client::builder()
|
||||
.timeout(Duration::from_secs(15))
|
||||
.build()?;
|
||||
|
||||
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 = client
|
||||
.post(&*config::llm::CHAT_URL)
|
||||
.json(&req)
|
||||
.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(candidates.iter().map(|(idx, _)| *idx).collect())
|
||||
}
|
||||
Reference in New Issue
Block a user