Skip to main content

semquery_core/
models.rs

1use std::fmt;
2use std::ops::Range;
3use std::path::PathBuf;
4use std::result::Result as StdResult;
5use std::str::FromStr;
6
7use chrono::{DateTime, Utc};
8use serde::{Deserialize, Serialize};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Document {
12  /// Stable document identifier; currently derived from the file path so the
13  /// same path always maps to the same `id` across reindexes.
14  pub id: String,
15  /// SHA-256 of file content; drives incremental reindex.
16  pub content_hash: String,
17  pub content_size: usize,
18  pub indexed_at: DateTime<Utc>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct Chunk {
23  /// SHA-256 of `text`; enables content-addressed dedup.
24  pub id: String,
25  /// `Document.id` this chunk belongs to.
26  pub doc_id: String,
27  /// Full original text actually embedded.
28  pub text: String,
29  pub byte_range: Range<usize>,
30}
31
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct ChunkCandidate {
34  pub text: String,
35  pub byte_range: Range<usize>,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct SearchHit {
40  pub chunk: Chunk,
41  /// File system path of the source document, resolved from `document_paths`.
42  pub file_path: PathBuf,
43  pub score: f32,
44  pub explain: ScoreExplain,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
48#[serde(rename_all = "snake_case")]
49pub enum SearchStage {
50  EmbedQuery,
51  Bm25Recall,
52  VectorRecall,
53  Fusion,
54  Rerank,
55  ResolvePaths,
56  Assemble,
57}
58
59impl SearchStage {
60  pub fn as_str(self) -> &'static str {
61    match self {
62      Self::EmbedQuery => "embed_query",
63      Self::Bm25Recall => "bm25_recall",
64      Self::VectorRecall => "vector_recall",
65      Self::Fusion => "fusion",
66      Self::Rerank => "rerank",
67      Self::ResolvePaths => "resolve_paths",
68      Self::Assemble => "assemble",
69    }
70  }
71}
72
73impl fmt::Display for SearchStage {
74  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75    f.write_str(self.as_str())
76  }
77}
78
79/// Aggregated timings of one hybrid-search run, in milliseconds.
80#[derive(Debug, Clone, Default, Serialize, Deserialize)]
81pub struct SearchStats {
82  pub total_ms: u64,
83  pub embed_ms: u64,
84  pub bm25_ms: u64,
85  pub vector_ms: u64,
86  pub fusion_ms: u64,
87  pub rerank_ms: u64,
88}
89
90/// Streaming events emitted by the hybrid search pipeline, in order.
91/// The stream ends after `Completed` or when the underlying future returns Err.
92#[derive(Debug, Clone, Serialize, Deserialize)]
93#[serde(tag = "type", rename_all = "snake_case")]
94pub enum SearchEvent {
95  /// A model file needs downloading from the model hub (not yet cached).
96  /// Emitted as the first events of a lazy search stream.
97  ModelDownloadStart {
98    /// Which model role this file belongs to.
99    role: ModelRole,
100    /// HuggingFace repo id.
101    repo_id: String,
102    /// File within the repo.
103    filename: String,
104  },
105  /// A model file download finished.
106  ModelDownloadComplete {
107    /// Which model role this file belongs to.
108    role: ModelRole,
109    /// Wall time of the download, in milliseconds.
110    elapsed_ms: u64,
111  },
112  /// A pipeline stage started — for progress display.
113  StageStarted { stage: SearchStage },
114  /// A pipeline stage finished — carries the stage duration.
115  StageFinished { stage: SearchStage, elapsed_ms: u64 },
116  /// Retrieval finished: final ranked hits. Also the terminal event.
117  Completed { hits: Vec<SearchHit>, stats: SearchStats },
118}
119
120/// Aggregated timings of one ask run, in milliseconds.
121#[derive(Debug, Clone, Default, Serialize, Deserialize)]
122pub struct AskStats {
123  pub total_ms: u64,
124  pub retrieve_ms: u64,
125  pub prompt_ms: u64,
126  pub llm_ms: u64,
127}
128
129/// Streaming events emitted by the ask pipeline, in order.
130/// The stream ends after `AnswerComplete` or when the underlying future returns Err.
131#[derive(Debug, Clone, Serialize, Deserialize)]
132#[serde(tag = "type", rename_all = "snake_case")]
133pub enum AskEvent {
134  /// A model file needs downloading from the model hub (not yet cached).
135  /// Emitted as the first events of a lazy ask stream.
136  ModelDownloadStart {
137    /// Which model role this file belongs to.
138    role: ModelRole,
139    /// HuggingFace repo id.
140    repo_id: String,
141    /// File within the repo.
142    filename: String,
143  },
144  /// A model file download finished.
145  ModelDownloadComplete {
146    /// Which model role this file belongs to.
147    role: ModelRole,
148    /// Wall time of the download, in milliseconds.
149    elapsed_ms: u64,
150  },
151  /// A pipeline stage started — for progress display.
152  StageStarted { stage: SearchStage },
153  /// A pipeline stage finished — carries the stage duration.
154  StageFinished { stage: SearchStage, elapsed_ms: u64 },
155  /// Retrieval finished: the context set that grounds the answer.
156  Hits { hits: Vec<SearchHit> },
157  /// A streamed piece of LLM output (one token or a multi-token delta).
158  Token { delta: String },
159  /// Terminal event: the full answer with citations, plus timings.
160  AnswerComplete { answer: Answer, stats: AskStats },
161}
162
163#[derive(Debug, Clone, Default, Serialize, Deserialize)]
164pub struct ScoreExplain {
165  pub bm25_score: Option<f32>,
166  pub vector_score: Option<f32>,
167  pub rrf_score: Option<f32>,
168  pub rerank_score: Option<f32>,
169  pub final_score: f32,
170}
171
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct ScoredChunk {
174  pub chunk: Chunk,
175  pub score: f32,
176}
177
178#[derive(Debug, Clone, Serialize, Deserialize)]
179pub struct Answer {
180  pub text: String,
181  pub citations: Vec<Citation>,
182}
183
184#[derive(Debug, Clone, Serialize, Deserialize)]
185pub struct Citation {
186  /// Marker as printed in `text`, e.g. `[1]`.
187  pub marker: String,
188  /// Human-readable source, e.g. `docs/a.txt (bytes 120-512)`.
189  pub source: String,
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
193pub enum ModelRole {
194  Embedding,
195  Reranker,
196  Chat,
197  Tokenizer,
198}
199
200impl ModelRole {
201  pub fn as_str(self) -> &'static str {
202    match self {
203      Self::Embedding => "embedding",
204      Self::Reranker => "reranker",
205      Self::Chat => "chat",
206      Self::Tokenizer => "tokenizer",
207    }
208  }
209}
210
211impl fmt::Display for ModelRole {
212  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213    f.write_str(self.as_str())
214  }
215}
216
217impl FromStr for ModelRole {
218  type Err = String;
219  fn from_str(s: &str) -> StdResult<Self, Self::Err> {
220    match s {
221      "embedding" => Ok(Self::Embedding),
222      "reranker" => Ok(Self::Reranker),
223      "chat" => Ok(Self::Chat),
224      "tokenizer" => Ok(Self::Tokenizer),
225      other => Err(format!("unknown model role: {other}")),
226    }
227  }
228}
229
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct ModelSpec {
232  pub role: ModelRole,
233  pub repo_id: String,
234  pub filename: String,
235  pub revision: String,
236  pub checksum: Option<String>,
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize)]
240pub struct LlmConfig {
241  pub n_ctx: u32,
242  pub temperature: f32,
243  pub top_p: f32,
244  pub max_tokens: usize,
245  pub seed: u32,
246  pub system_prompt: String,
247}
248
249impl Default for LlmConfig {
250  fn default() -> Self {
251    Self {
252      n_ctx: 8192,
253      temperature: 0.7,
254      top_p: 0.9,
255      max_tokens: 512,
256      seed: 0,
257      system_prompt: "You are a helpful assistant.".into(),
258    }
259  }
260}
261
262#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct Collection {
264  pub name: String,
265  pub path: PathBuf,
266}
267
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct DocumentSource {
270  pub path: PathBuf,
271  pub content: String,
272}
273
274#[derive(Debug, Clone, Serialize, Deserialize)]
275pub struct EngineStatus {
276  pub documents: usize,
277  pub chunks: usize,
278  pub collections: Vec<Collection>,
279}