gateway_server.py 1.7 KB

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