-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontext.rs
More file actions
282 lines (252 loc) · 8.74 KB
/
Copy pathcontext.rs
File metadata and controls
282 lines (252 loc) · 8.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0
//! IndexContext, QueryContext, and IndexOptions Python wrappers.
use pyo3::prelude::*;
use ::vectorless::{DocumentFormat, IndexContext, IndexMode, IndexOptions, QueryContext};
use super::error::VectorlessError;
/// Parse format string to DocumentFormat.
fn parse_format(format: &str) -> PyResult<DocumentFormat> {
match format.to_lowercase().as_str() {
"markdown" | "md" => Ok(DocumentFormat::Markdown),
"pdf" => Ok(DocumentFormat::Pdf),
_ => Err(PyErr::from(VectorlessError::new(
format!("Unknown format: {}. Supported: markdown, pdf", format),
"config",
))),
}
}
// ============================================================
// IndexOptions
// ============================================================
/// Options for controlling indexing behavior.
///
/// Args:
/// mode: Indexing mode - "default", "force", or "incremental".
/// generate_summaries: Whether to generate summaries. Default: True.
/// generate_description: Whether to generate document description. Default: False.
/// generate_ids: Whether to generate node IDs. Default: True.
/// enable_synonym_expansion: Whether to expand keywords with LLM-generated
/// synonyms during indexing. Improves recall for differently-worded queries.
/// Default: False.
#[pyclass(name = "IndexOptions", skip_from_py_object)]
#[derive(Clone)]
pub struct PyIndexOptions {
pub(crate) inner: IndexOptions,
}
#[pymethods]
impl PyIndexOptions {
#[new]
#[pyo3(signature = (mode="default", generate_summaries=true, generate_description=false, generate_ids=true, enable_synonym_expansion=true, timeout_secs=None))]
fn new(
mode: &str,
generate_summaries: bool,
generate_description: bool,
generate_ids: bool,
enable_synonym_expansion: bool,
timeout_secs: Option<u64>,
) -> PyResult<Self> {
let mut opts = IndexOptions::new();
match mode {
"default" => {}
"force" => opts = opts.with_mode(IndexMode::Force),
"incremental" => opts = opts.with_mode(IndexMode::Incremental),
_ => {
return Err(PyErr::from(VectorlessError::new(
format!(
"Unknown mode: {}. Supported: default, force, incremental",
mode
),
"config",
)));
}
}
opts.generate_summaries = generate_summaries;
opts.generate_description = generate_description;
opts.generate_ids = generate_ids;
opts.enable_synonym_expansion = enable_synonym_expansion;
if let Some(secs) = timeout_secs {
opts = opts.with_timeout_secs(secs);
}
Ok(Self { inner: opts })
}
fn __repr__(&self) -> String {
format!(
"IndexOptions(mode='{}', generate_summaries={}, generate_description={}, generate_ids={}, enable_synonym_expansion={})",
match self.inner.mode {
IndexMode::Default => "default",
IndexMode::Force => "force",
IndexMode::Incremental => "incremental",
},
self.inner.generate_summaries,
self.inner.generate_description,
self.inner.generate_ids,
self.inner.enable_synonym_expansion,
)
}
}
// ============================================================
// IndexContext
// ============================================================
/// Context for indexing a document.
///
/// Create using the static methods:
///
/// ```python
/// from vectorless import IndexContext
///
/// # Single file
/// ctx = IndexContext.from_path("./document.pdf")
///
/// # Multiple files
/// ctx = IndexContext.from_paths(["./a.pdf", "./b.md"])
///
/// # Directory
/// ctx = IndexContext.from_dir("./docs/")
///
/// # From text
/// ctx = IndexContext.from_content("# Title\\nContent...", "markdown").with_name("doc")
///
/// # From bytes
/// ctx = IndexContext.from_bytes(data, "pdf").with_name("doc")
/// ```
#[pyclass(name = "IndexContext")]
pub struct PyIndexContext {
pub(crate) inner: IndexContext,
}
#[pymethods]
impl PyIndexContext {
/// Create an IndexContext from a single file path.
#[staticmethod]
fn from_path(path: String) -> Self {
Self {
inner: IndexContext::from_path(&path),
}
}
/// Create an IndexContext from multiple file paths.
#[staticmethod]
fn from_paths(paths: Vec<String>) -> Self {
Self {
inner: IndexContext::from_paths(&paths),
}
}
/// Create an IndexContext from all supported files in a directory.
///
/// Args:
/// path: Directory path to scan.
/// recursive: If True, scan subdirectories recursively. Default: False.
#[staticmethod]
#[pyo3(signature = (path, recursive=false))]
fn from_dir(path: String, recursive: bool) -> Self {
let inner = IndexContext::from_dir(&path, recursive);
Self { inner }
}
/// Create an IndexContext from text content.
#[staticmethod]
#[pyo3(signature = (content, format="markdown"))]
fn from_content(content: String, format: &str) -> PyResult<Self> {
let doc_format = parse_format(format)?;
let ctx = IndexContext::from_content(&content, doc_format);
Ok(Self { inner: ctx })
}
/// Create an IndexContext from binary data.
#[staticmethod]
fn from_bytes(data: Vec<u8>, format: &str) -> PyResult<Self> {
let doc_format = parse_format(format)?;
let ctx = IndexContext::from_bytes(data, doc_format);
Ok(Self { inner: ctx })
}
/// Set the document name (single-source only).
fn with_name(&self, name: String) -> Self {
let ctx = self.inner.clone().with_name(&name);
Self { inner: ctx }
}
/// Apply indexing options.
fn with_options(&self, options: &PyIndexOptions) -> Self {
let ctx = self.inner.clone().with_options(options.inner.clone());
Self { inner: ctx }
}
/// Set indexing mode.
fn with_mode(&self, mode: &str) -> PyResult<Self> {
let m = match mode {
"default" => IndexMode::Default,
"force" => IndexMode::Force,
"incremental" => IndexMode::Incremental,
_ => {
return Err(PyErr::from(VectorlessError::new(
format!(
"Unknown mode: {}. Supported: default, force, incremental",
mode
),
"config",
)));
}
};
let ctx = self.inner.clone().with_mode(m);
Ok(Self { inner: ctx })
}
/// Number of document sources.
fn __len__(&self) -> usize {
self.inner.len()
}
/// Whether no sources are present.
fn is_empty(&self) -> bool {
self.inner.is_empty()
}
fn __repr__(&self) -> String {
format!("IndexContext(sources={})", self.inner.len())
}
}
// ============================================================
// QueryContext
// ============================================================
/// Context for a query operation.
///
/// ```python
/// from vectorless import QueryContext
///
/// # Query specific documents
/// ctx = QueryContext("What is the total revenue?").with_doc_ids([doc_id])
///
/// # Query multiple documents
/// ctx = QueryContext("What is the architecture?").with_doc_ids(["doc-1", "doc-2"])
///
/// # Query entire workspace
/// ctx = QueryContext("Explain the algorithm")
/// ```
#[pyclass(name = "QueryContext")]
pub struct PyQueryContext {
pub(crate) inner: QueryContext,
}
#[pymethods]
impl PyQueryContext {
/// Create a new query context (defaults to workspace scope).
#[new]
fn new(query: String) -> Self {
Self {
inner: QueryContext::new(&query),
}
}
/// Set scope to specific documents.
fn with_doc_ids(&self, doc_ids: Vec<String>) -> Self {
let ctx = self.inner.clone().with_doc_ids(doc_ids);
Self { inner: ctx }
}
/// Set scope to entire workspace.
fn with_workspace(&self) -> Self {
let ctx = self.inner.clone().with_workspace();
Self { inner: ctx }
}
/// Set per-operation timeout in seconds.
fn with_timeout_secs(&self, secs: u64) -> Self {
let ctx = self.inner.clone().with_timeout_secs(secs);
Self { inner: ctx }
}
/// Force the Orchestrator to analyze documents before dispatching Workers.
fn with_force_analysis(&self, force: bool) -> Self {
let ctx = self.inner.clone().with_force_analysis(force);
Self { inner: ctx }
}
fn __repr__(&self) -> String {
"QueryContext(...)".to_string()
}
}