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 pipeline stage started — for progress display.
93  StageStarted { stage: SearchStage },
94  /// A pipeline stage finished — carries the stage duration.
95  StageFinished { stage: SearchStage, elapsed_ms: u64 },
96  /// Retrieval finished: final ranked hits. Also the terminal event.
97  Completed { hits: Vec<SearchHit>, stats: SearchStats },
98}
99
100#[derive(Debug, Clone, Default, Serialize, Deserialize)]
101pub struct ScoreExplain {
102  pub bm25_score: Option<f32>,
103  pub vector_score: Option<f32>,
104  pub rrf_score: Option<f32>,
105  pub rerank_score: Option<f32>,
106  pub final_score: f32,
107}
108
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct ScoredChunk {
111  pub chunk: Chunk,
112  pub score: f32,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct Answer {
117  pub text: String,
118  pub citations: Vec<Citation>,
119}
120
121#[derive(Debug, Clone, Serialize, Deserialize)]
122pub struct Citation {
123  /// Marker as printed in `text`, e.g. `[1]`.
124  pub marker: String,
125  /// Human-readable source, e.g. `docs/a.txt (bytes 120-512)`.
126  pub source: String,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
130pub enum ModelRole {
131  Embedding,
132  Reranker,
133  Chat,
134  Tokenizer,
135}
136
137impl ModelRole {
138  pub fn as_str(self) -> &'static str {
139    match self {
140      Self::Embedding => "embedding",
141      Self::Reranker => "reranker",
142      Self::Chat => "chat",
143      Self::Tokenizer => "tokenizer",
144    }
145  }
146}
147
148impl std::fmt::Display for ModelRole {
149  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
150    f.write_str(self.as_str())
151  }
152}
153
154impl std::str::FromStr for ModelRole {
155  type Err = String;
156  fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
157    match s {
158      "embedding" => Ok(Self::Embedding),
159      "reranker" => Ok(Self::Reranker),
160      "chat" => Ok(Self::Chat),
161      "tokenizer" => Ok(Self::Tokenizer),
162      other => Err(format!("unknown model role: {other}")),
163    }
164  }
165}
166
167#[derive(Debug, Clone, Serialize, Deserialize)]
168pub struct ModelSpec {
169  pub role: ModelRole,
170  pub repo_id: String,
171  pub filename: String,
172  pub revision: String,
173  pub checksum: Option<String>,
174}
175
176#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct LlmConfig {
178  pub n_ctx: u32,
179  pub temperature: f32,
180  pub top_p: f32,
181  pub max_tokens: usize,
182  pub seed: u32,
183  pub system_prompt: String,
184}
185
186impl Default for LlmConfig {
187  fn default() -> Self {
188    Self {
189      n_ctx: 8192,
190      temperature: 0.7,
191      top_p: 0.9,
192      max_tokens: 512,
193      seed: 0,
194      system_prompt: "You are a helpful assistant.".into(),
195    }
196  }
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
200pub struct Collection {
201  pub name: String,
202  pub path: std::path::PathBuf,
203}
204
205#[derive(Debug, Clone, Serialize, Deserialize)]
206pub struct DocumentSource {
207  pub path: std::path::PathBuf,
208  pub content: String,
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
212pub struct EngineStatus {
213  pub documents: usize,
214  pub chunks: usize,
215  pub collections: Vec<Collection>,
216}