feat: solution for 6a02e23da6fe2e4ac16acf65
This commit is contained in:
@@ -11,10 +11,10 @@ from langchain_qdrant import QdrantVectorStore
|
|||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
from qdrant_client.http.models import Distance, VectorParams
|
from qdrant_client.http.models import Distance, VectorParams
|
||||||
# Text splitter
|
# Text splitter
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
||||||
# Agent
|
# Agent
|
||||||
from langchain.agents import create_agent
|
from langchain.agents import create_agent
|
||||||
# Document type
|
# Documents
|
||||||
from langchain_core.documents import Document
|
from langchain_core.documents import Document
|
||||||
|
|
||||||
# -------------------- 1. RAG tools --------------------
|
# -------------------- 1. RAG tools --------------------
|
||||||
@@ -26,7 +26,7 @@ def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
|||||||
return "No relevant documents found."
|
return "No relevant documents found."
|
||||||
response_lines = []
|
response_lines = []
|
||||||
for doc, score in results:
|
for doc, score in results:
|
||||||
title = doc.metadata.get("title", "Untitled")
|
title = doc.metadata.get("title", "N/A")
|
||||||
snippet = doc.page_content[:200] + ("..." if len(doc.page_content) > 200 else "")
|
snippet = doc.page_content[:200] + ("..." if len(doc.page_content) > 200 else "")
|
||||||
response_lines.append(f"Score: {score:.4f}\nTitle: {title}\nContent: {snippet}")
|
response_lines.append(f"Score: {score:.4f}\nTitle: {title}\nContent: {snippet}")
|
||||||
return "\n\n".join(response_lines)
|
return "\n\n".join(response_lines)
|
||||||
@@ -38,76 +38,92 @@ def add_to_knowledge_base(content: str, title: str) -> str:
|
|||||||
vector_store.add_documents([doc])
|
vector_store.add_documents([doc])
|
||||||
return f"Document '{title}' added successfully."
|
return f"Document '{title}' added successfully."
|
||||||
|
|
||||||
# -------------------- 2. Vector store setup --------------------
|
# -------------------- 2. Qdrant setup --------------------
|
||||||
client = QdrantClient(":memory:")
|
qdrant_client = QdrantClient(":memory:")
|
||||||
client.create_collection(
|
qdrant_client.create_collection(
|
||||||
collection_name="knowledge",
|
collection_name="knowledge_base",
|
||||||
vectors_config=VectorParams(size=384, distance=Distance.COSINE),
|
vectors_config=VectorParams(size=384, distance=Distance.COSINE),
|
||||||
)
|
)
|
||||||
|
|
||||||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||||||
vector_store = QdrantVectorStore(
|
vector_store = QdrantVectorStore(
|
||||||
client=client,
|
client=qdrant_client,
|
||||||
collection_name="knowledge",
|
collection_name="knowledge_base",
|
||||||
embedding=embeddings,
|
embedding=embeddings,
|
||||||
)
|
)
|
||||||
|
|
||||||
# -------------------- 3. Text splitter --------------------
|
# -------------------- 3. Text splitter --------------------
|
||||||
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
|
||||||
|
|
||||||
# -------------------- 4. Agent --------------------
|
def load_and_index(directory: str):
|
||||||
agent = create_agent(
|
"""Load all .txt files from directory and index them."""
|
||||||
model=ChatOllama(model="llama3", temperature=0.2),
|
docs: List[Document] = []
|
||||||
tools=[search_knowledge_base, add_to_knowledge_base],
|
for file_path in Path(directory).glob("*.txt"):
|
||||||
system_prompt="You are a helpful assistant that can search and add documents to the knowledge base.",
|
|
||||||
)
|
|
||||||
|
|
||||||
# -------------------- 5. Load docs from directory --------------------
|
|
||||||
def load_docs_from_dir(directory: str) -> List[Document]:
|
|
||||||
docs = []
|
|
||||||
for file_path in Path(directory).rglob("*.txt"):
|
|
||||||
text = file_path.read_text(encoding="utf-8")
|
text = file_path.read_text(encoding="utf-8")
|
||||||
chunks = splitter.split_text(text)
|
chunks = splitter.split_text(text)
|
||||||
for i, chunk in enumerate(chunks):
|
for i, chunk in enumerate(chunks):
|
||||||
docs.append(
|
docs.append(
|
||||||
Document(page_content=chunk, metadata={"title": f"{file_path.name} #{i+1}"})
|
Document(
|
||||||
|
page_content=chunk,
|
||||||
|
metadata={
|
||||||
|
"title": f"{file_path.stem} #{i+1}",
|
||||||
|
"source": str(file_path),
|
||||||
|
},
|
||||||
|
)
|
||||||
)
|
)
|
||||||
return docs
|
|
||||||
|
|
||||||
def init_knowledge_base(directory: str):
|
|
||||||
docs = load_docs_from_dir(directory)
|
|
||||||
vector_store.add_documents(docs)
|
vector_store.add_documents(docs)
|
||||||
|
|
||||||
# -------------------- 6. Interactive CLI --------------------
|
# -------------------- 4. Agent --------------------
|
||||||
|
system_prompt = """
|
||||||
|
You are an assistant that can search and add documents to a knowledge base.
|
||||||
|
Use the tools `search_knowledge_base` and `add_to_knowledge_base` as needed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
agent = create_agent(
|
||||||
|
model=ChatOllama(model="llama3", temperature=0.2),
|
||||||
|
tools=[search_knowledge_base, add_to_knowledge_base],
|
||||||
|
system_prompt=system_prompt,
|
||||||
|
)
|
||||||
|
|
||||||
|
# -------------------- 5. CLI client --------------------
|
||||||
def main():
|
def main():
|
||||||
print("Initializing knowledge base...")
|
# Load initial documents
|
||||||
init_knowledge_base("./docs") # replace with your docs folder
|
load_and_index("docs") # ensure a 'docs' folder with .txt files
|
||||||
print("Ready! Use /add, /search, or /quit.")
|
|
||||||
|
print(
|
||||||
|
"RAG Agent ready. Commands: /add <title> <content>, /search <query>, /quit"
|
||||||
|
)
|
||||||
while True:
|
while True:
|
||||||
user_input = input("> ").strip()
|
user_input = input("> ").strip()
|
||||||
if not user_input:
|
if not user_input:
|
||||||
continue
|
continue
|
||||||
if user_input.lower() == "/quit":
|
if user_input.lower() in ("exit", "quit", "/quit"):
|
||||||
break
|
break
|
||||||
|
|
||||||
if user_input.startswith("/add"):
|
if user_input.startswith("/add"):
|
||||||
try:
|
try:
|
||||||
_, title, content = user_input.split(" ", 2)
|
_, title, content = user_input.split(" ", 2)
|
||||||
result = add_to_knowledge_base(content=content, title=title)
|
result_msg = add_to_knowledge_base(content=content, title=title)
|
||||||
print(result)
|
print(result_msg)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
print("Usage: /add <title> <content>")
|
print("Usage: /add <title> <content>")
|
||||||
elif user_input.startswith("/search"):
|
elif user_input.startswith("/search"):
|
||||||
query = user_input[len("/search"):].strip()
|
query = user_input[len("/search") :].strip()
|
||||||
if not query:
|
if not query:
|
||||||
print("Provide a search query.")
|
print("Provide a search query.")
|
||||||
continue
|
continue
|
||||||
result = search_knowledge_base(query=query, max_results=3)
|
response = agent.invoke({"messages": [{"role": "human", "content": query}]})
|
||||||
print(result)
|
for msg in response["messages"]:
|
||||||
|
if hasattr(msg, "content"):
|
||||||
|
print(msg.content)
|
||||||
else:
|
else:
|
||||||
# Regular chat with agent
|
# Regular chat with the agent
|
||||||
response = agent.invoke({"messages": [{"role": "human", "content": user_input}]})
|
response = agent.invoke(
|
||||||
ai_msg = response["messages"][-1]
|
{"messages": [{"role": "human", "content": user_input}]}
|
||||||
print(ai_msg.content)
|
)
|
||||||
|
for msg in response["messages"]:
|
||||||
|
if hasattr(msg, "content"):
|
||||||
|
print(msg.content)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user