controller.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # -*- coding: utf-8 -*-
  2. from fastapi import APIRouter, Depends, Path, Body, WebSocket
  3. from fastapi.responses import JSONResponse, StreamingResponse
  4. from app.common.response import StreamResponse, SuccessResponse
  5. from app.common.request import PaginationService
  6. from app.core.base_params import PaginationQueryParam
  7. from app.core.dependencies import AuthPermission
  8. from app.core.logger import log
  9. from app.api.v1.module_system.auth.schema import AuthSchema
  10. from app.core.router_class import OperationLogRoute
  11. from .service import McpService
  12. from .schema import McpCreateSchema, McpUpdateSchema, ChatQuerySchema, McpQueryParam
  13. AIRouter = APIRouter(route_class=OperationLogRoute, prefix="/ai", tags=["MCP智能助手"])
  14. @AIRouter.post("/chat", summary="智能对话", description="与MCP智能助手进行对话")
  15. async def chat_controller(
  16. query: ChatQuerySchema,
  17. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:chat"]))
  18. ) -> StreamingResponse:
  19. """
  20. 智能对话接口
  21. 参数:
  22. - query (ChatQuerySchema): 聊天查询模型
  23. 返回:
  24. - StreamingResponse: 流式响应,每次返回一个聊天响应
  25. """
  26. user_name = auth.user.name if auth.user else "未知用户"
  27. log.info(f"用户 {user_name} 发起智能对话: {query.message[:50]}...")
  28. async def generate_response():
  29. try:
  30. async for chunk in McpService.chat_query(query=query):
  31. # 确保返回的是字节串
  32. if chunk:
  33. yield chunk.encode('utf-8') if isinstance(chunk, str) else chunk
  34. except Exception as e:
  35. log.error(f"流式响应出错: {str(e)}")
  36. yield f"抱歉,处理您的请求时出现了错误: {str(e)}".encode('utf-8')
  37. return StreamResponse(generate_response(), media_type="text/plain; charset=utf-8")
  38. @AIRouter.get("/detail/{id}", summary="获取 MCP 服务器详情", description="获取 MCP 服务器详情")
  39. async def detail_controller(
  40. id: int = Path(..., description="MCP ID"),
  41. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:query"]))
  42. ) -> JSONResponse:
  43. """
  44. 获取 MCP 服务器详情接口
  45. 参数:
  46. - id (int): MCP 服务器ID
  47. 返回:
  48. - JSONResponse: 包含 MCP 服务器详情的 JSON 响应
  49. """
  50. result_dict = await McpService.detail_service(auth=auth, id=id)
  51. log.info(f"获取 MCP 服务器详情成功 {id}")
  52. return SuccessResponse(data=result_dict, msg="获取 MCP 服务器详情成功")
  53. @AIRouter.get("/list", summary="查询 MCP 服务器列表", description="查询 MCP 服务器列表")
  54. async def list_controller(
  55. page: PaginationQueryParam = Depends(),
  56. search: McpQueryParam = Depends(),
  57. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:query"]))
  58. ) -> JSONResponse:
  59. """
  60. 查询 MCP 服务器列表接口
  61. 参数:
  62. - page (PaginationQueryParam): 分页查询参数模型
  63. - search (McpQueryParam): 查询参数模型
  64. - auth (AuthSchema): 认证信息模型
  65. 返回:
  66. - JSONResponse: 包含 MCP 服务器列表的 JSON 响应
  67. """
  68. result_dict_list = await McpService.list_service(auth=auth, search=search, order_by=page.order_by)
  69. result_dict = await PaginationService.paginate(data_list=result_dict_list, page_no=page.page_no, page_size=page.page_size)
  70. log.info(f"查询 MCP 服务器列表成功")
  71. return SuccessResponse(data=result_dict, msg="查询 MCP 服务器列表成功")
  72. @AIRouter.post("/create", summary="创建 MCP 服务器", description="创建 MCP 服务器")
  73. async def create_controller(
  74. data: McpCreateSchema,
  75. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:create"]))
  76. ) -> JSONResponse:
  77. """
  78. 创建 MCP 服务器接口
  79. 参数:
  80. - data (McpCreateSchema): 创建 MCP 服务器模型
  81. - auth (AuthSchema): 认证信息模型
  82. 返回:
  83. - JSONResponse: 包含创建 MCP 服务器结果的 JSON 响应
  84. """
  85. result_dict = await McpService.create_service(auth=auth, data=data)
  86. log.info(f"创建 MCP 服务器成功: {result_dict}")
  87. return SuccessResponse(data=result_dict, msg="创建 MCP 服务器成功")
  88. @AIRouter.put("/update/{id}", summary="修改 MCP 服务器", description="修改 MCP 服务器")
  89. async def update_controller(
  90. data: McpUpdateSchema,
  91. id: int = Path(..., description="MCP ID"),
  92. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:update"]))
  93. ) -> JSONResponse:
  94. """
  95. 修改 MCP 服务器接口
  96. 参数:
  97. - data (McpUpdateSchema): 修改 MCP 服务器模型
  98. - id (int): MCP 服务器ID
  99. - auth (AuthSchema): 认证信息模型
  100. 返回:
  101. - JSONResponse: 包含修改 MCP 服务器结果的 JSON 响应
  102. """
  103. result_dict = await McpService.update_service(auth=auth, id=id, data=data)
  104. log.info(f"修改 MCP 服务器成功: {result_dict}")
  105. return SuccessResponse(data=result_dict, msg="修改 MCP 服务器成功")
  106. @AIRouter.delete("/delete", summary="删除 MCP 服务器", description="删除 MCP 服务器")
  107. async def delete_controller(
  108. ids: list[int] = Body(..., description="ID列表"),
  109. auth: AuthSchema = Depends(AuthPermission(["module_application:ai:delete"]))
  110. ) -> JSONResponse:
  111. """
  112. 删除 MCP 服务器接口
  113. 参数:
  114. - ids (list[int]): MCP 服务器ID列表
  115. - auth (AuthSchema): 认证信息模型
  116. 返回:
  117. - JSONResponse: 包含删除 MCP 服务器结果的 JSON 响应
  118. """
  119. await McpService.delete_service(auth=auth, ids=ids)
  120. log.info(f"删除 MCP 服务器成功: {ids}")
  121. return SuccessResponse(msg="删除 MCP 服务器成功")
  122. @AIRouter.websocket("/ws/chat", name="WebSocket聊天")
  123. async def websocket_chat_controller(
  124. websocket: WebSocket,
  125. ):
  126. """
  127. WebSocket聊天接口
  128. ws://127.0.0.1:8001/api/v1/ai/mcp/ws/chat
  129. """
  130. await websocket.accept()
  131. try:
  132. while True:
  133. data = await websocket.receive_text()
  134. # 流式发送响应
  135. try:
  136. async for chunk in McpService.chat_query(query=ChatQuerySchema(message=data)):
  137. if chunk:
  138. await websocket.send_text(chunk)
  139. except Exception as e:
  140. log.error(f"处理聊天查询出错: {str(e)}")
  141. await websocket.send_text(f"抱歉,处理您的请求时出现了错误: {str(e)}")
  142. except Exception as e:
  143. log.error(f"WebSocket聊天出错: {str(e)}")
  144. finally:
  145. await websocket.close()