fix: main.py — Агент с RAG-памятью

This commit is contained in:
2026-07-02 09:48:59 +00:00
parent 68c6963604
commit a00049957b
+97 -38
View File
@@ -1,77 +1,136 @@
import asyncio
import os import os
import asyncio
from pathlib import Path from pathlib import Path
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_core.messages import HumanMessage from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_qdrant import QdrantVectorStore
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_core.messages import HumanMessage
from utils import llm, vector_store, splitter # Configuration
from langchain_core.documents import Document OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise RuntimeError("OPENAI_API_KEY not set in environment")
# LLM via OpenRouter
llm = ChatOpenAI(
model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1",
api_key=OPENAI_API_KEY,
temperature=0.0,
)
# Embeddings via OpenRouter
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
base_url="https://openrouter.ai/api/v1",
api_key=OPENAI_API_KEY,
)
# Qdrant client and vector store
from qdrant_client import QdrantClient
qdrant_client = QdrantClient(url="http://localhost:6333")
collection_name = "knowledge_base"
vector_store = QdrantVectorStore(
client=qdrant_client,
collection_name=collection_name,
embedding_function=embeddings,
)
# Text splitter
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
# Tool: search knowledge base
@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 the knowledge base for relevant information.""" """Search the knowledge base for relevant information."""
docs = vector_store.similarity_search(query, k=max_results) docs = vector_store.similarity_search(query, k=max_results)
return "\n".join(d.page_content for d in docs) if docs else "No results." if not docs:
return "No results found."
return "\n\n".join(f"Title: {doc.metadata.get('title', 'unknown')}\n{doc.page_content}" for doc in docs)
# Tool: add to knowledge base
@tool @tool
def add_to_knowledge_base(content: str, title: str = "doc") -> str: def add_to_knowledge_base(content: str, title: str = "document") -> str:
"""Add content to the knowledge base.""" """Add content to the knowledge base."""
chunks = splitter.split_text(content) chunks = splitter.split_text(content)
docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks] docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
vector_store.add_documents(docs) vector_store.add_documents(docs)
return f"Added {len(docs)} chunks for {title}." return f"Added {len(docs)} chunks from '{title}'."
# Backend for deepagents
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 a helpful knowledge assistant. Use the provided tools to search and add information.",
) )
async def main(): # Helper: load documents from a directory
print("RAG Agent CLI. Commands: /add, /search, /quit") def load_documents_from_dir(directory: str):
dir_path = Path(directory)
if not dir_path.is_dir():
raise ValueError(f"Directory {directory} does not exist.")
for file_path in dir_path.rglob("*"):
if file_path.is_file() and file_path.suffix.lower() in {".txt", ".md", ".py", ".json"}:
content = file_path.read_text(encoding="utf-8")
title = file_path.stem
add_to_knowledge_base(content, title)
# Interactive CLI
async def interactive_loop():
print("RAG Agent CLI. Commands: /add <file_path>, /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() == "/quit":
print("Goodbye.") print("Exiting.")
break break
if user_input.lower().startswith("/add"): if user_input.startswith("/add "):
title = input("Title: ").strip() _, file_path = user_input.split(maxsplit=1)
print("Enter content (end with a single line containing only END):") try:
lines = [] content = Path(file_path).read_text(encoding="utf-8")
while True: title = Path(file_path).stem
line = input() result = add_to_knowledge_base(content, title)
if line.strip() == "END": print(result)
break except Exception as e:
lines.append(line) print(f"Error adding file: {e}")
content = "\n".join(lines) continue
result = add_to_knowledge_base(content, title) if user_input.startswith("/search "):
_, query = user_input.split(maxsplit=1)
result = search_knowledge_base(query, max_results=3)
print(result) print(result)
continue continue
if user_input.lower().startswith("/search"): # Treat as normal message to agent
query = input("Query: ").strip() try:
max_results_str = input("Max results (default 3): ").strip() response = await agent.ainvoke(
max_results = int(max_results_str) if max_results_str.isdigit() else 3 {"messages": [HumanMessage(content=user_input)]},
result = search_knowledge_base(query, max_results) {"configurable": {"thread_id": "session-1"}},
print("Search results:") )
print(result) print(response["messages"][-1].content)
continue except Exception as e:
# Regular message to agent print(f"Agent error: {e}")
response = await agent.ainvoke(
{"messages": [HumanMessage(content=user_input)]}, def main():
{"configurable": {"thread_id": "session-1"}}, # Optional: load initial docs from a folder
) init_dir = os.getenv("INIT_DOCS_DIR")
print(response["messages"][-1].content) if init_dir:
try:
load_documents_from_dir(init_dir)
print(f"Loaded documents from {init_dir}")
except Exception as e:
print(f"Failed to load initial docs: {e}")
asyncio.run(interactive_loop())
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) main()