|
import requests |
|
import json |
|
|
|
|
|
def test_api_connection(): |
|
"""Test if the API is running""" |
|
try: |
|
response = requests.get("http://localhost:8000/", timeout=5) |
|
print("β
API is running!") |
|
print(f"Status: {response.json()}") |
|
return True |
|
except requests.exceptions.ConnectionError: |
|
print("β Cannot connect to API. Make sure it's running on http://localhost:8000") |
|
return False |
|
except Exception as e: |
|
print(f"β Error connecting to API: {e}") |
|
return False |
|
|
|
|
|
def ask_question(question): |
|
"""Send a question to the API""" |
|
try: |
|
url = "http://localhost:8000/ask" |
|
headers = {"Content-Type": "application/json"} |
|
data = {"query": question} |
|
|
|
print("π€ Processing your question...") |
|
response = requests.post(url, headers=headers, json=data, timeout=30) |
|
|
|
if response.status_code == 200: |
|
result = response.json() |
|
print("\n" + "="*60) |
|
print("π ANSWER:") |
|
print("="*60) |
|
print(result.get("answer", "No answer provided")) |
|
|
|
print(f"\nπ€ Model used: {result.get('model_used', 'Unknown')}") |
|
|
|
print( |
|
f"\n πͺ Vector store used: {result.get("vector_store_used", 'Unknown')}") |
|
|
|
if "sources" in result and result["sources"]: |
|
print(f"\nπ Sources ({len(result['sources'])}):") |
|
for i, source in enumerate(result["sources"], 1): |
|
print(f"{i}. {source.get('content', 'No content')}") |
|
print("="*60) |
|
else: |
|
print(f"β Error {response.status_code}: {response.text}") |
|
|
|
except requests.exceptions.Timeout: |
|
print("β° Request timed out. The API might be processing a complex query.") |
|
except Exception as e: |
|
print(f"β Error asking question: {e}") |
|
|
|
|
|
def interactive_loop(): |
|
"""Main interactive loop""" |
|
print("π FastAPI Interactive Tester") |
|
print("="*40) |
|
|
|
|
|
if not test_api_connection(): |
|
print("\nPlease start your FastAPI server first:") |
|
print("cd rag_app") |
|
print("python api/main.py") |
|
return |
|
|
|
print("\nπ‘ Type your questions below!") |
|
print("Commands:") |
|
print(" β’ Type any question to ask the API") |
|
print(" β’ Type 'quit', 'exit', or 'q' to exit") |
|
print(" β’ Type 'status' to check API status") |
|
print(" β’ Press Ctrl+C to exit anytime") |
|
print("-" * 40) |
|
|
|
while True: |
|
try: |
|
|
|
question = input("\nβ Your question: ").strip() |
|
|
|
|
|
if question.lower() in ['quit', 'exit', 'q']: |
|
print("π Goodbye!") |
|
break |
|
elif question.lower() == 'status': |
|
test_api_connection() |
|
continue |
|
elif not question: |
|
print("Please enter a question or 'quit' to exit.") |
|
continue |
|
|
|
|
|
ask_question(question) |
|
|
|
except KeyboardInterrupt: |
|
print("\n\nπ Goodbye!") |
|
break |
|
except Exception as e: |
|
print(f"β Unexpected error: {e}") |
|
|
|
|
|
if __name__ == "__main__": |
|
interactive_loop() |
|
|