add main.py
This commit is contained in:
@@ -1,21 +1,20 @@
|
|||||||
import os, asyncio
|
import os
|
||||||
|
import asyncio
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
||||||
from langchain_core.messages import HumanMessage
|
from langchain_chroma import Chroma
|
||||||
|
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
||||||
|
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_chroma import Chroma
|
from langchain_core.messages import HumanMessage
|
||||||
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
|
||||||
from langchain_ollama import OllamaEmbeddings
|
|
||||||
from langchain_ollama import Ollama
|
|
||||||
from langchain_tavily import TavilySearchResults
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
# Load env vars
|
# Load environment variables
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
# ---------- LLM ----------
|
# ---------- LLM and Embeddings ----------
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
model="openai/gpt-oss-20b:free",
|
model="openai/gpt-oss-20b:free",
|
||||||
base_url="https://openrouter.ai/api/v1",
|
base_url="https://openrouter.ai/api/v1",
|
||||||
@@ -23,43 +22,60 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Vectorstore ----------
|
embeddings = OpenAIEmbeddings(
|
||||||
persist_dir = Path("./chroma_db")
|
model="text-embedding-3-small",
|
||||||
persist_dir.mkdir(parents=True, exist_ok=True)
|
base_url="https://openrouter.ai/api/v1",
|
||||||
|
api_key=os.getenv("OPENAI_API_KEY"),
|
||||||
embeddings = OllamaEmbeddings(model="nomic-embed-text")
|
|
||||||
vectorstore = Chroma(
|
|
||||||
collection_name="knowledge",
|
|
||||||
embedding_function=embeddings,
|
|
||||||
persist_directory=str(persist_dir),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Load documents from ./documents
|
# ---------- Vector Store ----------
|
||||||
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
CHROMA_DIR = "./chroma_db"
|
||||||
for file_path in Path("./documents").glob("**/*.*"):
|
vector_store = Chroma(collection_name="knowledge", embedding_function=embeddings, persist_directory=CHROMA_DIR)
|
||||||
if file_path.suffix.lower() in {".txt", ".md"}:
|
|
||||||
content = file_path.read_text(encoding="utf-8")
|
# ---------- Document Loader ----------
|
||||||
docs = text_splitter.split_text(content)
|
|
||||||
vectorstore.add_documents([{"page_content": d, "metadata": {"source": str(file_path)}} for d in docs])
|
def load_documents(directory: str):
|
||||||
vectorstore.persist()
|
"""Read .txt/.md files, split into chunks, and add to Chroma collection."""
|
||||||
|
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
||||||
|
docs = []
|
||||||
|
for root, _, files in os.walk(directory):
|
||||||
|
for file in files:
|
||||||
|
if file.lower().endswith(('.txt', '.md')):
|
||||||
|
path = os.path.join(root, file)
|
||||||
|
with open(path, 'r', encoding='utf-8') as f:
|
||||||
|
text = f.read()
|
||||||
|
chunks = splitter.split_text(text)
|
||||||
|
docs.extend([Document(page_content=c, metadata={"source": path}) for c in chunks])
|
||||||
|
if docs:
|
||||||
|
vector_store.add_documents(docs)
|
||||||
|
vector_store.persist()
|
||||||
|
|
||||||
|
# Load documents once at startup
|
||||||
|
if not os.path.exists(CHROMA_DIR) or not os.listdir(CHROMA_DIR):
|
||||||
|
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 local ChromaDB knowledge base."""
|
"""Semantic search in the local Chroma knowledge base."""
|
||||||
docs = vectorstore.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 local knowledge found."
|
||||||
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 via Tavily."""
|
"""Web search using Tavily."""
|
||||||
tavily = TavilySearchResults(api_key=os.getenv("TAVILY_API_KEY"))
|
results = TavilySearchResults(api_key=TAVILY_API_KEY, max_results=3)
|
||||||
results = tavily.run(query)
|
search_results = results.run(query)
|
||||||
if not results:
|
if not search_results:
|
||||||
return "No web results found."
|
return "No web results found."
|
||||||
return "\n---\n".join([f"{r['title']}\n{r['content']}" for r in results])
|
return "\n---\n".join([f"{r['title']}\n{r['content']}" for r in search_results])
|
||||||
|
|
||||||
# ---------- Backend ----------
|
# ---------- Backend ----------
|
||||||
backend = CompositeBackend([
|
backend = CompositeBackend([
|
||||||
@@ -72,13 +88,21 @@ 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="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 your answer.",
|
system_prompt=(
|
||||||
|
"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 up‑to‑date 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 ----------
|
||||||
async def main():
|
async def main():
|
||||||
print("Welcome to the RAG agent. Type 'exit' to quit.")
|
print("RAG Agent ready. Type 'exit' to quit.")
|
||||||
while True:
|
while True:
|
||||||
user_input = input("\nQuery: ")
|
user_input = input("\nЗапрос: ")
|
||||||
if user_input.lower() in {"exit", "quit"}:
|
if user_input.lower() in {"exit", "quit"}:
|
||||||
print("Goodbye!")
|
print("Goodbye!")
|
||||||
break
|
break
|
||||||
@@ -86,9 +110,9 @@ async def main():
|
|||||||
{"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; last is the assistant reply
|
# The agent returns a list of messages; the last is the assistant reply
|
||||||
reply = result["messages"][-1].content
|
reply = result["messages"][-1].content
|
||||||
print("\nAnswer:\n", reply)
|
print(f"\n{reply}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|||||||
Reference in New Issue
Block a user