| 1 | use axum::extract::{Path, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use utopia_core::models::Role; |
| 6 | use utopia_core::AppError; |
| 7 | use uuid::Uuid; |
| 8 | |
| 9 | use crate::auth::AuthUser; |
| 10 | use crate::error::ApiResult; |
| 11 | use crate::retrieval; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | #[derive(Deserialize)] |
| 15 | pub struct SearchReq { |
| 16 | pub q: String, |
| 17 | #[serde(default)] |
| 18 | pub top_k: Option<usize>, |
| 19 | } |
| 20 | |
| 21 | pub async fn search( |
| 22 | State(state): State<AppState>, |
| 23 | AuthUser(user): AuthUser, |
| 24 | Path(kb_id): Path<Uuid>, |
| 25 | Json(req): Json<SearchReq>, |
| 26 | ) -> ApiResult<Json<serde_json::Value>> { |
| 27 | let q = req.q.trim(); |
| 28 | if q.is_empty() { |
| 29 | return Err(AppError::invalid("empty_query", "Search query cannot be empty").into()); |
| 30 | } |
| 31 | let kb = utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 32 | |
| 33 | let top_k = req.top_k.unwrap_or(10).min(50); |
| 34 | let chunks = retrieval::hybrid(&state, kb_id, kb.workspace_id, q, top_k).await?; |
| 35 | Ok(Json(json!({ "results": chunks }))) |
| 36 | } |