day1demo / services /embedding.py
sg-altis's picture
add initial unit and integration tests, makefile, and more codebase guidelines
9b32d94
Raw History Blame Contribute Delete
3.15 kB
from abc import ABC, abstractmethod
from llama_index.core import Settings, VectorStoreIndex
from llama_index.core.node_parser import SentenceSplitter
from llama_index.embeddings.openai import OpenAIEmbedding
from models.internal import Document, RAGChunkDoc
class DocumentEmbeddingService(ABC):
@abstractmethod
def embed_documents(self, documents: list[Document]) -> None:
pass
@abstractmethod
def retrieve_documents(
self,
query: str,
extra_queries: list[str] | None = None,
top_k: int = 8,
) -> list[RAGChunkDoc]:
pass
class LlamaIndexEmbeddingService(DocumentEmbeddingService):
def __init__(self, chunk_size: int = 900, chunk_overlap: int = 100):
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.index: VectorStoreIndex | None = None
# Configure the embedding model
Settings.embed_model = OpenAIEmbedding(model="text-embedding-3-small")
def embed_documents(self, documents: list[Document]) -> None:
print("[embedding service] creating embeddings")
llama_docs = [doc.to_llama_index_document() for doc in documents if doc.content is not None]
splitter = SentenceSplitter(
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
)
self.index = VectorStoreIndex.from_documents(
llama_docs,
transformations=[splitter],
)
print("[embedding service] finished creating embeddings")
def retrieve_documents(
self,
query: str,
extra_queries: list[str] | None = None,
top_k: int = 8,
) -> list[RAGChunkDoc]:
if self.index is None:
raise ValueError("No documents have been embedded yet. Call embed_documents first.")
retriever = self.index.as_retriever(similarity_top_k=top_k)
queries = [query] + (extra_queries or [])
seen = set()
out: list[RAGChunkDoc] = []
cit_i = 1
for q in queries:
print(f"[embedding service] retrieving documents for query: {q[:50]}...")
nodes = retriever.retrieve(q)
print("[embedding service] retrieval complete")
for nws in nodes:
node = nws.node
md = node.metadata or {}
source_id = md.get("document_id", "")
source_name = md.get("document_name", "unknown")
source_type = md.get("source_type", "unknown")
# Build a unique key to avoid duplicates
unique_key = f"{source_id}:{node.hash}"
if unique_key in seen:
continue
seen.add(unique_key)
chunk_doc = RAGChunkDoc(
citation_id=f"cit_{cit_i}",
source_id=source_id,
source_name=source_name,
source_type=source_type,
source_position=f"chunk_{cit_i}",
text=node.text,
)
out.append(chunk_doc)
cit_i += 1
return out