fix(needs_fixes): 3 исправлений, 0 отстояно — main.py

This commit is contained in:
+60 -99
View File
@@ -1,36 +1,16 @@
"""
# main.py RAGagent with Qdrant, OpenRouter, and deepagents
# ----------------------------------------------------------
# 1. Imports and configuration
# 2. Qdrant vector store wrapper (embedding, add, search)
# 3. Text splitter (RecursiveCharacterTextSplitter)
# 4. LangChain tools: search_knowledge_base, add_to_knowledge_base
# 5. DeepAgent creation (create_deep_agent)
# 6. CLI client for /add, /search, /quit
# ----------------------------------------------------------
"""
import os import os
import asyncio import asyncio
import json
from pathlib import Path from pathlib import Path
from typing import List from langchain_openai import ChatOpenAI
from langchain_ollama import OllamaEmbeddings
from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain_qdrant import QdrantVectorStore
from langchain_core.documents import Document from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
from langchain_qdrant import QdrantVectorStore from langchain_core.messages import HumanMessage
# ------------------------------------------------------------------ # ---------- LLM ----------
# 1. Configuration
# ------------------------------------------------------------------
# Load environment variables (e.g. OPENAI_API_KEY)
from dotenv import load_dotenv
load_dotenv()
# LLM OpenRouter (free tier)
llm = ChatOpenAI( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1",
@@ -38,110 +18,91 @@ llm = ChatOpenAI(
temperature=0.0, temperature=0.0,
) )
# Embeddings OpenAI via OpenRouter # ---------- Embeddings ----------
embeddings = OpenAIEmbeddings( # Using Ollama embeddings as per assignment correction
model="text-embedding-3-small", embeddings = OllamaEmbeddings(model="nomic-embed-text")
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
)
# Qdrant client assumes Qdrant is running locally on default port # ---------- Vector Store (Qdrant) ----------
qdrant_url = os.getenv("QDRANT_URL", "http://localhost:6333") # Ensure Qdrant is running locally (default port 6333)
collection_name = "knowledge_base"
vector_store = QdrantVectorStore( vector_store = QdrantVectorStore(
url=qdrant_url, url="http://localhost:6333",
collection_name=collection_name, collection_name="knowledge",
embeddings=embeddings, embedding_function=embeddings,
) )
# Text splitter 1000 chars max, 200 overlap # ---------- Tools ----------
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
# ------------------------------------------------------------------
# 2. Tools
# ------------------------------------------------------------------
@tool @tool
def search_knowledge_base(query: str, max_results: int = 3) -> str: def search_knowledge_base(query: str, max_results: int = 3) -> str:
"""Semantic search in the Qdrant knowledge base.""" """Semantic search in the knowledge base."""
docs: List[Document] = vector_store.similarity_search(query, k=max_results) docs = vector_store.similarity_search(query, k=max_results)
if not docs: if not docs:
return "No relevant documents found." return "No results found."
return "\n\n---\n\n".join([f"{doc.metadata.get('title', 'Untitled')}:\n{doc.page_content}" for doc in docs]) return "\n---\n".join(f"{i+1}. {doc.page_content[:200]}..." for i, doc in enumerate(docs))
@tool @tool
def add_to_knowledge_base(content: str, title: str = "Untitled") -> str: def add_to_knowledge_base(content: str, title: str = "untitled") -> str:
"""Add a new document to the knowledge base. """Add a document to the knowledge base."""
The content is split into chunks before being stored. doc = Document(page_content=content, metadata={"title": title})
""" vector_store.add_documents([doc])
chunks = text_splitter.split_text(content) return f"Document '{title}' added to the knowledge base."
docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
vector_store.add_documents(docs)
return f"Added {len(docs)} chunks for document '{title}'."
# ------------------------------------------------------------------ # ---------- Backend ----------
# 3. DeepAgent setup
# ------------------------------------------------------------------
backend = CompositeBackend([ backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"), LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(), FilesystemBackend(),
]) ])
# ---------- Agent ----------
agent = create_deep_agent( agent = create_deep_agent(
model=llm, model=llm,
tools=[search_knowledge_base, add_to_knowledge_base], tools=[search_knowledge_base, add_to_knowledge_base],
backend=backend, backend=backend,
system_prompt="You are a helpful assistant with access to a knowledge base. Use the provided tools to search and add information.", system_prompt="You are an assistant with access to a knowledge base. Use the provided tools to search and add information."
) )
# ------------------------------------------------------------------ # ---------- Document Loader ----------
# 4. CLI client async def load_documents_from_dir(directory: str):
# ------------------------------------------------------------------ """Load all text files from a directory into the vector store."""
async def run_cli(): for file_path in Path(directory).rglob("*.txt"):
print("Welcome to the RAG Agent CLI. Commands: /add <title> <file>, /search <query>, /quit") text = file_path.read_text(encoding="utf-8")
thread_id = "cli-session" 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: while True:
try:
user_input = input("> ") user_input = input("> ")
except EOFError: if user_input.strip() == "/quit":
break
if not user_input:
continue
if user_input.startswith("/quit"):
print("Goodbye!") print("Goodbye!")
break break
if user_input.startswith("/add"): if user_input.startswith("/add "):
parts = user_input.split(maxsplit=2) parts = user_input.split(" ", 1)
if len(parts) < 3: title = parts[1] if len(parts) > 1 else "untitled"
print("Usage: /add <title> <file_path>") content = input("Enter content: ")
continue
title, file_path = parts[1], parts[2]
try:
content = Path(file_path).read_text(encoding="utf-8")
except Exception as e:
print(f"Error reading file: {e}")
continue
# Invoke tool directly
result = add_to_knowledge_base(content, title)
print(result)
continue
if user_input.startswith("/search"):
query = user_input[len("/search"):].strip()
if not query:
print("Usage: /search <query>")
continue
# Use agent to perform search via tool
response = await agent.ainvoke( response = await agent.ainvoke(
{"messages": [{"role": "user", "content": f"search {query}"}]}, {"messages": [HumanMessage(content=f"/add {title}")], "content": content},
{"configurable": {"thread_id": thread_id}}, {"configurable": {"thread_id": "session"}},
) )
print(response["messages"][-1].content) print(response["messages"][-1].content)
continue elif user_input.startswith("/search "):
# Default: treat as normal user message query = user_input.split(" ", 1)[1]
response = await agent.ainvoke( response = await agent.ainvoke(
{"messages": [{"role": "user", "content": user_input}]}, {"messages": [HumanMessage(content=f"/search {query}")]},
{"configurable": {"thread_id": thread_id}}, {"configurable": {"thread_id": "session"}},
) )
print(response["messages"][-1].content) 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__": if __name__ == "__main__":
asyncio.run(run_cli()) asyncio.run(main())