You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
swarms/api/app.py

34 lines
1.2 KiB

2 years ago
from fastapi import FastAPI, HTTPException, Depends
from fastapi_cache.decorator import cache
from fastapi_cache.coder import JsonCoder
from fastapi_cache import FastAPICache
from aioredis import Redis
2 years ago
from pydantic import BaseModel
2 years ago
from swarms.swarms import swarm
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
2 years ago
class SwarmInput(BaseModel):
2 years ago
api_key: str
2 years ago
objective: str
2 years ago
app = FastAPI()
@app.on_event("startup")
async def startup():
redis = Redis(host="localhost", port=6379)
FastAPICache.init(RedisBackend(redis), prefix="fastapi-cache", coder=JsonCoder())
await FastAPILimiter.init("redis://localhost:6379")
2 years ago
2 years ago
@app.post("/chat", dependencies=[Depends(RateLimiter(times=2, minutes=1))])
@cache(expire=60) # Cache results for 1 minute
2 years ago
async def run_swarms(swarm_input: SwarmInput):
try:
results = swarm(swarm_input.api_key, swarm_input.objective)
if not results:
2 years ago
raise HTTPException(status_code=500, detail="Failed to run swarms")
2 years ago
return {"results": results}
except ValueError as ve:
raise HTTPException(status_code=400, detail=str(ve))
except Exception as e:
2 years ago
raise HTTPException(status_code=500, detail=str(e))