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) # Test connection first 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: # Get user input question = input("\nā“ Your question: ").strip() # Handle special commands 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 the question ask_question(question) except KeyboardInterrupt: print("\n\nšŸ‘‹ Goodbye!") break except Exception as e: print(f"āŒ Unexpected error: {e}") if __name__ == "__main__": interactive_loop()