Update src/cli.py
This commit is contained in:
+56
-48
@@ -1,67 +1,75 @@
|
|||||||
"""Interactive command‑line client for the RAG agent.
|
"""Interactive command line client for the RAG agent.
|
||||||
|
|
||||||
Commands:
|
Commands:
|
||||||
/add – add a new document to the knowledge base.
|
/add <title> <path> – Load a document from a file and add it to the knowledge base.
|
||||||
/search – perform a semantic search.
|
/search <query> – Search the knowledge base and display results.
|
||||||
/quit – exit the program.
|
/quit – Exit the program.
|
||||||
|
/help – Show this help message.
|
||||||
|
|
||||||
Any other input is treated as a user message and is processed by the agent.
|
The client uses the global agent defined in ``src.agent`` and the knowledge
|
||||||
|
base instance from ``src.tools``.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from typing import List
|
from __future__ import annotations
|
||||||
|
|
||||||
from .agent import run_agent
|
import sys
|
||||||
from .tools import search_knowledge_base, add_to_knowledge_base
|
from pathlib import Path
|
||||||
|
|
||||||
|
from .agent import run_query
|
||||||
|
from .tools import kb
|
||||||
|
|
||||||
|
HELP_TEXT = """
|
||||||
|
Available commands:
|
||||||
|
/add <title> <file_path> Add a document to the knowledge base.
|
||||||
|
/search <query> Search the knowledge base.
|
||||||
|
/quit Exit the program.
|
||||||
|
/help Show this help message.
|
||||||
|
"""
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
print("Welcome to the RAG agent CLI. Type /help for commands.")
|
print("RAG Agent CLI. Type /help for commands.")
|
||||||
history: List[dict] = []
|
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
user_input = input(">>> ")
|
user_input = input("> ")
|
||||||
except EOFError:
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
print("\nExiting.")
|
||||||
break
|
break
|
||||||
if not user_input:
|
if not user_input.strip():
|
||||||
continue
|
continue
|
||||||
if user_input.startswith("/"):
|
if user_input.startswith("/add"):
|
||||||
cmd, *args = user_input.split(maxsplit=1)
|
parts = user_input.split(maxsplit=2)
|
||||||
if cmd == "/quit":
|
if len(parts) != 3:
|
||||||
print("Goodbye!")
|
print("Usage: /add <title> <file_path>")
|
||||||
break
|
|
||||||
elif cmd == "/help":
|
|
||||||
print("Commands: /add, /search, /quit")
|
|
||||||
continue
|
continue
|
||||||
elif cmd == "/add":
|
title, file_path = parts[1], parts[2]
|
||||||
title = input("Title: ")
|
path = Path(file_path)
|
||||||
print("Enter content (end with a single line containing only 'END'):\n")
|
if not path.is_file():
|
||||||
lines = []
|
print(f"File not found: {file_path}")
|
||||||
while True:
|
|
||||||
line = input()
|
|
||||||
if line.strip() == "END":
|
|
||||||
break
|
|
||||||
lines.append(line)
|
|
||||||
content = "\n".join(lines)
|
|
||||||
response = add_to_knowledge_base(content, title)
|
|
||||||
print(response)
|
|
||||||
continue
|
continue
|
||||||
elif cmd == "/search":
|
content = path.read_text(encoding="utf-8")
|
||||||
query = input("Query: ")
|
kb.add_document(title=title, content=content)
|
||||||
results = search_knowledge_base(query, max_results=5)
|
print(f"Document '{title}' added.")
|
||||||
if not results:
|
elif user_input.startswith("/search"):
|
||||||
print("No results found.")
|
query = user_input[len("/search"):].strip()
|
||||||
else:
|
if not query:
|
||||||
for i, res in enumerate(results, 1):
|
print("Please provide a search query.")
|
||||||
print(f"{i}. Title: {res['title']}, Score: {res['score']:.4f}")
|
|
||||||
print(f" {res['content'][:200]}...\n")
|
|
||||||
continue
|
continue
|
||||||
else:
|
results = kb.search(query, limit=5)
|
||||||
print("Unknown command. Type /help for list of commands.")
|
if not results:
|
||||||
|
print("No results found.")
|
||||||
continue
|
continue
|
||||||
# Normal user message
|
print("Results:")
|
||||||
history.append({"role": "user", "content": user_input})
|
for i, r in enumerate(results, 1):
|
||||||
reply = run_agent(history)
|
print(f"{i}. [{r['title']} - chunk {r['chunk_index']}] {r['content'][:200]}...")
|
||||||
print(f"Assistant: {reply}")
|
elif user_input.startswith("/quit"):
|
||||||
history.append({"role": "assistant", "content": reply})
|
print("Goodbye.")
|
||||||
|
break
|
||||||
|
elif user_input.startswith("/help"):
|
||||||
|
print(HELP_TEXT)
|
||||||
|
else:
|
||||||
|
# Treat as a normal user query to the agent.
|
||||||
|
response = run_query(user_input)
|
||||||
|
print(response)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user