Spaces:
Paused
Paused
Download app.py from arudradey/agent-loop: direct link, hf CLI and curl.
- Browser
- Download file 4.17 kB
-
https://huggingface.co/spaces/arudradey/agent-loop/resolve/main/app.py
- Command line
-
hf download hf://spaces/arudradey/agent-loop/app.py
-
curl -L -o app.py https://huggingface.co/spaces/arudradey/agent-loop/resolve/main/app.py
4.17 kB
| import os | |
| import json | |
| import platform | |
| import psutil | |
| from datetime import datetime | |
| from typing import Optional | |
| from pathlib import Path | |
| from fastapi import FastAPI, HTTPException, Query | |
| from fastapi.responses import HTMLResponse, StreamingResponse | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from solana_quant import solana_quant | |
| from small_ai import stream_quant_response, get_ai_status | |
| from storage_manager import ( | |
| get_storage_info, | |
| list_storage_files, | |
| read_storage_file, | |
| write_storage_file, | |
| delete_storage_file, | |
| STORAGE_DIR, | |
| ) | |
| app = FastAPI( | |
| title="Solana Quantum Hedge Fund API", | |
| description="Autonomous Quantitative Hedge Fund and Local Small AI on Solana", | |
| version="2.0.0", | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| STATIC_DIR = Path(__file__).parent / "static" | |
| STATIC_DIR.mkdir(parents=True, exist_ok=True) | |
| app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") | |
| class QuantQueryRequest(BaseModel): | |
| prompt: str | |
| max_tokens: Optional[int] = 256 | |
| temperature: Optional[float] = 0.7 | |
| class TradeOrderRequest(BaseModel): | |
| symbol: str | |
| side: str | |
| amount_usdc: float | |
| strategy: Optional[str] = "AI_MOMENTUM" | |
| async def serve_dashboard(): | |
| index_file = STATIC_DIR / "index.html" | |
| if index_file.exists(): | |
| return HTMLResponse(content=index_file.read_text(encoding="utf-8")) | |
| return HTMLResponse("<h1>Solana Hedge Fund is running</h1>") | |
| async def health_check(): | |
| return { | |
| "status": "healthy", | |
| "service": "Solana Quantum Hedge Fund", | |
| "timestamp": datetime.utcnow().isoformat(), | |
| "storage": str(STORAGE_DIR) | |
| } | |
| async def get_market_data(): | |
| return solana_quant.get_market_overview() | |
| async def get_trades(): | |
| return {"trades": solana_quant.get_trade_history()} | |
| async def execute_trade(req: TradeOrderRequest): | |
| if req.amount_usdc <= 0: | |
| raise HTTPException(status_code=400, detail="Invalid trade amount") | |
| trade = solana_quant.execute_simulated_trade( | |
| symbol=req.symbol, | |
| side=req.side, | |
| amount_usdc=req.amount_usdc, | |
| strategy=req.strategy or "AI_MOMENTUM" | |
| ) | |
| return {"status": "success", "trade": trade} | |
| async def ai_status(): | |
| return get_ai_status() | |
| async def analyze_with_local_ai(req: QuantQueryRequest): | |
| if not req.prompt or not req.prompt.strip(): | |
| raise HTTPException(status_code=400, detail="Prompt cannot be empty") | |
| def event_stream(): | |
| try: | |
| yield f"event: start\ndata: {json.dumps({'status': 'streaming'})}\n\n" | |
| for token in stream_quant_response( | |
| prompt=req.prompt.strip(), | |
| max_tokens=req.max_tokens or 256, | |
| temperature=req.temperature or 0.7 | |
| ): | |
| yield f"event: token\ndata: {json.dumps({'token': token})}\n\n" | |
| yield f"event: done\ndata: {json.dumps({'status': 'complete'})}\n\n" | |
| except Exception as e: | |
| yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" | |
| return StreamingResponse( | |
| event_stream(), | |
| media_type="text/event-stream", | |
| headers={ | |
| "Cache-Control": "no-cache", | |
| "Connection": "keep-alive", | |
| "X-Accel-Buffering": "no" | |
| } | |
| ) | |
| async def get_storage_files(subpath: str = Query("", description="Relative subpath")): | |
| try: | |
| files = list_storage_files(subpath) | |
| info = get_storage_info() | |
| return {"subpath": subpath, "files": files, "storage_info": info} | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True) | |