-
-
Notifications
You must be signed in to change notification settings - Fork 19
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
Implement embeddings for use with LLM agents #680
Open
ahuang11
wants to merge
3
commits into
main
Choose a base branch
from
use_duckdb_embedding
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 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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 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 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 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 |
---|---|---|
@@ -1,33 +1,136 @@ | ||
import os | ||
|
||
from pathlib import Path | ||
|
||
from .config import DEFAULT_EMBEDDINGS_PATH | ||
import duckdb | ||
|
||
DEFAULT_EMBEDDINGS_PATH = Path("embeddings") | ||
|
||
|
||
class Embeddings: | ||
def __init__(self, database_path: str = ":memory:"): | ||
self.database_path = database_path | ||
self.connection = duckdb.connect(database_path) | ||
self.setup_database() | ||
|
||
def add_directory(self, data_dir: Path): | ||
raise NotImplementedError | ||
def setup_database(self): | ||
self.connection.execute( | ||
""" | ||
INSTALL vss; | ||
LOAD vss; | ||
CREATE TABLE document_data ( | ||
id INTEGER, | ||
text VARCHAR, | ||
embedding FLOAT[1536], | ||
table_name VARCHAR | ||
); | ||
CREATE INDEX embedding_index ON document_data USING HNSW (embedding) WITH (metric = 'cosine'); | ||
""" | ||
) | ||
|
||
@classmethod | ||
def from_directory( | ||
cls, | ||
data_dir: Path, | ||
file_type: str = "json", | ||
database_path: str = ":memory:", | ||
table_name: str = "default", | ||
): | ||
embeddings = cls(database_path) | ||
for i, path in enumerate(data_dir.glob(f"**/*.{file_type}")): | ||
text = path.read_text() | ||
embedding = embeddings.get_embedding(text) | ||
embeddings.connection.execute( | ||
""" | ||
INSERT INTO document_data (id, text, embedding, table_name) | ||
VALUES (?, ?, ?, ?); | ||
""", | ||
[i, text, embedding, table_name], | ||
) | ||
return embeddings | ||
|
||
@classmethod | ||
def from_dict(cls, data: dict, database_path: str = ":memory:"): | ||
embeddings = cls(database_path) | ||
global_id = 0 | ||
for table_name, texts in data.items(): | ||
for text in texts: | ||
embedding = embeddings.get_embedding(text) | ||
embeddings.connection.execute( | ||
""" | ||
INSERT INTO document_data (id, text, embedding, table_name) | ||
VALUES (?, ?, ?, ?); | ||
""", | ||
[global_id, text, embedding, table_name], | ||
) | ||
global_id += 1 | ||
return embeddings | ||
|
||
def query(self, query_texts: str) -> list: | ||
def get_embedding(self, text: str) -> list: | ||
raise NotImplementedError | ||
|
||
def get_text_chunks( | ||
self, text: str, chunk_size: int = 512, overlap: int = 50 | ||
) -> list: | ||
words = text.split() | ||
chunks = [] | ||
for i in range(0, len(words), chunk_size - overlap): | ||
chunk = " ".join(words[i : i + chunk_size]) | ||
chunks.append(chunk) | ||
return chunks | ||
|
||
class ChromaDb(Embeddings): | ||
def get_combined_embedding(self, text: str) -> list: | ||
chunks = self.get_text_chunks(text) | ||
embeddings = [self.get_embedding(chunk) for chunk in chunks] | ||
combined_embedding = [sum(x) / len(x) for x in zip(*embeddings)] | ||
return combined_embedding | ||
|
||
def __init__(self, collection: str, persist_dir: str = DEFAULT_EMBEDDINGS_PATH): | ||
import chromadb | ||
self.client = chromadb.PersistentClient(path=str(persist_dir / collection)) | ||
self.collection = self.client.get_or_create_collection(collection) | ||
def query(self, query_text: str, top_k: int = 1, table_name: str | None = None) -> list: | ||
print(query_text, "QUERY") | ||
query_embedding = self.get_combined_embedding(query_text) | ||
|
||
def add_directory(self, data_dir: Path, file_type='json'): | ||
add_kwargs = { | ||
"ids": [], | ||
"documents": [], | ||
} | ||
for i, path in enumerate(data_dir.glob(f"**/*.{file_type}")): | ||
add_kwargs["ids"].append(f"{i}") | ||
add_kwargs["documents"].append(path.read_text()) | ||
self.collection.add(**add_kwargs) | ||
if table_name: | ||
result = self.connection.execute( | ||
""" | ||
SELECT id, text, array_cosine_similarity(embedding, ?::FLOAT[1536]) AS similarity, table_name | ||
FROM document_data | ||
WHERE table_name = ? | ||
ORDER BY similarity DESC | ||
LIMIT ?; | ||
""", | ||
[query_embedding, table_name, top_k], | ||
).fetchall() | ||
else: | ||
result = self.connection.execute( | ||
""" | ||
SELECT id, text, array_cosine_similarity(embedding, ?::FLOAT[1536]) AS similarity, table_name | ||
FROM document_data | ||
ORDER BY similarity DESC | ||
LIMIT ?; | ||
""", | ||
[query_embedding, top_k], | ||
).fetchall() | ||
|
||
return result | ||
|
||
def close(self): | ||
self.connection.close() | ||
|
||
|
||
class OpenAIEmbeddings(Embeddings): | ||
def __init__( | ||
self, database_path: str = ":memory:", model: str = "text-embedding-3-small" | ||
): | ||
super().__init__(database_path) | ||
self.model = model | ||
|
||
def get_embedding(self, text: str) -> list: | ||
from openai import OpenAI | ||
|
||
def query(self, query_texts: str) -> list: | ||
return self.collection.query(query_texts=query_texts)["documents"] | ||
text = text.replace("\n", " ") | ||
return ( | ||
OpenAI(api_key=os.getenv("OPENAI_API_KEY")) | ||
.embeddings.create(input=[text], model=self.model) | ||
.data[0] | ||
.embedding | ||
) |
Binary file not shown.
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.
Another TODO: handle ephemeral tables