-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
204 lines (160 loc) · 5.95 KB
/
Copy pathmain.py
File metadata and controls
204 lines (160 loc) · 5.95 KB
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
import sys
import os
import asyncio
from contextlib import asynccontextmanager
from typing import Dict, Any
from datetime import datetime
from fastapi import FastAPI, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
import uvicorn
import logging
# Add src to path for imports
sys.path.insert(0, os.path.dirname(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from src.orchestration.supervisor import SupervisorNode
from src.core.redis_config import RedisConnectionManager
from src.api.models import SystemStatusResponse
# Logging setup
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(name)s %(levelname)s %(message)s'
)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup
logger.info("Starting AgentWeaver server...")
# Initialize Redis connection
app.state.redis_manager = RedisConnectionManager()
logger.info("Redis manager is ready")
# Initialize supervisor
app.state.supervisor = SupervisorNode()
logger.info("Supervisor is ready")
# Initialize WebSocket manager
from src.services.websocket_manager import WebSocketManager
from src.services.websocket_integration import integration_service
app.state.ws_manager = WebSocketManager()
# Connect integration service to WebSocket manager
integration_service.set_websocket_manager(app.state.ws_manager)
logger.info("WebSocket system is ready")
logger.info("AgentWeaver server is fully operational")
yield
# Shutdown
logger.info("Shutting down AgentWeaver server...")
# Cleanup connections
if hasattr(app.state, 'ws_manager'):
await app.state.ws_manager.disconnect_all()
logger.info("All WebSocket connections closed")
logger.info("AgentWeaver shutdown complete")
# FastAPI application
app = FastAPI(
title="AgentWeaver API",
description="Multi-agent orchestration platform",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc"
)
# CORS for frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all origins for now
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/", tags=["Root"])
async def root():
return {
"message": "AgentWeaver API is running",
"version": "1.0.0",
"docs": "/docs",
"health": "/health"
}
@app.get("/health", tags=["Health"], response_model=SystemStatusResponse)
async def health_check():
try:
# Check Redis
redis_status = "connected" if app.state.redis_manager.test_connection() else "disconnected"
# Check supervisor
supervisor_status = "initialized" if hasattr(app.state, 'supervisor') else "not_initialized"
# Check WebSocket manager
ws_status = "initialized" if hasattr(app.state, 'ws_manager') else "not_initialized"
ws_connections = len(app.state.ws_manager.active_connections) if hasattr(app.state, 'ws_manager') else 0
return SystemStatusResponse(
status="healthy",
uptime=0.0, # Track actual uptime
version="1.0.0",
timestamp=datetime.now(),
services={
"redis": redis_status,
"supervisor": supervisor_status,
"websocket_manager": ws_status
},
metrics={
"active_websocket_connections": ws_connections,
"active_agents": 0, # Get from supervisor
"running_workflows": 0 # Get from supervisor
}
)
except Exception as e:
logger.error(f"Health check failed: {e}")
raise HTTPException(status_code=503, detail=f"Service unhealthy: {str(e)}")
# Include routers
from src.api.routers import agents, workflows, websocket
app.include_router(agents.router)
app.include_router(workflows.router)
app.include_router(websocket.router)
@app.get("/api/info", tags=["Info"])
async def api_info():
return {
"api": "AgentWeaver",
"version": "1.0.0",
"endpoints": {
"agents": "/agents - Manage agents",
"workflows": "/workflows - Control workflows",
"websocket": "/ws/updates - Real-time updates"
},
"status": "ready"
}
from pydantic import BaseModel
import time
from src.agents.stock_analyst import run_pipeline
class ChatRequest(BaseModel):
message: str = "Give me a snapshot of AAPL right now."
def _make_workflow_id(prefix: str = "chat") -> str:
return f"{prefix}_{int(time.time() * 1000)}"
@app.post("/api/chat", tags=["Chat"])
async def chat(req: ChatRequest):
"""Start a multi-agent stock analysis workflow for the user's question.
Returns immediately with a workflow_id. Real progress streams over the
/ws/updates WebSocket and the final assistant reply arrives as the
`synthesis` workflow step event.
"""
query = (req.message or "").strip() or "Give me a snapshot of AAPL right now."
workflow_id = _make_workflow_id("chat")
asyncio.create_task(run_pipeline(workflow_id, query))
return {"workflow_id": workflow_id, "status": "started", "query": query}
@app.post("/api/test/demo-workflow", tags=["Testing"])
async def trigger_demo_workflow():
"""Backward-compat alias: triggers the chat pipeline with a default AAPL question."""
workflow_id = _make_workflow_id("demo")
asyncio.create_task(
run_pipeline(workflow_id, "Give me a snapshot of AAPL right now.")
)
return {
"message": "Demo workflow started",
"workflow_id": workflow_id,
"check_dashboard": "Watch your dashboard for real-time updates!",
}
if __name__ == "__main__":
# Run server
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info"
)