109 lines
3.9 KiB
Python
109 lines
3.9 KiB
Python
import os
|
|
import asyncio
|
|
from pathlib import Path
|
|
from langchain_openai import ChatOpenAI
|
|
from langchain_ollama import OllamaEmbeddings
|
|
from langchain_qdrant import QdrantVectorStore
|
|
from langchain_core.documents import Document
|
|
from langchain.tools import tool
|
|
from deepagents import create_deep_agent
|
|
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
|
from langchain_core.messages import HumanMessage
|
|
|
|
# ---------- LLM ----------
|
|
llm = ChatOpenAI(
|
|
model="openai/gpt-oss-20b:free",
|
|
base_url="https://openrouter.ai/api/v1",
|
|
api_key=os.getenv("OPENAI_API_KEY"),
|
|
temperature=0.0,
|
|
)
|
|
|
|
# ---------- Embeddings ----------
|
|
# Using Ollama embeddings as per assignment correction
|
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
|
|
|
# ---------- Vector Store (Qdrant) ----------
|
|
# Ensure Qdrant is running locally (default port 6333)
|
|
vector_store = QdrantVectorStore(
|
|
url="http://localhost:6333",
|
|
collection_name="knowledge",
|
|
embedding_function=embeddings,
|
|
)
|
|
|
|
# ---------- Tools ----------
|
|
@tool
|
|
def search_knowledge_base(query: str, max_results: int = 3) -> str:
|
|
"""Semantic search in the knowledge base."""
|
|
docs = vector_store.similarity_search(query, k=max_results)
|
|
if not docs:
|
|
return "No results found."
|
|
return "\n---\n".join(f"{i+1}. {doc.page_content[:200]}..." for i, doc in enumerate(docs))
|
|
|
|
@tool
|
|
def add_to_knowledge_base(content: str, title: str = "untitled") -> str:
|
|
"""Add a document to the knowledge base."""
|
|
doc = Document(page_content=content, metadata={"title": title})
|
|
vector_store.add_documents([doc])
|
|
return f"Document '{title}' added to the knowledge base."
|
|
|
|
# ---------- Backend ----------
|
|
backend = CompositeBackend([
|
|
LocalShellBackend(workspace_dir="./workspace"),
|
|
FilesystemBackend(),
|
|
])
|
|
|
|
# ---------- Agent ----------
|
|
agent = create_deep_agent(
|
|
model=llm,
|
|
tools=[search_knowledge_base, add_to_knowledge_base],
|
|
backend=backend,
|
|
system_prompt="You are an assistant with access to a knowledge base. Use the provided tools to search and add information."
|
|
)
|
|
|
|
# ---------- Document Loader ----------
|
|
async def load_documents_from_dir(directory: str):
|
|
"""Load all text files from a directory into the vector store."""
|
|
for file_path in Path(directory).rglob("*.txt"):
|
|
text = file_path.read_text(encoding="utf-8")
|
|
title = file_path.stem
|
|
await agent.ainvoke(
|
|
{"messages": [HumanMessage(content=f"/add {title}")], "content": text},
|
|
{"configurable": {"thread_id": "init"}},
|
|
)
|
|
|
|
# ---------- Interactive CLI ----------
|
|
async def interactive_loop():
|
|
print("Welcome to the RAG Agent. Commands: /add <title>, /search <query>, /quit")
|
|
while True:
|
|
user_input = input("> ")
|
|
if user_input.strip() == "/quit":
|
|
print("Goodbye!")
|
|
break
|
|
if user_input.startswith("/add "):
|
|
parts = user_input.split(" ", 1)
|
|
title = parts[1] if len(parts) > 1 else "untitled"
|
|
content = input("Enter content: ")
|
|
response = await agent.ainvoke(
|
|
{"messages": [HumanMessage(content=f"/add {title}")], "content": content},
|
|
{"configurable": {"thread_id": "session"}},
|
|
)
|
|
print(response["messages"][-1].content)
|
|
elif user_input.startswith("/search "):
|
|
query = user_input.split(" ", 1)[1]
|
|
response = await agent.ainvoke(
|
|
{"messages": [HumanMessage(content=f"/search {query}")]},
|
|
{"configurable": {"thread_id": "session"}},
|
|
)
|
|
print(response["messages"][-1].content)
|
|
else:
|
|
print("Unknown command. Use /add, /search, or /quit.")
|
|
|
|
# ---------- Main ----------
|
|
async def main():
|
|
# Optional: load initial documents
|
|
# await load_documents_from_dir("./data")
|
|
await interactive_loop()
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|