Skip to content

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 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 3 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pgml-sdks/pgml/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pgml-sdks/pgml/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "pgml"
version = "1.0.3"
version = "1.0.4"
edition = "2021"
authors = ["PosgresML <[email protected]>"]
homepage = "https://postgresml.org/"
Expand Down
2 changes: 2 additions & 0 deletions pgml-sdks/pgml/python/tests/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pytest
pytest-asyncio
12 changes: 12 additions & 0 deletions pgml-sdks/pgml/python/tests/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ def test_can_create_builtins():
builtins = pgml.Builtins()
assert builtins is not None

@pytest.mark.asyncio
async def test_can_embed_with_builtins():
builtins = pgml.Builtins()
result = await builtins.embed("intfloat/e5-small-v2", "test")
assert result is not None

@pytest.mark.asyncio
async def test_can_embed_batch_with_builtins():
builtins = pgml.Builtins()
result = await builtins.embed_batch("intfloat/e5-small-v2", ["test"])
assert result is not None


###################################################
## Test searches ##################################
Expand Down
76 changes: 75 additions & 1 deletion pgml-sdks/pgml/src/builtins.rs
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;
Expand All @@ -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)]
#[alias_methods(new, query, transform, embed, embed_batch)]
impl Builtins {
pub fn new(database_url: Option<String>) -> Self {
Self { database_url }
Expand Down Expand Up @@ -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()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can collect into a Result<Vec<_>> so you can ? the Result instead of panicking if the value is not a str.

Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Contributor Author

Choose a reason for hiding this comment

The 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.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are still calling as_str here so if it was an object, it wouldn't be treated as a string. I was merely suggesting using Result::Err instead of unwrap. But all is good.

.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)]
Expand Down Expand Up @@ -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(())
}
}