diff --git a/autonomous/connectors/perplexity_finance.py b/autonomous/connectors/perplexity_finance.py index bc710a66..3e1742f0 100644 --- a/autonomous/connectors/perplexity_finance.py +++ b/autonomous/connectors/perplexity_finance.py @@ -94,16 +94,14 @@ class PerplexityFinanceConnector: Fixed connector for Perplexity Finance API providing advanced financial analysis. """ - # List of valid Perplexity models (as of Jan 2024) + # List of valid Perplexity models (current API models) VALID_MODELS = [ - "pplx-7b-online", # Fast online model - "pplx-70b-online", # Large online model (may require pro) - "pplx-7b-chat", # Fast chat model - "pplx-70b-chat", # Large chat model - "sonar-small-online", # New Sonar models - "sonar-medium-online", - "sonar-small-chat", - "sonar-medium-chat" + "sonar", # Default sonar model (works!) + "sonar-online", # Online search model + "sonar-chat", # Chat-focused model + "mixtral-8x7b-instruct", # Mixtral instruct model + "codellama-70b-instruct", # Code-focused model + "llama-3.1-70b-instruct" # Large Llama model ] def __init__(self, @@ -140,7 +138,7 @@ class PerplexityFinanceConnector: self.finance_model = model else: # Default to most reliable model - self.finance_model = "sonar-small-online" # Fast and reliable + self.finance_model = "sonar" # Fast and reliable (verified working) logger.info(f"Using default model: {self.finance_model}") # Track rate limiting diff --git a/test_perplexity.py b/test_perplexity.py new file mode 100644 index 00000000..574f88bb --- /dev/null +++ b/test_perplexity.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python +""" +Quick test script to verify Perplexity API connectivity and functionality. +""" + +import asyncio +import os +from dotenv import load_dotenv +import sys + +# Load environment variables +load_dotenv() + +# Add current directory to path +sys.path.append('.') + +from autonomous.connectors.perplexity_finance import ( + PerplexityFinanceConnector, + AnalysisType, + ResearchDepth +) + + +async def test_perplexity(): + """Test Perplexity API functionality""" + + print("=" * 60) + print("šŸ” Testing Perplexity Finance API") + print("=" * 60) + + try: + # Initialize connector + print("\n1. Initializing Perplexity connector...") + connector = PerplexityFinanceConnector( + api_key=os.getenv('PERPLEXITY_API_KEY') + ) + print("āœ… Connector initialized") + + # Test 1: Analyze a single stock + print("\n2. Testing stock analysis (NVDA)...") + analysis = await connector.analyze_stock( + "NVDA", + AnalysisType.FUNDAMENTAL, + ResearchDepth.QUICK + ) + + print(f""" +āœ… Stock Analysis Complete: + - Ticker: {analysis.ticker} + - Current Price: ${analysis.current_price:.2f if analysis.current_price else 'N/A'} + - Fair Value: ${analysis.fair_value:.2f if analysis.fair_value else 'N/A'} + - P/E Ratio: {analysis.pe_ratio if analysis.pe_ratio else 'N/A'} + - Rating: {analysis.rating} + - Confidence: {analysis.confidence_score}% + + Analysis Preview: + {analysis.detailed_analysis[:300]}... + """) + + # Test 2: Market sentiment + print("\n3. Testing market sentiment analysis...") + sentiment = await connector.get_market_sentiment() + + print(f""" +āœ… Market Sentiment: + {sentiment['analysis'][:300]}... + """) + + # Test 3: Stock screening + print("\n4. Testing stock screening...") + query = "Find undervalued technology stocks with P/E under 25" + results = await connector.screen_stocks(query, max_results=5) + + print(f""" +āœ… Screening Results for: "{query}" + Found {results.total_results} stocks + + Top Results:""") + + for stock in results.stocks[:3]: + print(f" - {stock.get('ticker', 'N/A')}: ${stock.get('price', 0):.2f}") + + print("\n" + "=" * 60) + print("āœ… ALL TESTS PASSED - Perplexity API is working!") + print("=" * 60) + + return True + + except Exception as e: + print(f"\nāŒ Error: {e}") + import traceback + traceback.print_exc() + return False + + +async def test_research_agent(): + """Test the AI Research Agent with Perplexity""" + + print("\n" + "=" * 60) + print("šŸ¤– Testing AI Research Agent") + print("=" * 60) + + try: + from autonomous.research.ai_research_agent import ( + AIResearchAgent, + ResearchQuery, + ResearchMode + ) + + # Initialize agent + print("\n1. Initializing AI Research Agent...") + agent = AIResearchAgent( + openai_api_key=os.getenv('OPENAI_API_KEY'), + perplexity_connector=PerplexityFinanceConnector( + api_key=os.getenv('PERPLEXITY_API_KEY') + ) + ) + print("āœ… Agent initialized") + + # Test natural language query + print("\n2. Testing natural language query...") + question = "What are the top 3 undervalued stocks in the technology sector right now?" + print(f"Question: {question}") + + answer = await agent.answer_question(question) + + print(f""" +āœ… Answer received: +{answer[:500]}... + """) + + print("\n" + "=" * 60) + print("āœ… AI Research Agent is working!") + print("=" * 60) + + return True + + except Exception as e: + print(f"\nāŒ Error: {e}") + import traceback + traceback.print_exc() + return False + + +async def main(): + """Run all tests""" + + print(""" +╔════════════════════════════════════════════════════════════╗ +ā•‘ Perplexity Finance API Integration Test ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• + """) + + # Check for API key + if not os.getenv('PERPLEXITY_API_KEY'): + print("āŒ PERPLEXITY_API_KEY not found in .env file") + return + + print(f"šŸ“Œ Using Perplexity API key: {os.getenv('PERPLEXITY_API_KEY')[:10]}...") + + # Run tests + perplexity_ok = await test_perplexity() + + if perplexity_ok and os.getenv('OPENAI_API_KEY'): + agent_ok = await test_research_agent() + else: + print("\nāš ļø Skipping AI Research Agent test (requires OpenAI API key)") + agent_ok = False + + # Summary + print("\n" + "=" * 60) + print("šŸ“Š TEST SUMMARY") + print("=" * 60) + print(f"Perplexity API: {'āœ… PASSED' if perplexity_ok else 'āŒ FAILED'}") + print(f"Research Agent: {'āœ… PASSED' if agent_ok else 'ā­ļø SKIPPED' if not os.getenv('OPENAI_API_KEY') else 'āŒ FAILED'}") + + if perplexity_ok: + print(""" +šŸŽ‰ SUCCESS! Your AI research system is ready to: + - Analyze stocks with real-time data + - Answer complex investment questions + - Screen for opportunities + - Monitor market sentiment + +Next steps: + 1. Run the interactive CLI: python autonomous/research/research_cli.py + 2. Run the full demo: python research_demo.py + 3. Start the autonomous system: python autonomous_trader.py + """) + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/test_perplexity_simple.py b/test_perplexity_simple.py new file mode 100644 index 00000000..96680a2d --- /dev/null +++ b/test_perplexity_simple.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python +""" +Simplified test script to verify Perplexity API connectivity. +Works around import issues. +""" + +import asyncio +import os +import sys +from dotenv import load_dotenv + +# Load environment variables +load_dotenv() + +# Add directories to path +sys.path.insert(0, '.') +sys.path.insert(0, './autonomous') + + +async def test_perplexity_direct(): + """Test Perplexity API directly without complex imports""" + + print("=" * 60) + print("šŸ” Testing Perplexity Finance API (Direct)") + print("=" * 60) + + api_key = os.getenv('PERPLEXITY_API_KEY') + if not api_key: + print("āŒ PERPLEXITY_API_KEY not found in .env") + return False + + print(f"šŸ“Œ Using API key: {api_key[:15]}...") + + # Test with a simple API call + import aiohttp + import json + + url = "https://api.perplexity.ai/chat/completions" + headers = { + "Authorization": f"Bearer {api_key}", + "Content-Type": "application/json" + } + + payload = { + "model": "sonar", # Try the basic sonar model + "messages": [ + { + "role": "system", + "content": "You are a financial analyst. Be brief and specific." + }, + { + "role": "user", + "content": "What is NVIDIA's current stock price and P/E ratio? Reply with just the numbers." + } + ], + "max_tokens": 200, + "temperature": 0.1 + } + + try: + print("\n1. Sending test request to Perplexity API...") + async with aiohttp.ClientSession() as session: + async with session.post(url, headers=headers, json=payload) as response: + if response.status == 200: + data = await response.json() + content = data['choices'][0]['message']['content'] + print(f"āœ… API Response received:") + print(f" {content[:200]}") + print("\nāœ… Perplexity API is working!") + return True + else: + error = await response.text() + print(f"āŒ API Error (status {response.status}):") + print(f" {error[:200]}") + return False + + except Exception as e: + print(f"āŒ Connection error: {e}") + return False + + +async def test_research_functionality(): + """Test our research functionality""" + + print("\n" + "=" * 60) + print("šŸ¤– Testing Research Functionality") + print("=" * 60) + + try: + # Import just what we need + from autonomous.connectors.perplexity_finance import ( + PerplexityFinanceConnector, + AnalysisType, + ResearchDepth + ) + + print("\n1. Initializing Perplexity connector...") + connector = PerplexityFinanceConnector( + api_key=os.getenv('PERPLEXITY_API_KEY') + ) + print("āœ… Connector initialized") + + # Test stock analysis + print("\n2. Analyzing NVDA stock...") + analysis = await connector.analyze_stock( + "NVDA", + AnalysisType.FUNDAMENTAL, + ResearchDepth.QUICK + ) + + print(f""" +āœ… Analysis Complete: + Ticker: {analysis.ticker} + Rating: {analysis.rating} + Confidence: {analysis.confidence_score}% + + Analysis Preview: + {analysis.detailed_analysis[:200]}... + """) + + # Test market sentiment + print("\n3. Getting market sentiment...") + sentiment = await connector.get_market_sentiment() + print(f"āœ… Market Sentiment: {sentiment['analysis'][:150]}...") + + print("\nāœ… All research functions working!") + return True + + except ImportError as e: + print(f"āš ļø Import error: {e}") + print(" Some dependencies may be missing") + return False + except Exception as e: + print(f"āŒ Error: {e}") + import traceback + traceback.print_exc() + return False + + +async def main(): + """Run tests""" + + print(""" +╔════════════════════════════════════════════════════════════╗ +ā•‘ Perplexity Finance API Test (Simplified) ā•‘ +ā•šā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā•ā• + """) + + # Test 1: Direct API test + api_ok = await test_perplexity_direct() + + # Test 2: Research functionality (may have import issues) + if api_ok: + research_ok = await test_research_functionality() + else: + research_ok = False + + # Summary + print("\n" + "=" * 60) + print("šŸ“Š TEST SUMMARY") + print("=" * 60) + print(f"Perplexity API Connection: {'āœ… WORKING' if api_ok else 'āŒ FAILED'}") + print(f"Research Functions: {'āœ… WORKING' if research_ok else 'āš ļø PARTIAL' if api_ok else 'āŒ FAILED'}") + + if api_ok: + print(""" +šŸŽ‰ Your Perplexity API is connected and working! + +The API can: + - Answer investment questions + - Analyze stocks in real-time + - Provide market sentiment + - Screen for opportunities + +Note: Some import issues may exist with the full system, +but the core Perplexity functionality is operational. + """) + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file