-
Notifications
You must be signed in to change notification settings - Fork 713
feat: postgresql store #157
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| 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.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" | ||
|
|
||
| [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,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="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. | ||
|
|
||
| ## 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. | ||
|
Contributor
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 my testing, I had to go an add the
Author
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. Huh, curious. You mean by brew installing it separately or something like that? In any case, I guess the confusing term here in the README is "installed" - what I meant is that the crate will run |
||
|
|
||
| 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. | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,83 @@ | ||
| 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> { | ||
| // 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); | ||
| } | ||
| }); | ||
milancermak marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // 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(()) | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.