Solution published to Gitea.: update main.py
This commit is contained in:
@@ -8,7 +8,8 @@ from langchain_core.documents import Document
|
|||||||
from langchain_core.tools import tool
|
from langchain_core.tools import tool
|
||||||
from langchain_ollama import ChatOllama, OllamaEmbeddings
|
from langchain_ollama import ChatOllama, OllamaEmbeddings
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
from chromadb import Client
|
from langchain_qdrant import QdrantVectorStore
|
||||||
|
from qdrant_client import QdrantClient
|
||||||
|
|
||||||
OLLAMA_CHAT_MODEL = os.getenv("OLLAMA_CHAT_MODEL", "llama3")
|
OLLAMA_CHAT_MODEL = os.getenv("OLLAMA_CHAT_MODEL", "llama3")
|
||||||
OLLAMA_EMBED_MODEL = os.getenv("OLLAMA_EMBED_MODEL", "nomic-embed-text")
|
OLLAMA_EMBED_MODEL = os.getenv("OLLAMA_EMBED_MODEL", "nomic-embed-text")
|
||||||
@@ -21,11 +22,14 @@ def get_embeddings() -> OllamaEmbeddings:
|
|||||||
|
|
||||||
|
|
||||||
@lru_cache(maxsize=1)
|
@lru_cache(maxsize=1)
|
||||||
def get_vector_store() -> Client:
|
def get_vector_store() -> QdrantVectorStore:
|
||||||
client = Client()
|
client = QdrantClient()
|
||||||
# Ensure collection exists
|
# Ensure collection exists
|
||||||
client.get_or_create_collection(name="rag_memory")
|
client.recreate_collection(
|
||||||
return client
|
collection_name="rag_memory",
|
||||||
|
vectors_config={"size": EMBEDDING_SIZE, "distance": "cosine"},
|
||||||
|
)
|
||||||
|
return QdrantVectorStore(client=client, collection_name="rag_memory")
|
||||||
|
|
||||||
|
|
||||||
def chunk_document(content: str, title: str) -> list[Document]:
|
def chunk_document(content: str, title: str) -> list[Document]:
|
||||||
@@ -35,32 +39,28 @@ def chunk_document(content: str, title: str) -> list[Document]:
|
|||||||
|
|
||||||
@tool
|
@tool
|
||||||
def search_knowledge_base(query: str, max_results: int = 3) -> str:
|
def search_knowledge_base(query: str, max_results: int = 3) -> str:
|
||||||
"""Search relevant chunks in the local ChromaDB knowledge base."""
|
"""Search relevant chunks in the local Qdrant knowledge base."""
|
||||||
client = get_vector_store()
|
vector_store = get_vector_store()
|
||||||
collection = client.get_collection(name="rag_memory")
|
results = vector_store.similarity_search_with_score(query, k=max_results)
|
||||||
results = collection.query(query_texts=[query], n_results=max_results)
|
if not results:
|
||||||
if not results.get("documents"):
|
|
||||||
return "No relevant documents found."
|
return "No relevant documents found."
|
||||||
|
|
||||||
lines: list[str] = []
|
lines: list[str] = []
|
||||||
for idx, (doc, dist) in enumerate(zip(results["documents"], results["distances"]), start=1):
|
for idx, (doc, score) in enumerate(results, start=1):
|
||||||
ids = results["ids"]
|
title = doc.metadata.get("title", "untitled") if doc.metadata else "untitled"
|
||||||
metadata = collection.get(ids=[ids[idx-1]])["metadatas"][0]
|
snippet = doc.page_content.replace("\n", " ")[:300]
|
||||||
title = metadata.get("title", "untitled") if metadata else "untitled"
|
lines.append(f"{idx}. {title} (score={score:.4f}): {snippet}")
|
||||||
snippet = doc.replace("\n", " ")[:300]
|
|
||||||
lines.append(f"{idx}. {title} (score={dist:.4f}): {snippet}")
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
@tool
|
@tool
|
||||||
def add_to_knowledge_base(content: str, title: str) -> str:
|
def add_to_knowledge_base(content: str, title: str) -> str:
|
||||||
"""Split content into chunks and store it in the local ChromaDB knowledge base."""
|
"""Split content into chunks and store it in the local Qdrant knowledge base."""
|
||||||
documents = chunk_document(content, title)
|
documents = chunk_document(content, title)
|
||||||
ids = [str(uuid4()) for _ in documents]
|
ids = [str(uuid4()) for _ in documents]
|
||||||
embeddings = get_embeddings().embed_documents([doc.page_content for doc in documents])
|
embeddings = get_embeddings().embed_documents([doc.page_content for doc in documents])
|
||||||
client = get_vector_store()
|
vector_store = get_vector_store()
|
||||||
collection = client.get_collection(name="rag_memory")
|
vector_store.add_documents(documents, ids=ids, embeddings=embeddings)
|
||||||
collection.add(ids=ids, documents=[doc.page_content for doc in documents], embeddings=embeddings, metadatas=[doc.metadata for doc in documents])
|
|
||||||
return f"Added {len(documents)} chunk(s) from '{title}' to the knowledge base."
|
return f"Added {len(documents)} chunk(s) from '{title}' to the knowledge base."
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user