| 1 | //! 混合检索:BM25(Tantivy)+ 向量(pgvector)→ RRF 融合。 |
| 2 | //! embedding 未配置或请求失败时静默降级为纯 BM25。 |
| 3 | |
| 4 | use crate::llm_util; |
| 5 | use crate::state::AppState; |
| 6 | use utopia_core::models::ChunkView; |
| 7 | use utopia_core::AppResult; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | const RECALL_PER_CHANNEL: usize = 24; |
| 11 | |
| 12 | pub async fn hybrid( |
| 13 | state: &AppState, |
| 14 | kb_id: Uuid, |
| 15 | workspace_id: Uuid, |
| 16 | query: &str, |
| 17 | top_k: usize, |
| 18 | ) -> AppResult<Vec<ChunkView>> { |
| 19 | let mut lists: Vec<Vec<String>> = Vec::new(); |
| 20 | |
| 21 | // BM25 |
| 22 | let bm25 = state |
| 23 | .search |
| 24 | .search(&kb_id.to_string(), query, RECALL_PER_CHANNEL) |
| 25 | .map_err(utopia_core::AppError::Other)?; |
| 26 | lists.push(bm25.into_iter().map(|h| h.chunk_id).collect()); |
| 27 | |
| 28 | // 向量(可选通道) |
| 29 | let settings = utopia_store::settings::get(&state.pool, workspace_id).await?; |
| 30 | if let Some(client) = settings.as_ref().and_then(llm_util::embed_client) { |
| 31 | match client.embed(&[query.to_string()]).await { |
| 32 | Ok(mut embeddings) if !embeddings.is_empty() => { |
| 33 | let ids = utopia_store::documents::vector_search( |
| 34 | &state.pool, |
| 35 | kb_id, |
| 36 | &embeddings.remove(0), |
| 37 | RECALL_PER_CHANNEL as i64, |
| 38 | ) |
| 39 | .await?; |
| 40 | lists.push(ids.into_iter().map(|id| id.to_string()).collect()); |
| 41 | } |
| 42 | Ok(_) => {} |
| 43 | Err(e) => tracing::warn!(error = %e, "查询 embedding 失败,降级为纯 BM25"), |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | let fused = utopia_search::rrf_fuse(&lists, top_k); |
| 48 | let ids: Vec<Uuid> = fused.iter().filter_map(|s| s.parse().ok()).collect(); |
| 49 | utopia_store::documents::chunks_by_ids(&state.pool, kb_id, &ids).await |
| 50 | } |