You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

140 lines
4.8 KiB

package migu
import (
"encoding/json"
"net/http"
"runtime/debug"
"yunyan/lego/sys/log"
"yunyan/sys/migu"
)
// ===================== 普通聊天接口的请求 / 响应结构 =====================
type (
// ChatRequest 聊天请求体
ChatRequest struct {
Message string `json:"message"` // 本次问话(必填)
History []Message `json:"history,omitempty"` // 历史对话(可选)
DeviceId string `json:"deviceId,omitempty"` // 设备ID(可选,亦可用 X-Device-Id 头)
SessionId string `json:"sessionId,omitempty"` // 会话ID(可选,亦可用 X-Session-Id 头)
Stream bool `json:"stream"` // 是否流式
}
Message struct {
Role string `json:"role"` // user / assistant / system
Content string `json:"content"` // 文本内容
}
// ChatChunk 流式单帧;只填充当前帧命中的字段
ChatChunk struct {
Reasoning string `json:"reasoning,omitempty"` // 模型思考增量
Content string `json:"content,omitempty"` // 文本增量
Card *migu.Content `json:"card,omitempty"` // 结构化卡片(音乐等,含 type+data)
RecommendPrompts []string `json:"recommendPrompts,omitempty"` // 追问提示词
FinishReason string `json:"finishReason,omitempty"` // 结束原因:空=未结束/正常;fail/filter
}
// ChatResponse 非流式完整响应(把整段对话聚合为一个结构化结果)
ChatResponse struct {
ReqId string `json:"reqId"`
SessionId string `json:"sessionId"`
Reasoning string `json:"reasoning,omitempty"` // 拼接后的完整思考
Content string `json:"content"` // 拼接后的完整文本
Cards []migu.Content `json:"cards,omitempty"` // 全部结构化卡片(音乐等)
RecommendPrompts []string `json:"recommendPrompts,omitempty"` // 全部追问提示词
FinishReason string `json:"finishReason"` // 结束原因
}
)
// convertChunk 把一条咪咕 StreamResp 转换为 ChatChunk;无可用内容返回 nil。
func convertChunk(sr *migu.StreamResp) *ChatChunk {
if sr == nil || len(sr.Choices) == 0 {
return nil
}
c := sr.Choices[0]
chunk := &ChatChunk{FinishReason: c.FinishReason}
hit := c.FinishReason != ""
// 模型思考
if c.Delta.ReasoningContent != nil && c.Delta.ReasoningContent.Text != "" {
chunk.Reasoning = c.Delta.ReasoningContent.Text
hit = true
}
// 文本 / 结构化卡片
if c.Delta.Content != nil {
switch c.Delta.Content.Type {
case migu.ContentTypeText:
var td migu.TextData
if err := json.Unmarshal(c.Delta.Content.Data, &td); err == nil && td.Text != "" {
chunk.Content = td.Text
hit = true
}
case migu.ContentTypeH5, migu.ContentTypeTemplate:
// 结构化卡片(H5/模板,音乐等)原样透传 type+data
chunk.Card = c.Delta.Content
hit = true
}
}
// 追问提示词
for _, p := range c.Delta.RecommendPrompts {
if p.Text != "" {
chunk.RecommendPrompts = append(chunk.RecommendPrompts, p.Text)
}
}
if len(chunk.RecommendPrompts) > 0 {
hit = true
}
if !hit {
return nil
}
return chunk
}
// ===================== HTTP 中间件 =====================
func withRecover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Errorf("migu panic recovered in %s %s: %v", r.Method, r.URL.Path, err)
if stack := debug.Stack(); len(stack) > 0 {
log.Errorf("stack trace: %s", string(stack))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"error":"internal server error"}`))
}
}()
next.ServeHTTP(w, r)
})
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Device-Id, X-Session-Id")
w.Header().Set("Access-Control-Allow-Credentials", "true")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
// writeError 以统一 JSON 格式返回错误
func writeError(w http.ResponseWriter, status int, message string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": message})
}