diff --git a/.gitignore b/.gitignore index 3369bad9..2043c597 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,10 @@ eval_results/ eval_data/ *.egg-info/ .env + +# API Database +api_database.db +api_database.db-* +*.db +*.db-shm +*.db-wal diff --git a/api/API_IMPLEMENTATION_SUMMARY.md b/api/API_IMPLEMENTATION_SUMMARY.md index 0c4ee0d9..d25e63f1 100644 --- a/api/API_IMPLEMENTATION_SUMMARY.md +++ b/api/API_IMPLEMENTATION_SUMMARY.md @@ -274,13 +274,13 @@ Future improvements could include: The FastAPI Trading Agents API is fully implemented and ready for use. It provides a robust, scalable foundation for frontend applications to interact with the TradingAgents multi-agent system. ### Getting Started -1. Read `API_QUICKSTART.md` for setup instructions -2. Check `api/README.md` for full documentation -3. Run `api/example_client.py` to see it in action +1. Read `START_API.md` or `API_QUICKSTART.md` for setup instructions +2. Check `README.md` for full documentation +3. Run `example_client.py` to see it in action 4. Start building your frontend! ### Support -- API Documentation: http://localhost:8000/docs -- Project README: `api/README.md` -- Quick Start: `API_QUICKSTART.md` +- API Documentation: http://localhost:8001/docs +- Project README: `README.md` +- Quick Start: `START_API.md` or `API_QUICKSTART.md` diff --git a/api/QUICKSTART.md b/api/QUICKSTART.md new file mode 100644 index 00000000..6719c321 --- /dev/null +++ b/api/QUICKSTART.md @@ -0,0 +1,40 @@ +# Trading Agents API - Quickest Start + +## One-Command Setup + +```bash +cd TradingAgents && pip install -r requirements.txt && python -m api.main +``` + +That's it! The API auto-initializes on first run. + +## What Happens on First Run + +1. ✅ Database is created automatically +2. ✅ Default API key is generated +3. ✅ API key is displayed in the console +4. ✅ Server starts at http://localhost:8001 + +**Save the API key from the console output!** + +## Test It + +```bash +# Replace YOUR_API_KEY with the key from console +curl -X POST "http://localhost:8001/api/v1/analyses" \ + -H "X-API-Key: YOUR_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "ticker": "AAPL", + "analysis_date": "2025-10-21", + "selected_analysts": ["market"], + "research_depth": 1 + }' +``` + +## Next Steps + +- View interactive docs: http://localhost:8001/docs +- Read full guide: `START_API.md` +- Manage API keys: `python -m api.cli_admin list-keys` + diff --git a/api/START_API.md b/api/START_API.md index 475e354d..ebb97015 100644 --- a/api/START_API.md +++ b/api/START_API.md @@ -1,83 +1,96 @@ -# Quick Start - Trading Agents API +# Trading Agents API - Quick Start -## 1. Install Dependencies (if not already done) +Get your API running in **2 simple steps**! + +## Prerequisites + +- Python 3.10+ +- Environment variables set (OPENAI_API_KEY, ALPHA_VANTAGE_API_KEY) + +## Setup + +### Step 1: Install Dependencies ```bash cd TradingAgents pip install -r requirements.txt ``` -## 2. Initialize Database & Create API Key - -```bash -# Initialize the database -python -m api.cli_admin init-database - -# Create your first API key -python -m api.cli_admin create-key "My Development Key" -``` - -**IMPORTANT**: Save the API key that's displayed! You'll need it for all requests. - -## 3. Start the API +### Step 2: Start the API ```bash python -m api.main ``` -Or use the startup script: -```bash -./run_api.sh +**That's it!** 🎉 + +### First Run Auto-Setup + +On first run, the API automatically: +- ✅ Creates the database +- ✅ Generates a default API key +- ✅ Displays the key in console logs + +**SAVE THE API KEY!** You'll see output like this: + +``` +====================================================================== +FIRST RUN DETECTED - Setting up Trading Agents API +====================================================================== + +✓ Database initialized successfully! +✓ Default API key created! + +====================================================================== +YOUR API KEY (save this, it won't be shown again): + + BgA2YyMlxYus2aIGJ5KGCPQO-q8k05WxTirayVZgPrM + +====================================================================== +Use this key in the X-API-Key header for all API requests. +Manage keys with: python -m api.cli_admin +====================================================================== ``` -The API will start at: **http://localhost:8001** +## Test Your API -## 4. Test It +Open your browser: +- **Interactive Docs**: http://localhost:8001/docs +- **Alternative Docs**: http://localhost:8001/redoc -Open your browser to see the interactive API documentation: -- **Swagger UI**: http://localhost:8001/docs -- **ReDoc**: http://localhost:8001/redoc - -## 5. Create Your First Analysis - -Using curl (replace `YOUR_API_KEY` with the key from step 2): +Or test with curl: ```bash curl -X POST "http://localhost:8001/api/v1/analyses" \ - -H "X-API-Key: YOUR_API_KEY" \ + -H "X-API-Key: YOUR_API_KEY_HERE" \ -H "Content-Type: application/json" \ -d '{ "ticker": "AAPL", "analysis_date": "2025-10-21", - "selected_analysts": ["market", "news"], + "selected_analysts": ["market"], "research_depth": 1 }' ``` -You'll get back an `analysis_id`. Use it to check status: +## Alternative Startup Methods ```bash -curl "http://localhost:8001/api/v1/analyses/YOUR_ANALYSIS_ID/status" \ - -H "X-API-Key: YOUR_API_KEY" -``` - -## Configuration (Optional) - -Set environment variables before starting: - -```bash -# Maximum concurrent analyses (default: 4) -export MAX_CONCURRENT_ANALYSES=8 - -# Your LLM API keys (if not already set) -export OPENAI_API_KEY="your-key" -export ALPHA_VANTAGE_API_KEY="your-key" - -# Then start the API +# Option 1: Direct Python (default port 8001) python -m api.main + +# Option 2: Startup script +./run_api.sh + +# Option 3: Custom port +API_PORT=8002 python -m api.main + +# Option 4: Using uvicorn directly +uvicorn api.main:app --host 0.0.0.0 --port 8001 ``` -## Common Commands +## Managing API Keys + +After initial setup, manage keys with the admin CLI: ```bash # List all API keys @@ -86,29 +99,57 @@ python -m api.cli_admin list-keys # Create a new API key python -m api.cli_admin create-key "Frontend App" -# Revoke an API key (use ID from list-keys) +# Revoke an API key python -m api.cli_admin revoke-key 1 + +# Activate a revoked key +python -m api.cli_admin activate-key 1 ``` -## Full Documentation +## Configuration (Optional) -- Quick Start: `API_QUICKSTART.md` -- Full API Docs: `api/README.md` -- Implementation Details: `API_IMPLEMENTATION_SUMMARY.md` +Set these environment variables before starting: + +```bash +# Maximum concurrent analyses (default: 4) +export MAX_CONCURRENT_ANALYSES=8 + +# Custom database location +export API_DATABASE_URL="sqlite:///./my_custom.db" + +# Custom port +export API_PORT=8002 +``` ## Troubleshooting **"Invalid or inactive API key"** -- Make sure you're using the exact key from step 2 -- Check: `python -m api.cli_admin list-keys` +- Use the exact key from the first-run console output +- Check active keys: `python -m api.cli_admin list-keys` + +**Port already in use** +- Change port: `API_PORT=8002 python -m api.main` + +**Database already exists but no API key** +- Create one: `python -m api.cli_admin create-key "My Key"` **Import errors** -- Make sure you're in the TradingAgents directory +- Ensure you're in the TradingAgents directory - Use: `python -m api.main` (not `python api/main.py`) -**Port 8001 already in use** -- Change port: `API_PORT=8002 python -m api.main` -- Or: `python -m uvicorn api.main:app --port 8002` +## Full Documentation -That's it! Your API is ready to use. 🚀 +- Quick Start: `QUICKSTART.md` (one-command setup) +- This Guide: `START_API.md` (you are here) +- Detailed Guide: `API_QUICKSTART.md` +- Full API Docs: `README.md` +- Implementation: `API_IMPLEMENTATION_SUMMARY.md` +## What's Next? + +1. Check out the interactive docs at http://localhost:8001/docs +2. Try creating an analysis via the API +3. Build your frontend integration +4. Read the full documentation in `README.md` + +Your Trading Agents API is ready! 🚀 diff --git a/api/main.py b/api/main.py index 9c944e54..14903293 100644 --- a/api/main.py +++ b/api/main.py @@ -30,11 +30,53 @@ logger = logging.getLogger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): """Lifespan context manager for startup and shutdown events.""" + import os + from pathlib import Path + # Startup logger.info("Initializing Trading Agents API...") + + # Check if this is first run (database doesn't exist) + db_path = Path(os.getenv("API_DATABASE_URL", "sqlite:///./api_database.db").replace("sqlite:///", "")) + is_first_run = not db_path.exists() + + # Initialize database init_db() + + # If first run, create a default API key + if is_first_run: + from api.auth import create_api_key + from api.database import SessionLocal + + logger.info("=" * 70) + logger.info("FIRST RUN DETECTED - Setting up Trading Agents API") + logger.info("=" * 70) + + db = SessionLocal() + try: + plain_key, db_key = create_api_key(db, "Default API Key") + logger.info("") + logger.info("✓ Database initialized successfully!") + logger.info("✓ Default API key created!") + logger.info("") + logger.info("=" * 70) + logger.info("YOUR API KEY (save this, it won't be shown again):") + logger.info("") + logger.info(f" {plain_key}") + logger.info("") + logger.info("=" * 70) + logger.info("Use this key in the X-API-Key header for all API requests.") + logger.info("Manage keys with: python -m api.cli_admin") + logger.info("=" * 70) + logger.info("") + except Exception as e: + logger.error(f"Failed to create default API key: {e}") + finally: + db.close() + get_executor() logger.info("Trading Agents API started successfully") + logger.info(f"API Documentation: http://localhost:{os.getenv('API_PORT', '8001')}/docs") yield @@ -92,7 +134,7 @@ if __name__ == "__main__": import uvicorn import os - port = int(os.getenv("API_PORT", "8002")) # Default to 8001 instead of 8000 + port = int(os.getenv("API_PORT", "8002")) uvicorn.run( "api.main:app", diff --git a/api_database.db b/api_database.db index 66e359b1..0cb53a10 100644 Binary files a/api_database.db and b/api_database.db differ diff --git a/run_api.sh b/run_api.sh index cd953f24..f2bfa9ba 100755 --- a/run_api.sh +++ b/run_api.sh @@ -3,13 +3,12 @@ echo "Starting Trading Agents API..." echo "" -echo "Make sure you have:" -echo "1. Installed dependencies: pip install -r requirements.txt" -echo "2. Initialized database: python -m api.cli_admin init-database" -echo "3. Created an API key: python -m api.cli_admin create-key 'My Key'" +echo "First time running? The API will automatically:" +echo " • Initialize the database" +echo " • Create a default API key (save it!)" echo "" -echo "API will be available at: http://localhost:8001" -echo "API Documentation: http://localhost:8001/docs" +echo "API will be available at: http://localhost:8002" +echo "API Documentation: http://localhost:8002/docs" echo "" cd "$(dirname "$0")"