from typing import Optional
import time
import uvicorn
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from swarms import Agent
app = FastAPI(
title="Swarms Agent API",
description="REST API for Swarms agents",
version="1.0.0",
)
class AgentRequest(BaseModel):
task: str
agent_name: Optional[str] = "default"
max_loops: Optional[int] = 1
temperature: Optional[float] = None
class AgentResponse(BaseModel):
success: bool
result: str
agent_name: str
task: str
execution_time: Optional[float] = None
def create_agent(agent_name: str = "default") -> Agent:
return Agent(
agent_name=agent_name,
agent_description="Versatile AI agent for various tasks",
system_prompt=(
"You are a helpful AI assistant. Be clear, accurate, and concise."
),
model_name="claude-sonnet-4-20250514",
dynamic_temperature_enabled=True,
max_loops=1,
dynamic_context_window=True,
)
@app.get("/")
async def root():
return {"message": "Swarms Agent API is running!", "status": "healthy"}
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "Swarms Agent API", "version": "1.0.0"}
@app.post("/agent/run", response_model=AgentResponse)
async def run_agent(request: AgentRequest):
try:
start_time = time.time()
agent = create_agent(request.agent_name)
result = agent.run(task=request.task, max_loops=request.max_loops)
return AgentResponse(
success=True,
result=str(result),
agent_name=request.agent_name,
task=request.task,
execution_time=time.time() - start_time,
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Agent execution failed: {e}")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)