fix(needs_fixes): 1 исправлений, 0 отстояно — main.py
This commit is contained in:
@@ -1,138 +1,103 @@
|
|||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
|
||||||
|
# LangChain imports
|
||||||
|
from langchain_ollama import ChatOllama, OllamaEmbeddings
|
||||||
from langchain_core.documents import Document
|
from langchain_core.documents import Document
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
from langchain_qdrant import QdrantVectorStore
|
from langchain_qdrant import QdrantVectorStore
|
||||||
|
from langchain.agents import create_agent
|
||||||
from langchain.tools import tool
|
from langchain.tools import tool
|
||||||
from deepagents import create_deep_agent
|
from langchain_core.messages import HumanMessage
|
||||||
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
|
||||||
|
|
||||||
# Load environment variables (OPENAI_API_KEY)
|
# Load environment variables (e.g., Ollama host)
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# LLM and embeddings configuration
|
||||||
# LLM and embeddings configuration (OpenRouter)
|
llm = ChatOllama(model="llama3")
|
||||||
# ---------------------------------------------------------------------------
|
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||||||
llm = ChatOpenAI(
|
|
||||||
model="openai/gpt-oss-20b:free",
|
|
||||||
base_url="https://openrouter.ai/api/v1",
|
|
||||||
api_key=os.getenv("OPENAI_API_KEY"),
|
|
||||||
temperature=0.0,
|
|
||||||
)
|
|
||||||
|
|
||||||
embeddings = OpenAIEmbeddings(
|
# Qdrant client and vector store initialization
|
||||||
model="text-embedding-3-small",
|
|
||||||
base_url="https://openrouter.ai/api/v1",
|
|
||||||
api_key=os.getenv("OPENAI_API_KEY"),
|
|
||||||
)
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Qdrant vector store setup
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
from qdrant_client import QdrantClient
|
from qdrant_client import QdrantClient
|
||||||
|
|
||||||
qdrant_client = QdrantClient(url="http://localhost:6333") # Qdrant must be running locally
|
qdrant_client = QdrantClient(host="localhost", port=6333)
|
||||||
vector_store = QdrantVectorStore(
|
vector_store = QdrantVectorStore(
|
||||||
embedding_function=embeddings,
|
|
||||||
client=qdrant_client,
|
client=qdrant_client,
|
||||||
collection_name="knowledge",
|
collection_name="knowledge",
|
||||||
|
embeddings=embeddings,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Text splitter for chunking documents
|
# Text splitter for chunking documents
|
||||||
# ---------------------------------------------------------------------------
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
||||||
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# Tool: Search knowledge base
|
||||||
# Tools for the agent
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
@tool
|
@tool
|
||||||
async def search_knowledge_base(query: str, max_results: int = 5) -> str:
|
def search_knowledge_base(query: str, max_results: int = 3) -> str:
|
||||||
"""Perform a semantic search in the knowledge base."""
|
"""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)
|
||||||
if not docs:
|
if not docs:
|
||||||
return "No relevant documents found."
|
return "No relevant documents found."
|
||||||
return "\n\n".join([f"Title: {doc.metadata.get('title', 'N/A')}\n{doc.page_content}" for doc in docs])
|
return "\n\n---\n\n".join(f"<{doc.metadata.get('title', 'Untitled')}>
|
||||||
|
{doc.page_content}" for doc in docs)
|
||||||
|
|
||||||
|
# Tool: Add document to knowledge base
|
||||||
@tool
|
@tool
|
||||||
async def add_to_knowledge_base(content: str, title: str = "Unnamed Document") -> str:
|
def add_to_knowledge_base(content: str, title: str = "Document") -> str:
|
||||||
"""Add a document to the knowledge base after chunking."""
|
"""Add content to the knowledge base."""
|
||||||
chunks = text_splitter.split_text(content)
|
# Split content into chunks
|
||||||
docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
|
chunks = splitter.split_text(content)
|
||||||
vector_store.add_documents(docs)
|
documents = [Document(page_content=chunk, metadata={"title": title, "chunk_index": idx})
|
||||||
return f"Document '{title}' added with {len(chunks)} chunks."
|
for idx, chunk in enumerate(chunks)]
|
||||||
|
vector_store.add_documents(documents)
|
||||||
|
return f"Added {len(chunks)} chunks from '{title}'."
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# Agent creation
|
||||||
# Backend configuration for DeepAgents
|
agent = create_agent(
|
||||||
# ---------------------------------------------------------------------------
|
llm=llm,
|
||||||
backend = CompositeBackend([
|
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
|
||||||
FilesystemBackend(),
|
|
||||||
])
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# DeepAgent definition
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
agent = create_deep_agent(
|
|
||||||
model=llm,
|
|
||||||
tools=[search_knowledge_base, add_to_knowledge_base],
|
tools=[search_knowledge_base, add_to_knowledge_base],
|
||||||
backend=backend,
|
system_prompt="You are an AI assistant with access to a knowledge base. Use the provided tools to search and add information."
|
||||||
system_prompt="You are a helpful assistant with access to a knowledge base. Use the provided tools to search and add documents. Respond concisely.",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# Helper to invoke agent asynchronously
|
||||||
# Helper function to load all .txt files from a directory into the vector store
|
async def invoke_agent(user_input: str) -> str:
|
||||||
# ---------------------------------------------------------------------------
|
result = await agent.ainvoke(
|
||||||
async def load_documents_from_directory(directory: str):
|
{"messages": [HumanMessage(content=user_input)]},
|
||||||
dir_path = Path(directory)
|
{"configurable": {"thread_id": "session-1"}},
|
||||||
for txt_file in dir_path.rglob("*.txt"):
|
)
|
||||||
content = txt_file.read_text(encoding="utf-8")
|
# The last message is the agent's reply
|
||||||
title = txt_file.stem
|
return result["messages"][-1].content
|
||||||
await add_to_knowledge_base(content, title)
|
|
||||||
print(f"Loaded {len(list(dir_path.rglob('*.txt')))} documents from {directory}.")
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# CLI loop
|
||||||
# Interactive CLI client
|
async def main():
|
||||||
# ---------------------------------------------------------------------------
|
print("Welcome to the RAG agent CLI. Commands: /add <file_path> | /search <query> | /quit")
|
||||||
async def interactive_loop():
|
|
||||||
print("Welcome to the RAG Agent CLI. Commands: /add title content | /search query | /quit")
|
|
||||||
while True:
|
while True:
|
||||||
user_input = input("> ")
|
user_input = input(">>> ")
|
||||||
|
if not user_input:
|
||||||
|
continue
|
||||||
if user_input.lower() == "/quit":
|
if user_input.lower() == "/quit":
|
||||||
print("Goodbye!")
|
print("Goodbye!")
|
||||||
break
|
break
|
||||||
if user_input.startswith("/add "):
|
if user_input.lower().startswith("/add "):
|
||||||
try:
|
path = user_input[5:].strip()
|
||||||
_, rest = user_input.split("/add ", 1)
|
if Path(path).is_file():
|
||||||
title, content = rest.split(" ", 1)
|
content = Path(path).read_text(encoding="utf-8")
|
||||||
except ValueError:
|
title = Path(path).stem
|
||||||
print("Usage: /add title content")
|
# Directly invoke tool via agent
|
||||||
|
response = await invoke_agent(f"Add document: {title}\n{content}")
|
||||||
|
else:
|
||||||
|
print("File not found.")
|
||||||
continue
|
continue
|
||||||
human_msg = f"Please add a document titled '{title}' with content: {content}"
|
elif user_input.lower().startswith("/search "):
|
||||||
elif user_input.startswith("/search "):
|
query = user_input[8:].strip()
|
||||||
query = user_input[len("/search "):]
|
response = await invoke_agent(f"Search for: {query}")
|
||||||
human_msg = f"Please search for: {query}"
|
|
||||||
else:
|
else:
|
||||||
print("Unknown command. Use /add, /search, or /quit.")
|
print("Unknown command. Use /add, /search, or /quit.")
|
||||||
continue
|
continue
|
||||||
|
print("\n--- Agent Response ---\n")
|
||||||
result = await agent.ainvoke(
|
print(response)
|
||||||
{"messages": [HumanMessage(content=human_msg)]},
|
print("\n-----------------------\n")
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
|
||||||
)
|
|
||||||
print(result["messages"][-1].content)
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# Main entry point
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
async def main():
|
|
||||||
# Optionally load documents from a directory on startup
|
|
||||||
# await load_documents_from_directory("./data")
|
|
||||||
await interactive_loop()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|||||||
Reference in New Issue
Block a user