优化输出
All checks were successful
构建并部署 AI Agent 服务 / deploy (push) Successful in 6m6s

This commit is contained in:
2026-05-09 01:51:18 +08:00
parent b30f7b00a7
commit 4c119073bc
18 changed files with 973 additions and 2941 deletions

View File

@@ -0,0 +1,91 @@
"""
响应格式化中间件
自动将 API 响应中的字符串或错误信息格式化为统一风格
"""
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse
from typing import Callable
from backend.app.core import get_formatter
class ResponseFormatterMiddleware(BaseHTTPMiddleware):
"""
响应格式化中间件
功能:
1. 统一响应包装
2. 错误信息格式化
3. 调试信息注入(可选)
"""
async def dispatch(self, request: Request, call_next: Callable):
response = await call_next(request)
return response
def format_error_response(
error_type: str,
error_message: str,
suggestions: list = None,
retry_count: int = 0,
max_retries: int = None
) -> str:
"""
格式化错误响应
Args:
error_type: 错误类型
error_message: 错误详情
suggestions: 建议操作列表
retry_count: 已重试次数
max_retries: 最大重试次数
Returns:
格式化后的 Markdown 文本
"""
formatter = get_formatter()
return formatter.render_error(
error_type=error_type,
error_message=error_message,
suggestions=suggestions,
retry_count=retry_count,
max_retries=max_retries
)
def format_success_response(
content: str,
title: str = None,
include_footer: bool = True
) -> str:
"""
格式化成功响应
Args:
content: 内容
title: 可选标题
include_footer: 是否包含页脚
Returns:
格式化后的 Markdown 文本
"""
formatter = get_formatter()
md = formatter.md
lines = []
if title:
lines.append(md.heading(title, 2))
lines.append("")
lines.append(content)
if include_footer:
lines.append("")
lines.append("---")
lines.append("*以上内容由 AI Agent 生成*")
return "\n".join(lines)