-
Notifications
You must be signed in to change notification settings - Fork 0
feat(search): Add basic vector search (l2_distance) #26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| use serde_json::Value; | ||
|
|
||
| /// Try to parse a vector from stdin. Accepts either: | ||
| /// - A raw JSON array of numbers: [0.1, -0.2, ...] | ||
| /// - An OpenAI-compatible response: {"data": [{"embedding": [...]}]} | ||
| pub fn read_vector_from_stdin() -> Vec<f64> { | ||
| use std::io::Read; | ||
| let mut input = String::new(); | ||
| std::io::stdin().read_to_string(&mut input).unwrap_or_else(|e| { | ||
| eprintln!("error reading stdin: {e}"); | ||
| std::process::exit(1); | ||
| }); | ||
|
|
||
| let input = input.trim(); | ||
| if input.is_empty() { | ||
| eprintln!("error: no vector provided on stdin"); | ||
| std::process::exit(1); | ||
| } | ||
|
|
||
| let parsed: Value = match serde_json::from_str(input) { | ||
| Ok(v) => v, | ||
| Err(e) => { | ||
| eprintln!("error parsing vector from stdin: {e}"); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
|
|
||
| extract_vector(&parsed) | ||
| } | ||
|
|
||
| /// Extract a float vector from either a raw JSON array or an OpenAI embedding response. | ||
| fn extract_vector(value: &Value) -> Vec<f64> { | ||
| // Raw array: [0.1, -0.2, ...] | ||
| if let Some(arr) = value.as_array() { | ||
| return parse_float_array(arr); | ||
| } | ||
|
|
||
| // OpenAI response: {"data": [{"embedding": [...]}]} | ||
| if let Some(embedding) = value.get("data") | ||
| .and_then(|d| d.get(0)) | ||
| .and_then(|d| d.get("embedding")) | ||
| .and_then(|e| e.as_array()) | ||
| { | ||
| return parse_float_array(embedding); | ||
| } | ||
|
|
||
| eprintln!("error: stdin must be a JSON array of numbers or an OpenAI embedding response"); | ||
| std::process::exit(1); | ||
| } | ||
|
|
||
| fn parse_float_array(arr: &[Value]) -> Vec<f64> { | ||
| arr.iter() | ||
| .enumerate() | ||
| .map(|(i, v)| { | ||
| v.as_f64().unwrap_or_else(|| { | ||
| eprintln!("error: vector element {i} is not a number: {v}"); | ||
| std::process::exit(1); | ||
| }) | ||
| }) | ||
| .collect() | ||
| } | ||
|
|
||
| /// Call the OpenAI embeddings API to generate a vector from text. | ||
| pub fn openai_embed(text: &str, model: &str) -> Vec<f64> { | ||
| let api_key = match std::env::var("OPENAI_API_KEY") { | ||
| Ok(k) if !k.is_empty() => k, | ||
| _ => { | ||
| eprintln!("error: OPENAI_API_KEY environment variable is not set"); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
|
|
||
| let body = serde_json::json!({ | ||
| "input": text, | ||
| "model": model, | ||
| }); | ||
|
|
||
| let client = reqwest::blocking::Client::new(); | ||
| let resp = match client | ||
| .post("https://api.openai.com/v1/embeddings") | ||
| .header("Authorization", format!("Bearer {api_key}")) | ||
| .header("Content-Type", "application/json") | ||
| .json(&body) | ||
| .send() | ||
| { | ||
| Ok(r) => r, | ||
| Err(e) => { | ||
| eprintln!("error connecting to OpenAI API: {e}"); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
|
|
||
| if !resp.status().is_success() { | ||
| let status = resp.status(); | ||
| let body = resp.text().unwrap_or_default(); | ||
| let message = serde_json::from_str::<Value>(&body) | ||
| .ok() | ||
| .and_then(|v| v["error"]["message"].as_str().map(str::to_string)) | ||
| .unwrap_or(body); | ||
| eprintln!("error from OpenAI API ({status}): {message}"); | ||
| std::process::exit(1); | ||
| } | ||
|
|
||
| let parsed: Value = match resp.json() { | ||
| Ok(v) => v, | ||
| Err(e) => { | ||
| eprintln!("error parsing OpenAI response: {e}"); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
|
|
||
| extract_vector(&parsed) | ||
| } | ||
|
|
||
| /// Format a vector as a SQL ARRAY literal: ARRAY[0.1,-0.2,...] | ||
| pub fn vector_to_sql(vec: &[f64]) -> String { | ||
| format!("ARRAY[{}]", vec.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(",")) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ mod config; | |
| mod connections; | ||
| mod connections_new; | ||
| mod datasets; | ||
| mod embedding; | ||
| mod indexes; | ||
| mod jobs; | ||
| mod queries; | ||
|
|
@@ -218,20 +219,54 @@ fn main() { | |
| } | ||
| } | ||
| } | ||
| Commands::Search { query, table, column, select, limit, workspace_id, output } => { | ||
| Commands::Search { query, table, column, select, limit, model, workspace_id, output } => { | ||
| let workspace_id = resolve_workspace(workspace_id); | ||
| let columns = match select.as_deref() { | ||
| Some(cols) => format!("{}, score", cols), | ||
| None => "*".to_string(), | ||
| let select_cols = select.as_deref().unwrap_or("*"); | ||
|
|
||
| // Determine search mode: | ||
| // 1. --model flag: embed the query text via the model provider | ||
| // 2. No query + piped stdin: read vector from stdin | ||
| // 3. Query text without --model: BM25 text search | ||
| let sql = if let Some(ref model_name) = model { | ||
| let query_text = match query { | ||
| Some(ref q) => q.as_str(), | ||
| None => { | ||
| eprintln!("error: --model requires a search query text"); | ||
| std::process::exit(1); | ||
| } | ||
| }; | ||
| let vec = embedding::openai_embed(query_text, model_name); | ||
| let vec_str = embedding::vector_to_sql(&vec); | ||
| format!( | ||
| "SELECT {}, l2_distance({}, {}) as dist FROM {} ORDER BY dist LIMIT {}", | ||
| select_cols, column, vec_str, table, limit, | ||
|
pthurlow marked this conversation as resolved.
|
||
| ) | ||
| } else if query.is_none() { | ||
| use std::io::IsTerminal; | ||
| if std::io::stdin().is_terminal() { | ||
| eprintln!("error: provide a search query or pipe a vector via stdin"); | ||
| std::process::exit(1); | ||
| } | ||
| let vec = embedding::read_vector_from_stdin(); | ||
| let vec_str = embedding::vector_to_sql(&vec); | ||
| format!( | ||
| "SELECT {}, l2_distance({}, {}) as dist FROM {} ORDER BY dist LIMIT {}", | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same unquoted-identifier issue as above — |
||
| select_cols, column, vec_str, table, limit, | ||
| ) | ||
| } else { | ||
| let bm25_columns = match select.as_deref() { | ||
| Some(cols) => format!("{}, score", cols), | ||
| None => "*".to_string(), | ||
| }; | ||
| format!( | ||
| "SELECT {} FROM bm25_search('{}', '{}', '{}') ORDER BY score DESC LIMIT {}", | ||
| bm25_columns, | ||
| table.replace('\'', "''"), | ||
| column.replace('\'', "''"), | ||
| query.unwrap().replace('\'', "''"), | ||
| limit, | ||
| ) | ||
| }; | ||
| let sql = format!( | ||
| "SELECT {} FROM bm25_search('{}', '{}', '{}') ORDER BY score DESC LIMIT {}", | ||
| columns, | ||
| table.replace('\'', "''"), | ||
| column.replace('\'', "''"), | ||
| query.replace('\'', "''"), | ||
| limit, | ||
| ); | ||
| query::execute(&sql, &workspace_id, None, &output) | ||
| } | ||
| Commands::Queries { id, output, command } => { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.