add: main.py
This commit is contained in:
@@ -5,11 +5,9 @@ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
|
||||
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 deepagents import create_deep_agent
|
||||
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
||||
from langchain_core.messages import HumanMessage
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
@@ -30,12 +28,16 @@ embeddings = OpenAIEmbeddings(
|
||||
|
||||
# ---------- Vector Store ----------
|
||||
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 ----------
|
||||
|
||||
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)
|
||||
docs = []
|
||||
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):
|
||||
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 ----------
|
||||
@tool
|
||||
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)
|
||||
if not docs:
|
||||
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 "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)
|
||||
|
||||
@tool
|
||||
def web_search(query: str) -> str:
|
||||
"""Web search using Tavily."""
|
||||
results = TavilySearchResults(api_key=TAVILY_API_KEY, max_results=3)
|
||||
search_results = results.run(query)
|
||||
if not search_results:
|
||||
from langchain_tavily import TavilySearchResults
|
||||
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['content']}" for r in search_results])
|
||||
return "\n---\n".join(f"{r['title']}\n{r['content']}" for r in results)
|
||||
|
||||
# ---------- Backend ----------
|
||||
backend = CompositeBackend([
|
||||
@@ -88,17 +86,10 @@ agent = create_deep_agent(
|
||||
model=llm,
|
||||
tools=[search_local_kb, web_search],
|
||||
backend=backend,
|
||||
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)."
|
||||
),
|
||||
system_prompt="You are a helpful assistant. For questions about local documents use the local knowledge base. For up‑to‑date facts use web search. Always state the source (chromadb or tavily) in your answer.",
|
||||
)
|
||||
|
||||
# ---------- CLI ----------
|
||||
# ---------- Main Loop ----------
|
||||
async def main():
|
||||
print("RAG Agent ready. Type 'exit' to quit.")
|
||||
while True:
|
||||
@@ -106,13 +97,14 @@ async def main():
|
||||
if user_input.lower() in {"exit", "quit"}:
|
||||
print("Goodbye!")
|
||||
break
|
||||
# Invoke agent
|
||||
result = await agent.ainvoke(
|
||||
{"messages": [HumanMessage(content=user_input)]},
|
||||
{"configurable": {"thread_id": "session-1"}},
|
||||
)
|
||||
# The agent returns a list of messages; the last is the assistant reply
|
||||
reply = result["messages"][-1].content
|
||||
print(f"\n{reply}")
|
||||
# Extract last message content
|
||||
answer = result["messages"][-1].content
|
||||
print(f"\nОтвет:\n{answer}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
|
||||
Reference in New Issue
Block a user