-
-
Notifications
You must be signed in to change notification settings - Fork 239
Add sqlite-vec support #906
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
Open
CarlQLange
wants to merge
5
commits into
patterns-ai-core:main
Choose a base branch
from
CarlQLange:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
cfad22e
Add sqlite-vec support
CarlQLange c482cea
Small fixes to the example script
CarlQLange 6818dd1
honestly, not sure what these changes are but they appear to be needed.
CarlQLange 93497e6
Merge branch 'main' into main
andreibondarev 6da185d
Merge branch 'main' into main
andreibondarev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
require "langchain" | ||
|
||
# Initialize the LLM (using Ollama in this example) | ||
llm = Langchain::LLM::Ollama.new | ||
|
||
# Initialize the SQLite-vec vectorstore | ||
db = Langchain::Vectorsearch::SqliteVec.new( | ||
url: ":memory:", # Use a file-based DB by passing a path or ":memory:" for in-memory | ||
index_name: "documents", | ||
namespace: "test", | ||
llm: llm | ||
) | ||
|
||
# Create the schema | ||
db.create_default_schema | ||
|
||
# Add some sample texts | ||
texts = [ | ||
"Ruby is a dynamic, open source programming language with a focus on simplicity and productivity.", | ||
"Python is a programming language that lets you work quickly and integrate systems more effectively.", | ||
"JavaScript is a lightweight, interpreted programming language with first-class functions.", | ||
"Rust is a multi-paradigm, general-purpose programming language designed for performance and safety." | ||
] | ||
|
||
puts "Adding texts..." | ||
ids = db.add_texts(texts: texts) | ||
puts "Added #{ids.size} texts with IDs: #{ids.join(", ")}" | ||
|
||
# Search for similar texts | ||
query = "What programming language is focused on memory safety?" | ||
puts "\nSearching for: #{query}" | ||
results = db.similarity_search(query: query) | ||
|
||
puts "\nResults:" | ||
results.each do |result| | ||
puts "- #{result[1]}" | ||
end | ||
|
||
# Ask a question | ||
question = "Which programming language emphasizes simplicity?" | ||
puts "\nAsking: #{question}" | ||
response = db.ask(question: question) | ||
puts "Answer: #{response.chat_completion}" | ||
|
||
# Clean up | ||
db.destroy_default_schema |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,154 @@ | ||
# frozen_string_literal: true | ||
|
||
require "sqlite_vec" | ||
module Langchain::Vectorsearch | ||
class SqliteVec < Base | ||
# | ||
# The SQLite vector search adapter using sqlite-vec | ||
# | ||
# Gem requirements: | ||
# gem "sqlite3", "~> 2.5" | ||
# gem "sqlite_vec", "~> 0.16.0" | ||
# | ||
# Usage: | ||
# sqlite_vec = Langchain::Vectorsearch::SqliteVec.new(url:, index_name:, llm:, namespace: nil) | ||
# | ||
|
||
attr_reader :db, :table_name, :namespace_column, :namespace | ||
|
||
# @param url [String] The path to the SQLite database file (or :memory: for in-memory) | ||
# @param index_name [String] The name of the table to use for the index | ||
# @param llm [Object] The LLM client to use | ||
# @param namespace [String] The namespace to use for the index when inserting/querying | ||
def initialize(url:, index_name:, llm:, namespace: nil) | ||
depends_on "sqlite3" | ||
depends_on "sqlite_vec" | ||
|
||
@db = SQLite3::Database.new(url) | ||
@db.enable_load_extension(true) | ||
::SqliteVec.load(@db) | ||
@db.enable_load_extension(false) | ||
|
||
@table_name = index_name | ||
@namespace_column = "namespace" | ||
@namespace = namespace | ||
|
||
super(llm: llm) | ||
end | ||
|
||
# Create default schema | ||
def create_default_schema | ||
@db.execute("CREATE VIRTUAL TABLE IF NOT EXISTS #{table_name} USING vec0( | ||
embedding float[#{llm.default_dimensions}], | ||
content TEXT, | ||
#{namespace_column} TEXT | ||
)") | ||
end | ||
|
||
# Destroy default schema | ||
def destroy_default_schema | ||
@db.execute("DROP TABLE IF EXISTS #{table_name}") | ||
end | ||
|
||
# Add a list of texts to the index | ||
# @param texts [Array<String>] The texts to add to the index | ||
# @param ids [Array<String>] The ids to add to the index, in the same order as the texts | ||
# @return [Array<Integer>] The ids of the added texts | ||
def add_texts(texts:, ids: nil) | ||
if ids.nil? || ids.empty? | ||
max_rowid = @db.execute("SELECT MAX(rowid) FROM #{table_name}").first.first || 0 | ||
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. Doesn't the |
||
ids = texts.map.with_index do |_, i| | ||
max_rowid + i + 1 | ||
end | ||
end | ||
|
||
@db.transaction do | ||
texts.zip(ids).each do |text, id| | ||
embedding = llm.embed(text: text).embedding | ||
@db.execute( | ||
"INSERT INTO #{table_name}(rowid, content, embedding, #{namespace_column}) VALUES (?, ?, ?, ?)", | ||
[id, text, embedding.pack("f*"), namespace] | ||
) | ||
end | ||
end | ||
|
||
ids | ||
end | ||
|
||
# Update a list of ids and corresponding texts in the index | ||
# @param texts [Array<String>] The texts to update in the index | ||
# @param ids [Array<String>] The ids to update in the index, in the same order as the texts | ||
# @return [Array<Integer>] The ids of the updated texts | ||
def update_texts(texts:, ids:) | ||
@db.transaction do | ||
texts.zip(ids).each do |text, id| | ||
embedding = llm.embed(text: text).embedding | ||
@db.execute( | ||
"UPDATE #{table_name} SET content = ?, embedding = ? WHERE rowid = ?", | ||
[text, embedding.pack("f*"), id] | ||
) | ||
end | ||
end | ||
ids | ||
end | ||
|
||
# Remove a list of texts from the index | ||
# @param ids [Array<Integer>] The ids of the texts to remove from the index | ||
# @return [Integer] The number of texts removed from the index | ||
def remove_texts(ids:) | ||
@db.execute("DELETE FROM #{table_name} WHERE rowid IN (#{ids.join(",")})") | ||
ids.length | ||
end | ||
|
||
# Search for similar texts in the index | ||
# @param query [String] The text to search for | ||
# @param k [Integer] The number of top results to return | ||
# @return [Array<Hash>] The results of the search | ||
def similarity_search(query:, k: 4) | ||
embedding = llm.embed(text: query).embedding | ||
similarity_search_by_vector(embedding: embedding, k: k) | ||
end | ||
|
||
# Search for similar texts in the index by vector | ||
# @param embedding [Array<Float>] The vector to search for | ||
# @param k [Integer] The number of top results to return | ||
# @return [Array<Hash>] The results of the search | ||
def similarity_search_by_vector(embedding:, k: 4) | ||
namespace_condition = namespace ? "AND #{namespace_column} = ?" : "" | ||
query_params = [embedding.pack("f*")] | ||
query_params << namespace if namespace | ||
|
||
@db.execute(<<-SQL, query_params) | ||
SELECT | ||
rowid, | ||
content, | ||
distance | ||
FROM #{table_name} | ||
WHERE embedding MATCH ? | ||
#{namespace_condition} | ||
ORDER BY distance | ||
LIMIT #{k} | ||
SQL | ||
end | ||
|
||
# Ask a question and return the answer | ||
# @param question [String] The question to ask | ||
# @param k [Integer] The number of results to have in context | ||
# @yield [String] Stream responses back one String at a time | ||
# @return [String] The answer to the question | ||
def ask(question:, k: 4, &) | ||
search_results = similarity_search(query: question, k: k) | ||
|
||
context = search_results.map { |result| result[1].to_s } | ||
context = context.join("\n---\n") | ||
|
||
prompt = generate_rag_prompt(question: question, context: context) | ||
|
||
messages = [{role: "user", content: prompt}] | ||
response = llm.chat(messages: messages, &) | ||
|
||
response.context = context | ||
response | ||
end | ||
end | ||
end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
@CarlQLange Why is this if/else statement needed? Isn't the gem version what gets required?
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.
Woof, I have no memory of this. I think it was something to do with using the gem locally from something else. Sorry, I pretty much have no idea what I was doing back then!