- Notifications
You must be signed in to change notification settings - Fork328
Embeddings support in the SDK#1475
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.
Uh oh!
There was an error while loading.Please reload this page.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
pytest | ||
pytest-asyncio |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,4 @@ | ||
use anyhow::Context; | ||
use rust_bridge::{alias, alias_methods}; | ||
use sqlx::Row; | ||
use tracing::instrument; | ||
@@ -13,7 +14,7 @@ use crate::{get_or_initialize_pool, query_runner::QueryRunner, types::Json}; | ||
#[cfg(feature = "python")] | ||
use crate::{query_runner::QueryRunnerPython, types::JsonPython}; | ||
#[alias_methods(new, query, transform, embed, embed_batch)] | ||
impl Builtins { | ||
pub fn new(database_url: Option<String>) -> Self { | ||
Self { database_url } | ||
@@ -87,6 +88,55 @@ impl Builtins { | ||
let results = results.first().unwrap().get::<serde_json::Value, _>(0); | ||
Ok(Json(results)) | ||
} | ||
/// Run the built-in `pgml.embed()` function. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `model` - The model to use. | ||
/// * `text` - The text to embed. | ||
/// | ||
pub async fn embed(&self, model: &str, text: &str) -> anyhow::Result<Json> { | ||
let pool = get_or_initialize_pool(&self.database_url).await?; | ||
let query = sqlx::query("SELECT embed FROM pgml.embed($1, $2)"); | ||
let result = query.bind(model).bind(text).fetch_one(&pool).await?; | ||
let result = result.get::<Vec<f32>, _>(0); | ||
let result = serde_json::to_value(result)?; | ||
Ok(Json(result)) | ||
} | ||
/// Run the built-in `pgml.embed()` function, but with handling for batch inputs and outputs. | ||
/// | ||
/// # Arguments | ||
/// | ||
/// * `model` - The model to use. | ||
/// * `texts` - The texts to embed. | ||
/// | ||
pub async fn embed_batch(&self, model: &str, texts: Json) -> anyhow::Result<Json> { | ||
let texts = texts | ||
.0 | ||
.as_array() | ||
.with_context(|| "embed_batch takes an array of strings")? | ||
.into_iter() | ||
.map(|v| { | ||
v.as_str() | ||
.with_context(|| "only text embeddings are supported") | ||
.unwrap() | ||
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. You can collect into a 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. Something like let texts = texts.0.as_array().with_context(||"embed_batch takes an array of texts")?.iter().map(|v|{ v.as_str().with_context(||"only text embeddings are supported").map(|s| s.to_string())}).collect::<anyhow::Result<Vec<String>>>()?; I think will work. 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. I don't think we want that. The API accepts an array of strings, so if someone passes in an array of objects that can be cast to a string, they will get embeddings of integers, or whatever else they passed in, which will make them think that everything is fine. 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. We are still calling | ||
.to_string() | ||
}) | ||
.collect::<Vec<String>>(); | ||
let pool = get_or_initialize_pool(&self.database_url).await?; | ||
let query = sqlx::query("SELECT embed AS embed_batch FROM pgml.embed($1, $2)"); | ||
let results = query | ||
.bind(model) | ||
.bind(texts) | ||
.fetch_all(&pool) | ||
.await? | ||
.into_iter() | ||
.map(|embeddings| embeddings.get::<Vec<f32>, _>(0)) | ||
.collect::<Vec<Vec<f32>>>(); | ||
Ok(Json(serde_json::to_value(results)?)) | ||
} | ||
} | ||
#[cfg(test)] | ||
@@ -117,4 +167,28 @@ mod tests { | ||
assert!(results.as_array().is_some()); | ||
Ok(()) | ||
} | ||
#[tokio::test] | ||
async fn can_embed() -> anyhow::Result<()> { | ||
internal_init_logger(None, None).ok(); | ||
let builtins = Builtins::new(None); | ||
let results = builtins.embed("intfloat/e5-small-v2", "test").await?; | ||
assert!(results.as_array().is_some()); | ||
Ok(()) | ||
} | ||
#[tokio::test] | ||
async fn can_embed_batch() -> anyhow::Result<()> { | ||
internal_init_logger(None, None).ok(); | ||
let builtins = Builtins::new(None); | ||
let results = builtins | ||
.embed_batch( | ||
"intfloat/e5-small-v2", | ||
Json(serde_json::json!(["test", "test2",])), | ||
) | ||
.await?; | ||
assert!(results.as_array().is_some()); | ||
assert_eq!(results.as_array().unwrap().len(), 2); | ||
Ok(()) | ||
} | ||
} |