103 lines
2.5 KiB
Go
103 lines
2.5 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"tcm-agent/internal/service"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// ========================================================================
|
||
// EnhancerHandler —— 知识增强接口的 HTTP 处理器
|
||
// ========================================================================
|
||
// 对接 PHP 端的 TcmAgentClient,提供 POST /api/v1/agent/enhance 端点。
|
||
// PHP 端拿到的响应里包含 content + steps,会把 steps 写入 xk_ai_generation_step。
|
||
// ========================================================================
|
||
|
||
// EnhancerHandler 知识增强接口处理器
|
||
type EnhancerHandler struct {
|
||
svc *service.EnhancerService
|
||
}
|
||
|
||
// NewEnhancerHandler 构造函数
|
||
func NewEnhancerHandler(svc *service.EnhancerService) *EnhancerHandler {
|
||
return &EnhancerHandler{svc: svc}
|
||
}
|
||
|
||
// Enhance HTTP 入口
|
||
//
|
||
// POST /api/v1/agent/enhance
|
||
//
|
||
// 请求体(与 service.EnhanceRequest 一致):
|
||
//
|
||
// {
|
||
// "scene": "medical_record",
|
||
// "context": "痰湿中阻 煎法",
|
||
// "messages": [
|
||
// {"role": "system", "content": "..."},
|
||
// {"role": "user", "content": "..."}
|
||
// ],
|
||
// "kb_enabled": true,
|
||
// "top_k": 5,
|
||
// "provider": "" // 空 = 按 scene 路由
|
||
// }
|
||
//
|
||
// 响应:
|
||
//
|
||
// {
|
||
// "code": 200,
|
||
// "data": {
|
||
// "content": "...", // 第一份成功(兼容)
|
||
// "contents": ["..."], // 仅成功内容
|
||
// "results": [{index,ok,content,error,steps}], // 多份时按槽位
|
||
// "provider": "spark",
|
||
// "model": "spark-max",
|
||
// "steps": [...],
|
||
// "total_ms": 1234
|
||
// }
|
||
// }
|
||
func (h *EnhancerHandler) Enhance(c *gin.Context) {
|
||
if h.svc == nil {
|
||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||
"code": 503,
|
||
"message": "知识增强服务未初始化",
|
||
})
|
||
return
|
||
}
|
||
|
||
var req service.EnhanceRequest
|
||
if err := c.ShouldBindJSON(&req); err != nil {
|
||
c.JSON(http.StatusBadRequest, gin.H{
|
||
"code": 400,
|
||
"message": "参数错误: " + err.Error(),
|
||
})
|
||
return
|
||
}
|
||
|
||
// 校验:messages 至少 1 条
|
||
if len(req.Messages) == 0 {
|
||
c.JSON(http.StatusBadRequest, gin.H{
|
||
"code": 400,
|
||
"message": "messages 不能为空",
|
||
})
|
||
return
|
||
}
|
||
|
||
resp, err := h.svc.Enhance(c.Request.Context(), &req)
|
||
if err != nil {
|
||
// 业务失败:仍然把已收集的 steps 返回,让 PHP 能记录失败过程
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 500,
|
||
"message": err.Error(),
|
||
"data": resp,
|
||
})
|
||
return
|
||
}
|
||
|
||
c.JSON(http.StatusOK, gin.H{
|
||
"code": 200,
|
||
"data": resp,
|
||
})
|
||
}
|