From a0710f555860252f8e1c4f5f9795d9e005dcbcd2 Mon Sep 17 00:00:00 2001 From: Marvin Gabler Date: Tue, 21 Oct 2025 19:04:51 +0200 Subject: [PATCH] update --- .gitignore | 7 ++ api/API_IMPLEMENTATION_SUMMARY.md | 12 +-- api/QUICKSTART.md | 40 ++++++++ api/START_API.md | 161 +++++++++++++++++++----------- api/main.py | 44 +++++++- api_database.db | Bin 102400 -> 126976 bytes run_api.sh | 11 +- 7 files changed, 202 insertions(+), 73 deletions(-) create mode 100644 api/QUICKSTART.md 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 66e359b1884f24435dff549851118feb5b34d29a..0cb53a10c9951c12edae775a1d14f04d2c22106e 100644 GIT binary patch delta 16210 zcmeI3--{eqcE?ASWXWw?z5cPz{<3`ovOJP{T0OrsKMV;YS@H@=mKaGa4i4Jt?&|LH zRCl$js%P8|r1X*mOdwWdFbkV_V@Mz`P831>YMhrW7H zZ06w~AADh7cKhb*`@ZsfYkMEP_QbC~`};3#Y;4Tz`TDy*U)gi`)(@Y2^r1%7?T3Eq zH}CxD$$R0??d1Hz^2$POVR>%8Hn%Wu=BK_{YhI1LrXSyV;cGu^f9qiR z6V{%2ru-k}e=GmI{L}JJ%6H2@Du1%)wV97^-hBVg$2XoTmwDjn3LoD%#>bOKZvEsB zp59wM^s`$B-ah|$`I++9%8!>HDL+`AIrQ&`{`Jt$?mTARI&^aX-aUJ&RejFQ>9bPN z=keqEJa$ZgjhCwCsJeO$iv$$PVZ_0cb)7v27A)sw4> zYs(9d@{2<=)tU02mw)5XUmTi!ckRf7GuJkr zeOhW?JiICeFRw1IF0E|(UJ~_!Ui);^OM~9PzxLet$>k3}uI;IvI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ns-(p0U`>SqDVC+eT;knBQc8J2}L=%IWQcU7U+?%xqk%=^vE9ES{37vYRBAtnw}KU3PM znlqN3a>QJ5j673f7w_v`BFLC|GYb{wDD&fcIWlJUx5c|O=k=bc-z*frnIO<)BL+sfgE1bjFN!C zDibk}$f$WZ`zf7*U4bpkT_DbyBaWm)uGQ6^V!P+K_n@0BmOH?UMk-r}plazjW)_3M zgrM<29AtoN83uAP5r@d2ZCgNTKtEFAMvM8Y5-c2`U$aCTbAH`1T1G2jPwY)Mz}zX} za8O)o1;r(Ix%^bl!Lxz5$Lqu?Bdj_e%;B|VR8Y4URz{*PI=pUGrAOQAW8H#wLoN~tY{QXC#X<&fA2*Gt)BV>{vksInne4M)1yw)X$OP`3z->v<@W`G}RuejypBTt>sx zFlHN`9Zw6&Cg-gb=jGH&nKVBvK*SlF>2rP;ji6kAj>;vr6P!00sMnn9M2(!ZM1&Jv zHPD?<-i%9*?(#)-Auok-7oD9L#cCIFTG+k3$HaEZJmS9yZ$rm@%p;sRe?nnQX%K3e zBU-X#&z3lT9O)J>%&ZYOSJ>fz@CZ^77g+5*KV$EPejew$2@SaiiWMvJe+G&Uj8DK9 zfehkGan(@#(Vzw0E~m`VRx1FZ00)4*k9tTi@HDN{7eqfxCA-eGM;B876$%wa(dzWB pdJgjous$(UxoZn+-)>&~OD6G-693s*I9J}6S66Dan>YXVzX1&+%@u4 kOrfgN4Gb79w;wQIG|~raW-+y}G~1TI_zB82F*30P04ye1Q~&?~ 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")"