#!/usr/bin/env python3 """ TradingAgents Local Development Server Simple, working version for local testing """ import os import logging from datetime import datetime from typing import Optional import google.generativeai as genai from fastapi import FastAPI, HTTPException from fastapi.responses import HTMLResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import uvicorn # Configure logging logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) # Your API keys (you can also create a .env file) GEMINI_API_KEY = 'AIzaSyDg38EA0zJH6j1OpWPc-6oj-BqIMUSI3G8' FINNHUB_API_KEY = 'd2nb0r1r01qn3vmk9bi0d2nb0r1r01qn3vmk9big' # Initialize Gemini try: genai.configure(api_key=GEMINI_API_KEY) model = genai.GenerativeModel('gemini-2.0-flash-exp') logger.info("✅ Gemini AI initialized successfully") except Exception as e: logger.error(f"❌ Failed to initialize Gemini: {e}") model = None # FastAPI app app = FastAPI(title="TradingAgents Local Dev Server") # Enable CORS for local development app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) class AnalyzeRequest(BaseModel): query: str provider: Optional[str] = None @app.get("/", response_class=HTMLResponse) def home(): """Main web interface""" return ''' TradingAgents - Local Dev

🤖 TradingAgents

Local Development Server - AI Financial Analysis

🟢 Server Status: Running on localhost:8000 | AI Provider: Google Gemini | Mode: Development

Quick Examples:

''' @app.get("/health") def health(): """Health check endpoint""" return { "status": "healthy", "service": "TradingAgents Local Dev", "timestamp": datetime.now().isoformat(), "ai_provider": "Google Gemini", "port": 8000 } @app.post("/api/analyze") def analyze(request: AnalyzeRequest): """Analyze financial query using AI""" logger.info(f"📊 Analysis request: {request.query[:50]}...") logger.info(f"🤖 Provider requested: {request.provider or 'auto'}") try: if not model: raise HTTPException(status_code=500, detail="AI model not initialized") # Enhanced prompt for financial analysis prompt = f""" As a professional financial analyst, provide a comprehensive analysis for: {request.query} Please structure your response with: 1. Executive Summary 2. Key Market Insights 3. Technical Analysis (if applicable) 4. Risk Assessment 5. Recommendation Keep it clear, data-driven, and actionable. """ logger.info("🔄 Generating AI response...") response = model.generate_content(prompt) result = { "success": True, "analysis": response.text, "provider": "gemini", "fallback_occurred": False, "timestamp": datetime.now().isoformat() } logger.info("✅ Analysis completed successfully") return result except Exception as e: logger.error(f"❌ Analysis failed: {e}") raise HTTPException(status_code=500, detail=str(e)) def main(): """Run the development server""" print("🚀 TradingAgents Local Development Server") print("=" * 50) print("🌐 Frontend: http://localhost:8000") print("🔧 API Docs: http://localhost:8000/docs") print("💚 Health: http://localhost:8000/health") print("=" * 50) print("✅ Server starting... Press Ctrl+C to stop") uvicorn.run( app, host="127.0.0.1", # localhost only for development port=8000, reload=False, # disable reload to prevent issues log_level="info" ) if __name__ == "__main__": main()