-
Notifications
You must be signed in to change notification settings - Fork 147
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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 |
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"] } |
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. |
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"> | ||
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. If it's the same logo for both, you prolly could just remove the |
||
<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. |
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(); | ||
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 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); | ||
} | ||
}); | ||
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. 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(()) | ||
} |
There was a problem hiding this comment.
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.