Files
task-6a02e23da6fe2e4ac16acf65/main.py
T

77 lines
2.8 KiB
Python

import asyncio
import os
from pathlib import Path
from langchain_core.messages import HumanMessage
from langchain.tools import tool
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
from utils import llm, vector_store, splitter
from langchain_core.documents import Document
@tool
def search_knowledge_base(query: str, max_results: int = 3) -> str:
"""Search the knowledge base for relevant information."""
docs = vector_store.similarity_search(query, k=max_results)
return "\n".join(d.page_content for d in docs) if docs else "No results."
@tool
def add_to_knowledge_base(content: str, title: str = "doc") -> str:
"""Add content to the knowledge base."""
chunks = splitter.split_text(content)
docs = [Document(page_content=chunk, metadata={"title": title}) for chunk in chunks]
vector_store.add_documents(docs)
return f"Added {len(docs)} chunks for {title}."
backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(),
])
agent = create_deep_agent(
model=llm,
tools=[search_knowledge_base, add_to_knowledge_base],
backend=backend,
system_prompt="You are a helpful assistant with access to a knowledge base. Use the provided tools to search and add information.",
)
async def main():
print("RAG Agent CLI. Commands: /add, /search, /quit")
while True:
user_input = input(">> ").strip()
if not user_input:
continue
if user_input.lower() == "/quit":
print("Goodbye.")
break
if user_input.lower().startswith("/add"):
title = input("Title: ").strip()
print("Enter content (end with a single line containing only END):")
lines = []
while True:
line = input()
if line.strip() == "END":
break
lines.append(line)
content = "\n".join(lines)
result = add_to_knowledge_base(content, title)
print(result)
continue
if user_input.lower().startswith("/search"):
query = input("Query: ").strip()
max_results_str = input("Max results (default 3): ").strip()
max_results = int(max_results_str) if max_results_str.isdigit() else 3
result = search_knowledge_base(query, max_results)
print("Search results:")
print(result)
continue
# Regular message to agent
response = await agent.ainvoke(
{"messages": [HumanMessage(content=user_input)]},
{"configurable": {"thread_id": "session-1"}},
)
print(response["messages"][-1].content)
if __name__ == "__main__":
asyncio.run(main())