gateway_server.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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.feishu.manager import (
  10. build_channels_api_router,
  11. channel_manager_from_env,
  12. )
  13. from gateway.core.registry import AgentRegistry
  14. from gateway.core.router import GatewayRouter
  15. # 配置日志
  16. logging.basicConfig(
  17. level=logging.INFO,
  18. format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
  19. )
  20. logger = logging.getLogger(__name__)
  21. def create_gateway_app() -> FastAPI:
  22. """创建 Gateway FastAPI 应用"""
  23. app = FastAPI(
  24. title="A2A IM Gateway",
  25. description="Agent 即时通讯网关",
  26. version="1.0.0",
  27. )
  28. # 添加 CORS 中间件
  29. app.add_middleware(
  30. CORSMiddleware,
  31. allow_origins=["*"],
  32. allow_credentials=True,
  33. allow_methods=["*"],
  34. allow_headers=["*"],
  35. )
  36. # 创建 Registry
  37. registry = AgentRegistry(heartbeat_timeout=60)
  38. # 创建 Gateway Router
  39. gateway_router = GatewayRouter(registry)
  40. # 注册 Gateway 路由
  41. app.include_router(gateway_router.router)
  42. channel_manager = channel_manager_from_env()
  43. app.include_router(build_channels_api_router(channel_manager))
  44. # 启动和关闭事件
  45. @app.on_event("startup")
  46. async def startup():
  47. await registry.start()
  48. logger.info("Gateway started")
  49. @app.on_event("shutdown")
  50. async def shutdown():
  51. await registry.stop()
  52. logger.info("Gateway stopped")
  53. # 健康检查
  54. @app.get("/health")
  55. async def health():
  56. return {"status": "ok"}
  57. return app
  58. def main():
  59. """启动 Gateway 服务器"""
  60. app = create_gateway_app()
  61. # 启动服务器
  62. uvicorn.run(
  63. app,
  64. host="0.0.0.0",
  65. port=8000,
  66. log_level="info",
  67. )
  68. if __name__ == "__main__":
  69. main()