add main.py

This commit is contained in:
2026-06-04 15:55:29 +00:00
parent 9a275db142
commit 7b972b123a
+40 -39
View File
@@ -4,12 +4,13 @@ from pathlib import Path
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage from langchain_core.messages import HumanMessage
from langchain.tools import tool from langchain.tools import tool
from langchain_ollama import OllamaEmbeddings
from langchain_chroma import Chroma
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_tavily import TavilySearchResults
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_chroma import Chroma
from langchain_ollama import OllamaEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings
from langchain_tavily import TavilySearchResults
# ---------- LLM ---------- # ---------- LLM ----------
llm = ChatOpenAI( llm = ChatOpenAI(
@@ -27,42 +28,35 @@ backend = CompositeBackend([
# ---------- Vectorstore utilities ---------- # ---------- Vectorstore utilities ----------
PERSIST_DIR = Path("./chroma_db") PERSIST_DIR = Path("./chroma_db")
PERSIST_DIR.mkdir(parents=True, exist_ok=True)
# Create or load Chroma vectorstore def create_vectorstore(persist_directory: str = "./chroma_db"):
vectorstore = Chroma( embeddings = OllamaEmbeddings(model="nomic-embed-text")
persist_directory=str(PERSIST_DIR), return Chroma(persist_directory=persist_directory, embedding_function=embeddings)
embedding_function=OllamaEmbeddings(model="nomic-embed-text"),
)
# Load documents from a directory into the vectorstore
def load_documents(directory: str, vectorstore): def load_documents(directory: str, vectorstore):
docs = []
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
for file_path in Path(directory).glob("**/*"): docs = []
if file_path.suffix.lower() in {".txt", ".md"}: for file in Path(directory).glob("**/*"):
text = file_path.read_text(encoding="utf-8") if file.suffix.lower() in {".txt", ".md"}:
text = file.read_text(encoding="utf-8")
docs.extend(splitter.split_text(text)) docs.extend(splitter.split_text(text))
# Convert to LangChain Documents # Convert to Document objects
from langchain_core.documents import Document from langchain_core.documents import Document
documents = [Document(page_content=chunk) for chunk in docs] documents = [Document(page_content=chunk) for chunk in docs]
vectorstore.add_documents(documents) vectorstore.add_documents(documents)
vectorstore.persist() vectorstore.persist()
# Load documents once at startup (if not already loaded)
if not any(PERSIST_DIR.iterdir()):
load_documents("./documents", vectorstore)
# ---------- Tools ---------- # ---------- Tools ----------
@tool @tool
def search_local_kb(query: str, top_k: int = 3) -> str: def search_local_kb(query: str, top_k: int = 3) -> str:
"""Semantic search in the local ChromaDB knowledge base.""" """Semantic search in the local ChromaDB knowledge base."""
vectorstore = create_vectorstore(PERSIST_DIR)
retriever = vectorstore.as_retriever(search_kwargs={"k": top_k}) retriever = vectorstore.as_retriever(search_kwargs={"k": top_k})
docs = retriever.get_relevant_documents(query) docs = retriever.invoke(query)
if not docs: if not docs:
return "No relevant documents found in local KB." return "No relevant local documents found."
return "\n---\n".join(doc.page_content for doc in docs) return "\n---\n".join(doc.page_content for doc in docs) + "\n[Source: chromadb]"
@tool @tool
def web_search(query: str) -> str: def web_search(query: str) -> str:
@@ -71,39 +65,46 @@ def web_search(query: str) -> str:
results = tavily.run(query) results = tavily.run(query)
if not results: if not results:
return "No web results found." return "No web results found."
return "\n---\n".join(f"{r['title']}\n{r['url']}\n{r.get('content', '')}" for r in results) snippets = [f"{r['title']}\n{r['content']}" for r in results]
return "\n---\n".join(snippets) + "\n[Source: tavily]"
# ---------- Agent ---------- # ---------- Agent ----------
SYSTEM_PROMPT = (
"You are an AI assistant that can answer questions using either a local knowledge base or the web. "
"If the question refers to documents in the local folder, use the `search_local_kb` tool. "
"If the question is about recent events or requires uptodate information, use the `web_search` tool. "
"Always include the source tag (`[Source: chromadb]` or `[Source: tavily]`) in your answer."
)
agent = create_deep_agent( agent = create_deep_agent(
model=llm, model=llm,
tools=[search_local_kb, web_search], tools=[search_local_kb, web_search],
backend=backend, backend=backend,
system_prompt=( system_prompt=SYSTEM_PROMPT,
"You are an AI assistant that answers user questions.\n"
"If the question is about information that should be in the local knowledge base,\n"
"use the search_local_kb tool.\n"
"If the question requires uptodate information from the web,\n"
"use the web_search tool.\n"
"Always indicate the source of the answer in the format:\n"
"[Source: chromadb] or [Source: tavily] before the answer."
),
) )
# ---------- CLI ---------- # ---------- CLI ----------
async def main(): async def chat_loop():
print("RAG Agent with ChromaDB and Tavily. Type 'exit' to quit.") print("RAG Agent ready. Type 'exit' to quit.")
while True: while True:
user_input = input("\nЗапрос: ") user_input = input("\nЗапрос: ")
if user_input.lower() in {"exit", "quit"}: if user_input.strip().lower() == "exit":
print("Goodbye!") print("Goodbye!")
break break
result = await agent.ainvoke( result = await agent.ainvoke(
{"messages": [HumanMessage(content=user_input)]}, {"messages": [HumanMessage(content=user_input)]},
{"configurable": {"thread_id": "session-1"}}, {"configurable": {"thread_id": "session-1"}},
) )
# The agent returns a list of messages; the last is the assistant reply # The last message is the assistant's reply
reply = result["messages"][-1].content reply = result["messages"][-1].content
print(f"\n{reply}") print(reply)
# ---------- Initialization ----------
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) # Ensure vectorstore exists and load documents if empty
vectorstore = create_vectorstore(PERSIST_DIR)
if not vectorstore.get_all_documents():
print("Loading documents into ChromaDB...")
load_documents("./documents", vectorstore)
print("Documents loaded.")
asyncio.run(chat_loop())