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

This commit is contained in:
2026-07-02 08:35:07 +00:00
parent 374fbf6ccf
commit f730fd7796
+23 -76
View File
@@ -1,20 +1,14 @@
import os
import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
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_qdrant import QdrantVectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter
from qdrant_client import QdrantClient
from tools import search_knowledge_base, add_to_knowledge_base
# Загрузка переменных окружения
load_dotenv()
# Инициализация LLM
llm = ChatOpenAI(
model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1",
@@ -22,90 +16,43 @@ llm = ChatOpenAI(
temperature=0.0,
)
# Инициализация эмбеддингов
embeddings = OpenAIEmbeddings(
model="text-embedding-3-small",
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
)
# Инициализация Qdrant
client = QdrantClient(url="http://localhost:6333")
collection_name = "knowledge_base"
vector_store = QdrantVectorStore(
client=client,
collection_name=collection_name,
embeddings=embeddings,
)
# Чанкинг
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
# Инструмент поиска
@tool
def search_knowledge_base(query: str, max_results: int) -> 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".join(doc.page_content for doc in docs)
# Инструмент добавления
@tool
def add_to_knowledge_base(content: str, title: str) -> str:
"""Add content to the knowledge base."""
chunks = splitter.split_text(content)
docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
vector_store.add_documents(docs)
return f"Added {len(docs)} chunks for {title}."
# Backend для deepagents
backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(),
])
# Создание агента
agent = create_deep_agent(
model=llm,
tools=[search_knowledge_base, add_to_knowledge_base],
backend=backend,
system_prompt="You are a helpful agent with access to a knowledge base. Use the tools to search and add information.",
system_prompt="You are a helpful knowledge assistant. Use the tools to search and add documents.",
)
async def main():
print("Interactive agent. Commands: /add, /search, /quit")
async def interactive_loop():
thread_id = "interactive-session"
print("Welcome to RAG Agent. Commands: /add <title> <content>, /search <query>, /quit")
while True:
try:
user_input = input("> ").strip()
except EOFError:
user_input = input(">> ")
if user_input.strip() == "/quit":
print("Goodbye.")
break
if not user_input:
continue
if user_input.startswith("/add"):
title = input("Title: ").strip()
content = input("Content: ").strip()
result = add_to_knowledge_base(content, title)
print(result)
elif user_input.startswith("/search"):
query = input("Query: ").strip()
max_str = input("Max results (int): ").strip()
try:
max_results = int(max_str)
_, title, content = user_input.split(" ", 2)
except ValueError:
max_results = 3
result = search_knowledge_base(query, max_results)
print(result)
elif user_input.startswith("/quit"):
print("Goodbye!")
break
print("Usage: /add <title> <content>")
continue
message = HumanMessage(content=f"Add document titled '{title}' with content: {content}")
elif user_input.startswith("/search"):
query = user_input[len("/search"):].strip()
message = HumanMessage(content=f"Search knowledge base for: {query}")
else:
# обычный диалог с агентом
response = await agent.ainvoke(
{"messages": [HumanMessage(content=user_input)]},
{"configurable": {"thread_id": "session-1"}},
)
print(response["messages"][-1].content)
message = HumanMessage(content=user_input)
result = await agent.ainvoke(
{"messages": [message]},
{"configurable": {"thread_id": thread_id}},
)
print(result["messages"][-1].content)
if __name__ == "__main__":
asyncio.run(main())
asyncio.run(interactive_loop())