feat: solution for 6a02e23da6fe2e4ac16acf65
This commit is contained in:
@@ -18,75 +18,58 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Embeddings ----------
|
# ---------- Vector Store ----------
|
||||||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
|
||||||
|
|
||||||
# ---------- Qdrant ----------
|
|
||||||
client = QdrantClient(":memory:")
|
client = QdrantClient(":memory:")
|
||||||
collection_name = "knowledge_base"
|
|
||||||
|
|
||||||
try:
|
|
||||||
client.get_collection(collection_name)
|
|
||||||
except Exception:
|
|
||||||
# Use a typical embedding size for nomic-embed-text (768)
|
|
||||||
client.create_collection(
|
client.create_collection(
|
||||||
collection_name=collection_name,
|
collection_name="knowledge_base",
|
||||||
vectors_config=VectorParams(size=768, distance=Distance.COSINE),
|
vectors_config=VectorParams(size=1024, distance=Distance.COSINE),
|
||||||
)
|
)
|
||||||
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||||||
vector_store = QdrantVectorStore(
|
vector_store = QdrantVectorStore(
|
||||||
client=client,
|
client=client,
|
||||||
collection_name=collection_name,
|
collection_name="knowledge_base",
|
||||||
embedding=embeddings,
|
embedding=embeddings,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Text splitter ----------
|
# ---------- Text Splitter ----------
|
||||||
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
||||||
|
|
||||||
# ---------- Tools ----------
|
# ---------- Tools ----------
|
||||||
@tool
|
@tool
|
||||||
def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
def add_to_knowledge_base(content: str, title: str) -> str:
|
||||||
"""Search the knowledge base for relevant documents."""
|
"""Add a document to the knowledge base."""
|
||||||
docs_with_score = vector_store.similarity_search_with_score(query, k=max_results)
|
docs = splitter.split_text(content)
|
||||||
if not docs_with_score:
|
documents = [Document(page_content=c, metadata={"title": title}) for c in docs]
|
||||||
return "No results found."
|
vector_store.add_documents(documents)
|
||||||
return "\n".join(
|
return f"Added {len(docs)} chunks under title '{title}'."
|
||||||
f"{i+1}. {doc.page_content[:200]}..."
|
|
||||||
for i, (doc, _) in enumerate(docs_with_score)
|
|
||||||
)
|
|
||||||
|
|
||||||
@tool
|
@tool
|
||||||
def add_to_knowledge_base(content: str, title: str = "") -> str:
|
def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
||||||
"""Add a new document to the knowledge base."""
|
"""Search the knowledge base for relevant information."""
|
||||||
chunks = splitter.split_text(content)
|
results = vector_store.similarity_search_with_score(query, k=max_results)
|
||||||
docs = [Document(page_content=c, metadata={"title": title}) for c in chunks]
|
if not results:
|
||||||
vector_store.add_documents(docs)
|
return "No relevant documents found."
|
||||||
return f"Added {len(chunks)} chunks under title '{title}'."
|
out_lines = []
|
||||||
|
for doc, score in results:
|
||||||
|
title = doc.metadata.get("title", "Untitled")
|
||||||
|
out_lines.append(f"[{score:.2f}] {title}: {doc.page_content[:200]}...")
|
||||||
|
return "\n".join(out_lines)
|
||||||
|
|
||||||
# ---------- Agent ----------
|
# ---------- Agent ----------
|
||||||
system_prompt = """
|
system_prompt = """
|
||||||
You are an assistant that can search and add information to a knowledge base.
|
You are an assistant with access to a knowledge base.
|
||||||
Use the tools `search_knowledge_base` and `add_to_knowledge_base` as needed.
|
Use the tools `add_to_knowledge_base` and `search_knowledge_base` as needed.
|
||||||
|
Respond concisely. If you need more info, ask the user.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
agent = create_agent(
|
agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[search_knowledge_base, add_to_knowledge_base],
|
tools=[add_to_knowledge_base, search_knowledge_base],
|
||||||
system_prompt=system_prompt,
|
system_prompt=system_prompt,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- CLI ----------
|
# ---------- CLI ----------
|
||||||
def load_directory(path: str):
|
|
||||||
"""Load all text files from a directory into the knowledge base."""
|
|
||||||
for root, _, files in os.walk(path):
|
|
||||||
for file in files:
|
|
||||||
if file.lower().endswith(".txt"):
|
|
||||||
with open(os.path.join(root, file), encoding="utf-8") as f:
|
|
||||||
content = f.read()
|
|
||||||
add_to_knowledge_base(content=content, title=file)
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("Welcome to the RAG agent. Commands: /add <file>, /search <query>, /load <dir>, /quit")
|
print("RAG Agent CLI. Commands: /add <title> <content>, /search <query>, /quit")
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
inp = input("> ").strip()
|
inp = input("> ").strip()
|
||||||
@@ -94,29 +77,29 @@ def main():
|
|||||||
break
|
break
|
||||||
if not inp:
|
if not inp:
|
||||||
continue
|
continue
|
||||||
if inp.lower() in ("/quit", "exit"):
|
if inp.lower() in ("exit", "quit", "/quit"):
|
||||||
print("Goodbye!")
|
print("Bye!")
|
||||||
break
|
break
|
||||||
if inp.startswith("/add "):
|
if inp.startswith("/add "):
|
||||||
_, file_path = inp.split(maxsplit=1)
|
parts = inp[5:].split(None, 1)
|
||||||
try:
|
if len(parts) != 2:
|
||||||
with open(file_path, encoding="utf-8") as f:
|
print("Usage: /add <title> <content>")
|
||||||
content = f.read()
|
continue
|
||||||
print(add_to_knowledge_base(content=content, title=os.path.basename(file_path)))
|
title, content = parts
|
||||||
except Exception as e:
|
res = add_to_knowledge_base(content=content, title=title)
|
||||||
print(f"Error adding file: {e}")
|
print(res)
|
||||||
elif inp.startswith("/search "):
|
elif inp.startswith("/search "):
|
||||||
_, query = inp.split(maxsplit=1)
|
query = inp[8:].strip()
|
||||||
print(search_knowledge_base(query=query))
|
if not query:
|
||||||
elif inp.startswith("/load "):
|
print("Usage: /search <query>")
|
||||||
_, dir_path = inp.split(maxsplit=1)
|
continue
|
||||||
load_directory(dir_path)
|
res = search_knowledge_base(query=query, max_results=5)
|
||||||
print(f"Loaded documents from {dir_path}")
|
print(res)
|
||||||
else:
|
else:
|
||||||
# Regular conversation
|
# Regular chat with agent
|
||||||
response = agent.invoke({"messages": [{"role": "human", "content": inp}]})
|
result = agent.invoke({"messages": [{"role": "human", "content": inp}]})
|
||||||
msg = response["messages"][-1]
|
ai_msg = result["messages"][-1]
|
||||||
print(msg.content)
|
print(ai_msg.content)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user