fix: main.py — Агент с RAG-памятью
This commit is contained in:
@@ -1,20 +1,14 @@
|
|||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
from dotenv import load_dotenv
|
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.messages import HumanMessage
|
||||||
from langchain_core.documents import Document
|
|
||||||
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 tools import search_knowledge_base, add_to_knowledge_base
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
||||||
from qdrant_client import QdrantClient
|
|
||||||
|
|
||||||
# Загрузка переменных окружения
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
# Инициализация LLM
|
|
||||||
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",
|
||||||
@@ -22,90 +16,43 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
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([
|
backend = CompositeBackend([
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
FilesystemBackend(),
|
FilesystemBackend(),
|
||||||
])
|
])
|
||||||
|
|
||||||
# Создание агента
|
|
||||||
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 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():
|
async def interactive_loop():
|
||||||
print("Interactive agent. Commands: /add, /search, /quit")
|
thread_id = "interactive-session"
|
||||||
|
print("Welcome to RAG Agent. Commands: /add <title> <content>, /search <query>, /quit")
|
||||||
while True:
|
while True:
|
||||||
try:
|
user_input = input(">> ")
|
||||||
user_input = input("> ").strip()
|
if user_input.strip() == "/quit":
|
||||||
except EOFError:
|
print("Goodbye.")
|
||||||
break
|
break
|
||||||
if not user_input:
|
|
||||||
continue
|
|
||||||
if user_input.startswith("/add"):
|
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:
|
try:
|
||||||
max_results = int(max_str)
|
_, title, content = user_input.split(" ", 2)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
max_results = 3
|
print("Usage: /add <title> <content>")
|
||||||
result = search_knowledge_base(query, max_results)
|
continue
|
||||||
print(result)
|
message = HumanMessage(content=f"Add document titled '{title}' with content: {content}")
|
||||||
elif user_input.startswith("/quit"):
|
elif user_input.startswith("/search"):
|
||||||
print("Goodbye!")
|
query = user_input[len("/search"):].strip()
|
||||||
break
|
message = HumanMessage(content=f"Search knowledge base for: {query}")
|
||||||
else:
|
else:
|
||||||
# обычный диалог с агентом
|
message = HumanMessage(content=user_input)
|
||||||
response = await agent.ainvoke(
|
result = await agent.ainvoke(
|
||||||
{"messages": [HumanMessage(content=user_input)]},
|
{"messages": [message]},
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
{"configurable": {"thread_id": thread_id}},
|
||||||
)
|
)
|
||||||
print(response["messages"][-1].content)
|
print(result["messages"][-1].content)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(interactive_loop())
|
||||||
Reference in New Issue
Block a user