add: main.py

This commit is contained in:
2026-06-04 16:29:22 +00:00
parent 4390888743
commit 83ddfe4631
+20 -28
View File
@@ -5,11 +5,9 @@ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_chroma import Chroma from langchain_chroma import Chroma
from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.documents import Document from langchain_core.documents import Document
from langchain_tavily import TavilySearchResults
from langchain.tools import tool 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_core.messages import HumanMessage
# Load environment variables # Load environment variables
load_dotenv() load_dotenv()
@@ -30,12 +28,16 @@ embeddings = OpenAIEmbeddings(
# ---------- Vector Store ---------- # ---------- Vector Store ----------
CHROMA_DIR = "./chroma_db" CHROMA_DIR = "./chroma_db"
vector_store = Chroma(collection_name="knowledge", embedding_function=embeddings, persist_directory=CHROMA_DIR) vector_store = Chroma(
collection_name="knowledge",
embedding_function=embeddings,
persist_directory=CHROMA_DIR,
)
# ---------- Document Loader ---------- # ---------- Document Loader ----------
def load_documents(directory: str): def load_documents(directory: str):
"""Read .txt/.md files, split into chunks, and add to Chroma collection.""" """Read .txt/.md files, split into chunks and add to Chroma."""
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
docs = [] docs = []
for root, _, files in os.walk(directory): for root, _, files in os.walk(directory):
@@ -54,28 +56,24 @@ def load_documents(directory: str):
if not os.path.exists(CHROMA_DIR) or not os.listdir(CHROMA_DIR): if not os.path.exists(CHROMA_DIR) or not os.listdir(CHROMA_DIR):
load_documents("./documents") load_documents("./documents")
# ---------- Tavily Search ----------
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
if not TAVILY_API_KEY:
raise ValueError("TAVILY_API_KEY not set in .env")
# ---------- 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 Chroma knowledge base.""" """Semantic search in the local knowledge base."""
docs = vector_store.similarity_search(query, k=top_k) docs = vector_store.similarity_search(query, k=top_k)
if not docs: if not docs:
return "No relevant local knowledge found." return "No relevant information found in local knowledge base."
return "\n---\n".join([f"{d.metadata.get('source', 'unknown')}\n{d.page_content}" for d in docs]) return "\n---\n".join(f"{d.metadata.get('source', 'unknown')}\n{d.page_content}" for d in docs)
@tool @tool
def web_search(query: str) -> str: def web_search(query: str) -> str:
"""Web search using Tavily.""" """Web search using Tavily."""
results = TavilySearchResults(api_key=TAVILY_API_KEY, max_results=3) from langchain_tavily import TavilySearchResults
search_results = results.run(query) tavily = TavilySearchResults(max_results=3)
if not search_results: results = tavily.run(query)
if not results:
return "No web results found." return "No web results found."
return "\n---\n".join([f"{r['title']}\n{r['content']}" for r in search_results]) return "\n---\n".join(f"{r['title']}\n{r['content']}" for r in results)
# ---------- Backend ---------- # ---------- Backend ----------
backend = CompositeBackend([ backend = CompositeBackend([
@@ -88,17 +86,10 @@ 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="You are a helpful assistant. For questions about local documents use the local knowledge base. For uptodate facts use web search. Always state the source (chromadb or tavily) in your answer.",
"You are a RAG agent with a local knowledge base and web search capability. "
"When a user asks a question, decide whether the answer can be found in the local "
"knowledge base or requires uptodate information from the web. Use the tool "
"search_local_kb for local queries and web_search for web queries. "
"Always indicate the source of the information in your final answer: "
"(chromadb) or (tavily)."
),
) )
# ---------- CLI ---------- # ---------- Main Loop ----------
async def main(): async def main():
print("RAG Agent ready. Type 'exit' to quit.") print("RAG Agent ready. Type 'exit' to quit.")
while True: while True:
@@ -106,13 +97,14 @@ async def main():
if user_input.lower() in {"exit", "quit"}: if user_input.lower() in {"exit", "quit"}:
print("Goodbye!") print("Goodbye!")
break break
# Invoke agent
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 # Extract last message content
reply = result["messages"][-1].content answer = result["messages"][-1].content
print(f"\n{reply}") print(f"\nОтвет:\n{answer}")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())