94 lines
3.5 KiB
Python
94 lines
3.5 KiB
Python
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from dotenv import load_dotenv
|
|
|
|
from langchain_openai import ChatOpenAI
|
|
from langchain_ollama import OllamaEmbeddings
|
|
from langchain_chroma import Chroma
|
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
from langchain.tools import tool
|
|
from langchain.agents import AgentExecutor, create_openai_tools_agent
|
|
from langchain_community.tools.tavily import TavilySearchResults
|
|
|
|
# Load env variables
|
|
load_dotenv()
|
|
|
|
# ---------- LLM and embeddings ----------
|
|
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 = OllamaEmbeddings(model="nomic-embed-text")
|
|
|
|
# ---------- Vectorstore ----------
|
|
PERSIST_DIR = Path("./chroma_db")
|
|
PERSIST_DIR.mkdir(parents=True, exist_ok=True)
|
|
vectorstore = Chroma(persist_directory=str(PERSIST_DIR), embedding_function=embeddings)
|
|
|
|
# Load documents if collection empty
|
|
if not vectorstore.get_collection().count():
|
|
docs_dir = Path("./documents")
|
|
if docs_dir.exists():
|
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
|
for file in docs_dir.glob("**/*.*"):
|
|
if file.suffix.lower() in {".txt", ".md"}:
|
|
text = file.read_text(encoding="utf-8")
|
|
chunks = splitter.split_text(text)
|
|
vectorstore.add_texts(chunks, ids=[f"{file.name}_{i}" for i in range(len(chunks))])
|
|
vectorstore.persist()
|
|
|
|
# ---------- Tools ----------
|
|
@tool("search_local_kb")
|
|
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.get_relevant_documents(query)
|
|
if not docs:
|
|
return "No relevant documents found in local KB."
|
|
return "\n---\n".join(doc.page_content for doc in docs)
|
|
|
|
@tool("web_search")
|
|
def web_search(query: str) -> str:
|
|
"""Web search using Tavily."""
|
|
tavily = TavilySearchResults(max_results=3)
|
|
results = tavily.run(query)
|
|
if not results:
|
|
return "No web results found."
|
|
return "\n---\n".join(f"{r['title']}\n{r['url']}\n{r.get('content', '')}" for r in results)
|
|
|
|
# ---------- Agent ----------
|
|
SYSTEM_PROMPT = (
|
|
"You are an AI assistant. For questions about local documents, use the tool 'search_local_kb'. "
|
|
"For up-to-date information or news, use 'web_search'. Always indicate the source in your answer."
|
|
)
|
|
|
|
tools = [search_local_kb, web_search]
|
|
agent = create_openai_tools_agent(llm, tools, system_message=SYSTEM_PROMPT)
|
|
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
|
|
|
# ---------- CLI ----------
|
|
|
|
def main():
|
|
print("RAG Agent with ChromaDB and Tavily. Type 'exit' to quit.")
|
|
while True:
|
|
try:
|
|
query = input("\nЗапрос: ")
|
|
except (EOFError, KeyboardInterrupt):
|
|
print("\nBye!")
|
|
break
|
|
if query.strip().lower() in {"exit", "quit"}:
|
|
print("Bye!")
|
|
break
|
|
result = agent_executor.invoke({"input": query})
|
|
# The tool name is stored in the tool_calls field of the result
|
|
tool_name = result.get("tool_calls", [{}])[0].get("name", "unknown")
|
|
source = "tavily" if tool_name == "web_search" else "chromadb"
|
|
print(f"\n[{'Web Search' if source=='tavily' else 'Local KB'}] {result.get('output', '')}\n")
|
|
print(f"Источник: {source}\n")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|