add cli.py

This commit is contained in:
2026-05-28 13:12:54 +00:00
parent 834f7d14ad
commit 5254d064ee
+50 -3
View File
@@ -1,19 +1,66 @@
""" """
Simple CLI for interacting with the RAG agent. CLI for interacting with the RAG agent.
This script provides three explicit commands:
* ``/add <text>`` add a piece of text to the knowledge base.
* ``/search <query>`` search the knowledge base and display results.
* ``/quit`` exit the program.
Any other input is forwarded to the underlying agent as a normal question.
""" """
import asyncio import asyncio
from langchain_core.messages import HumanMessage from langchain_core.messages import HumanMessage
from agent import run_agent from agent import run_agent
from tools import add_to_knowledge_base, search_knowledge_base
async def main(): async def main() -> None:
print("RAG Agent CLI. Type /quit to exit.") print("RAG Agent CLI. Type /quit to exit.")
while True: while True:
user_input = input("You: ") user_input = input("You: ")
if user_input.strip() == "/quit": stripped = user_input.strip()
if not stripped:
continue
# Handle explicit commands
if stripped.startswith("/add "):
text = stripped[5:].strip()
if not text:
print("Error: /add requires a nonempty text.")
continue
try:
await add_to_knowledge_base(text)
print("✅ Added to knowledge base.")
except Exception as exc: # pragma: no cover - defensive
print(f"❌ Failed to add: {exc}")
elif stripped.startswith("/search "):
query = stripped[8:].strip()
if not query:
print("Error: /search requires a nonempty query.")
continue
try:
results = await search_knowledge_base(query)
if not results:
print("No results found.")
else:
for idx, res in enumerate(results, start=1):
print(f"{idx}. {res}")
except Exception as exc: # pragma: no cover - defensive
print(f"❌ Search error: {exc}")
elif stripped == "/quit":
print("Goodbye!")
break break
else:
# Forward to agent
msg = HumanMessage(content=user_input) msg = HumanMessage(content=user_input)
try:
response = await run_agent([msg]) response = await run_agent([msg])
# ``run_agent`` returns the last assistant message as a string.
if isinstance(response, str):
print(f"Agent: {response}") print(f"Agent: {response}")
else:
print("Agent returned unexpected format.")
except Exception as exc: # pragma: no cover - defensive
print(f"❌ Agent error: {exc}")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())