89 lines
3.0 KiB
Python
89 lines
3.0 KiB
Python
import os
|
||
import asyncio
|
||
from pathlib import Path
|
||
from dotenv import load_dotenv
|
||
|
||
from langchain_openai import ChatOpenAI
|
||
from langchain_core.messages import HumanMessage
|
||
from langchain.tools import tool
|
||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||
from langchain_chroma import Chroma
|
||
from langchain_ollama import OllamaEmbeddings
|
||
from langchain_tavily import TavilySearchResults
|
||
from deepagents import create_deep_agent
|
||
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
||
|
||
# Load env vars
|
||
load_dotenv()
|
||
|
||
# ---------- LLM ----------
|
||
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,
|
||
)
|
||
|
||
# ---------- Backend ----------
|
||
backend = CompositeBackend([
|
||
LocalShellBackend(workspace_dir="./workspace"),
|
||
FilesystemBackend(),
|
||
])
|
||
|
||
# ---------- Vector Store ----------
|
||
PERSIST_DIR = Path("./chroma_db")
|
||
PERSIST_DIR.mkdir(exist_ok=True)
|
||
|
||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
||
vectorstore = Chroma(persist_directory=str(PERSIST_DIR), embedding_function=embeddings)
|
||
|
||
# Load documents from ./documents if not already loaded
|
||
if not vectorstore.get_collection().count():
|
||
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
||
docs = []
|
||
for file in Path("./documents").glob("*.txt"):
|
||
text = file.read_text(encoding="utf-8")
|
||
docs.extend(splitter.split_text(text))
|
||
vectorstore.add_texts(docs)
|
||
|
||
# ---------- Tools ----------
|
||
@tool
|
||
def search_local_kb(query: str, top_k: int = 3) -> str:
|
||
"""Semantic search in local ChromaDB knowledge base."""
|
||
retriever = vectorstore.as_retriever(search_kwargs={"k": top_k})
|
||
docs = retriever.invoke(query)
|
||
return "\n".join(doc.page_content for doc in docs) if docs else "No local results found."
|
||
|
||
@tool
|
||
def web_search(query: str) -> str:
|
||
"""Web search via Tavily."""
|
||
tavily = TavilySearchResults(api_key=os.getenv("TAVILY_API_KEY"))
|
||
results = tavily.invoke(query)
|
||
return "\n".join(f"{r['title']}: {r['url']}" for r in results) if results else "No web results found."
|
||
|
||
# ---------- Agent ----------
|
||
agent = create_deep_agent(
|
||
model=llm,
|
||
tools=[search_local_kb, web_search],
|
||
backend=backend,
|
||
system_prompt="You are a helpful RAG agent. For questions about local documents use search_local_kb, for up‑to‑date facts use web_search. Always state the source (chromadb or tavily) in the answer.",
|
||
)
|
||
|
||
# ---------- CLI ----------
|
||
async def main():
|
||
print("RAG Agent ready. Type 'exit' to quit.")
|
||
while True:
|
||
user_input = input("\nЗапрос: ")
|
||
if user_input.lower() in {"exit", "quit"}:
|
||
break
|
||
result = await agent.ainvoke(
|
||
{"messages": [HumanMessage(content=user_input)]},
|
||
{"configurable": {"thread_id": "session-1"}},
|
||
)
|
||
# The agent returns a list of messages; last is the assistant reply
|
||
reply = result["messages"][-1].content
|
||
print(f"\nОтвет: {reply}")
|
||
|
||
if __name__ == "__main__":
|
||
asyncio.run(main())
|