Skip to main content

semquery_core/
models.rs

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