Skip to content
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

feat: postgresql store #157

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
116 changes: 111 additions & 5 deletions Cargo.lock

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

5 changes: 2 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
resolver = "2"
members = [
"rig-core", "rig-lancedb",
"rig-mongodb", "rig-neo4j",
"rig-mongodb", "rig-neo4j", "rig-postgres",
"rig-qdrant", "rig-core/rig-core-derive",
"rig-sqlite"
]
"rig-sqlite"]
12 changes: 12 additions & 0 deletions rig-postgres/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- Postgres vector store
22 changes: 22 additions & 0 deletions rig-postgres/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "rig-postgres"
version = "0.1.0"
edition = "2021"
description = "PostgreSQL-based vector store implementation for the rig framework"
license = "MIT"

[dependencies]
pgvector = { version = "0.4.0", features = ["postgres"] }
rig-core = { path = "../rig-core", version = "0.5.0", features = ["derive"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.133"
tokio-postgres = "0.7.12"
tracing = "0.1.40"

[dev-dependencies]
anyhow = "1.0.94"
log = "0.4.22"
tokio = { version = "1.42.0", features = ["macros", "rt-multi-thread"] }
tokio-test = "0.4.4"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
uuid = { version = "1.11.0", features = ["v4"] }
7 changes: 7 additions & 0 deletions rig-postgres/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright (c) 2024, Playgrounds Analytics Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 changes: 37 additions & 0 deletions rig-postgres/README.md
Copy link
Contributor

Choose a reason for hiding this comment

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

I would also include basic instructions (esp. what a DATABASE_URL should be) and some links to install postgres.

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<div style="display: flex; align-items: center; justify-content: center;">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../img/rig_logo_dark.svg">
<source media="(prefers-color-scheme: light)" srcset="../img/rig_logo.svg">
<img src="../img/rig_logo.svg" width="200" alt="Rig logo">
</picture>
<span style="font-size: 48px; margin: 0 20px; font-weight: regular; font-family: Open Sans, sans-serif;"> + </span>
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://www.postgresql.org/media/img/about/press/elephant.png">
<source media="(prefers-color-scheme: light)" srcset="https://www.postgresql.org/media/img/about/press/elephant.png">
Copy link
Contributor

Choose a reason for hiding this comment

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

If it's the same logo for both, you prolly could just remove the media="(prefers-color-scheme: dark)" and just keep one <source>

<img src="https://www.postgresql.org/media/img/about/press/elephant.png" width="200" alt="SQLite logo">
</picture>
</div>

<br><br>

## Rig-postgres

This companion crate implements a Rig vector store based on PostgreSQL.

## Usage

Add the companion crate to your `Cargo.toml`, along with the rig-core crate:

```toml
[dependencies]
rig-core = "0.4.0"
rig-postgres = "0.1.0"
```

You can also run `cargo add rig-core rig-postgres` to add the most recent versions of the dependencies to your project.

See the [`/examples`](./examples) folder for usage examples.

## Important Note

The crate utilizes the [pgvector](https://github.com/pgvector/pgvector) PostgreSQL extension. It will automatically install it in your database if it's not yet present.
89 changes: 89 additions & 0 deletions rig-postgres/examples/vector_search_postgres.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
use rig::{
embeddings::EmbeddingsBuilder,
providers::openai::{Client, TEXT_EMBEDDING_3_SMALL},
vector_store::VectorStoreIndex,
Embed,
};
use rig_postgres::{Column, PostgresVectorIndex, PostgresVectorStore, PostgresVectorStoreTable};
use serde::Deserialize;
use tokio_postgres::types::ToSql;

#[derive(Clone, Debug, Deserialize, Embed)]
pub struct Document {
id: String,
#[embed]
content: String,
}

impl PostgresVectorStoreTable for Document {
fn name() -> &'static str {
"documents"
}

fn schema() -> Vec<Column> {
vec![
Column::new("id", "TEXT PRIMARY KEY"),
Column::new("content", "TEXT"),
]
}

fn column_values(&self) -> Vec<(&'static str, Box<dyn ToSql + Sync>)> {
vec![
("id", Box::new(self.id.clone())),
("content", Box::new(self.content.clone())),
]
}
}

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
// tracing_subscriber::fmt().with_env_filter(
// tracing_subscriber::EnvFilter::from_default_env()
// .add_directive(tracing::Level::DEBUG.into())
// .add_directive("hyper=off".parse().unwrap())
// ).init();
Copy link
Contributor

Choose a reason for hiding this comment

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

I would either leave this out or add this snippet back to the example!


// set up postgres connection
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL not set");
let db_config: tokio_postgres::Config = database_url.parse()?;
let (psql, connection) = db_config.connect(tokio_postgres::NoTls).await?;

tokio::spawn(async move {
if let Err(e) = connection.await {
tracing::error!("Connection error: {}", e);
}
});
Copy link
Contributor

Choose a reason for hiding this comment

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

In this example, why are you spawning a task for connecting, why can't you just await the connection directly?


// set up embedding model
let openai_api_key = std::env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY not set");
let openai = Client::new(&openai_api_key);
let model = openai.embedding_model(TEXT_EMBEDDING_3_SMALL);

// generate embeddings
let documents: Vec<Document> = vec![
"The Mediterranean diet emphasizes fish, olive oil, and vegetables, believed to reduce chronic diseases.",
"Photosynthesis in plants converts light energy into glucose and produces essential oxygen.",
"20th-century innovations, from radios to smartphones, centered on electronic advancements.",
].into_iter().map(|content| Document {
id: uuid::Uuid::new_v4().to_string(),
content: content.to_string(),
}).collect();
let embeddings = EmbeddingsBuilder::new(model.clone())
.documents(documents)?
.build()
.await?;

// add embeddings to store
let store = PostgresVectorStore::new(psql, &model).await?;
store.add_rows(embeddings).await?;

// query the index
let index = PostgresVectorIndex::new(model, store);
let results = index.top_n::<Document>("What is photosynthesis", 1).await?;
println!("top_n results: \n{:?}", results);

let ids = index.top_n_ids("What is photosynthesis?", 1).await?;
println!("top_n_ids results:\n{:?}", ids);

Ok(())
}
Loading
Loading