From f730fd7796875f5de8c67236c4b7fddaab260002 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=94=D0=B0=D0=BD=D0=B8=D0=B8=D0=BB=20=D0=92=D0=B8=D0=BA?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=BE=D0=B2?= Date: Thu, 2 Jul 2026 08:35:07 +0000 Subject: [PATCH] =?UTF-8?q?fix:=20main.py=20=E2=80=94=20=D0=90=D0=B3=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=20=D1=81=20RAG-=D0=BF=D0=B0=D0=BC=D1=8F=D1=82?= =?UTF-8?q?=D1=8C=D1=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 99 ++++++++++++++------------------------------------------- 1 file changed, 23 insertions(+), 76 deletions(-) diff --git a/main.py b/main.py index f67d0c0..75fb450 100644 --- a/main.py +++ b/main.py @@ -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 <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()) \ No newline at end of file + asyncio.run(interactive_loop()) \ No newline at end of file