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 #208

Closed
wants to merge 5 commits into from
Closed
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
909 changes: 510 additions & 399 deletions Cargo.lock

Large diffs are not rendered by default.

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
23 changes: 23 additions & 0 deletions rig-postgres/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
[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.6.0", features = ["derive"] }
serde = { version = "1.0.215", features = ["derive"] }
serde_json = "1.0.133"
tokio-postgres = "0.7.12"
tracing = "0.1.40"
dotenvy = "0.15.7"

[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.
36 changes: 36 additions & 0 deletions rig-postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<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 srcset="https://www.postgresql.org/media/img/about/press/elephant.png">
<img src="https://www.postgresql.org/media/img/about/press/elephant.png" width="200" alt="Postgres 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.

## PostgreSQL usage

The crate utilizes the [pgvector](https://github.com/pgvector/pgvector) extension, which is available for PostgreSQL version 13 and later. Use any of the [official](https://www.postgresql.org/download/) or alternative methods to install psql. The `pgvector` extension will be automatically installed by the crate if it's not present yet.

The crate relies on [`tokio-postgres`](https://docs.rs/tokio-postgres/latest/tokio_postgres/index.html) to manage its communication with the database. You can connect to a DB using any of the [supported methods](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING). See the [`/examples`](./examples) folder for usage examples.
86 changes: 86 additions & 0 deletions rig-postgres/examples/vector_search_postgres.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
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> {
// use dotvenv to load environment variables
dotenvy::dotenv().ok();

// 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);
}
});

// 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