gateway_server.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. """
  2. A2A IM Gateway Server
  3. 启动 Gateway 服务器,提供 Agent 注册和消息路由
  4. """
  5. import logging
  6. import uvicorn
  7. from fastapi import FastAPI
  8. from fastapi.middleware.cors import CORSMiddleware
  9. from gateway.core.channels.loader import load_enabled_channels
  10. from gateway.core.executor import TaskManager, build_executor_router
  11. from gateway.core.lifecycle import TraceManager, WorkspaceManager
  12. from gateway.core.registry import AgentRegistry
  13. from gateway.core.router import GatewayRouter
  14. # 配置日志
  15. logging.basicConfig(
  16. level=logging.INFO,
  17. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  18. )
  19. logger = logging.getLogger(__name__)
  20. def create_gateway_app() -> FastAPI:
  21. """创建 Gateway FastAPI 应用"""
  22. app = FastAPI(
  23. title="A2A IM Gateway",
  24. description="Agent 即时通讯网关",
  25. version="1.0.0",
  26. )
  27. # 添加 CORS 中间件
  28. app.add_middleware(
  29. CORSMiddleware,
  30. allow_origins=["*"],
  31. allow_credentials=True,
  32. allow_methods=["*"],
  33. allow_headers=["*"],
  34. )
  35. # 创建 Registry
  36. registry = AgentRegistry(heartbeat_timeout=60)
  37. # 创建 Gateway Router
  38. gateway_router = GatewayRouter(registry)
  39. # 注册 Gateway 路由
  40. app.include_router(gateway_router.router)
  41. for router in load_enabled_channels():
  42. app.include_router(router)
  43. _wm = WorkspaceManager.from_env()
  44. _tm = TraceManager.from_env(_wm)
  45. _task_mgr = TaskManager.from_env(_wm, _tm)
  46. app.include_router(build_executor_router(_task_mgr))
  47. logger.info("Gateway Executor mounted at /gateway/executor")
  48. # 启动和关闭事件
  49. @app.on_event("startup")
  50. async def startup():
  51. await registry.start()
  52. logger.info("Gateway started")
  53. @app.on_event("shutdown")
  54. async def shutdown():
  55. await registry.stop()
  56. logger.info("Gateway stopped")
  57. # 健康检查
  58. @app.get("/health")
  59. async def health():
  60. return {"status": "ok"}
  61. return app
  62. def main():
  63. """启动 Gateway 服务器"""
  64. app = create_gateway_app()
  65. # 启动服务器
  66. uvicorn.run(
  67. app,
  68. host="0.0.0.0",
  69. port=8000,
  70. log_level="info",
  71. )
  72. if __name__ == "__main__":
  73. main()