Spaces:
Sleeping
Sleeping
File size: 5,597 Bytes
27baee9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | """FastAPI backend for DeFi Agents simulation dashboard."""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional, Dict, Any
import json
from api.supabase_client import SupabaseClient
from core.simulation import Simulation
from core.analyzer import Analyzer
app = FastAPI(
title="DeFi Agents API",
description="Multi-agent LLM simulation in DeFi markets",
version="0.1.0"
)
# CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize clients
supabase = None
try:
supabase = SupabaseClient()
except ValueError:
print("Warning: Supabase not configured")
# ==================== Pydantic Models ====================
class RunRequest(BaseModel):
num_agents: int = 5
turns_per_run: int = 10
class RunResponse(BaseModel):
run_number: int
metrics: Dict[str, Any]
agents: List[Dict[str, Any]]
class AgentActionRequest(BaseModel):
agent_name: str
action: str
payload: Dict = {}
# ==================== Health Endpoints ====================
@app.get("/health")
def health_check():
"""Health check endpoint."""
return {
"status": "healthy",
"supabase": "connected" if supabase and supabase.health_check() else "disconnected"
}
# ==================== Run Endpoints ====================
@app.post("/api/runs")
def create_run(request: RunRequest):
"""Start a new simulation run."""
try:
sim = Simulation(
num_agents=request.num_agents,
turns_per_run=request.turns_per_run,
supabase=supabase
)
metrics = sim.run()
# Get agent states
agent_data = []
for agent in sim.agents:
agent_data.append({
"name": agent.name,
"token_a": agent.token_a,
"token_b": agent.token_b,
"profit": agent.calculate_profit(),
"strategy": agent.infer_strategy()
})
return RunResponse(
run_number=sim.current_run_number - 1,
metrics=metrics,
agents=agent_data
)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/runs")
def get_all_runs():
"""Get all runs."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
runs = supabase.get_all_runs()
return {"runs": runs}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/runs/{run_id}")
def get_run_detail(run_id: int):
"""Get detailed run data."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
detail = supabase.get_run_detail(run_id)
return detail
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ==================== Metrics Endpoints ====================
@app.get("/api/metrics/{run_id}")
def get_run_metrics(run_id: int):
"""Get metrics for a specific run."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
metrics = supabase.get_metrics(run_id)
if not metrics:
raise HTTPException(status_code=404, detail="Run not found")
return metrics
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/analysis/trends")
def get_trends():
"""Get trend analysis across all runs."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
runs = supabase.get_all_runs()
run_data = [r for r in runs if r.get("status") == "completed"]
metrics = []
for r in run_data:
run_metrics = supabase.get_metrics(r["id"])
if run_metrics:
metrics.append(run_metrics)
trends = Analyzer.detect_trends(metrics)
return trends
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ==================== Thinking/Reasoning Endpoints ====================
@app.get("/api/thinking/{action_id}")
def get_thinking_trace(action_id: int):
"""Get the thinking trace for a specific action."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
thinking = supabase.get_thinking_trace(action_id)
if thinking is None:
raise HTTPException(status_code=404, detail="Action not found")
return {"thinking": thinking}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
# ==================== Analysis Endpoints ====================
@app.get("/api/analysis/arms-race/{run_id}")
def get_arms_race_analysis(run_id: int):
"""Detect arms race patterns in a run."""
if not supabase:
raise HTTPException(status_code=503, detail="Supabase not configured")
try:
actions = supabase.get_actions(run_id)
analysis = Analyzer.detect_arms_races(actions)
return analysis
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
def run_server():
"""Run the FastAPI server."""
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
print("Starting DeFi Agents API server on http://0.0.0.0:8000")
run_server()
|