Files
model-gateway/service/model_task_start_service.go
T

74 lines
2.3 KiB
Go

package service
import (
"context"
"encoding/json"
"fmt"
"model-gateway/dao"
"model-gateway/model/dto"
"model-gateway/service/httpclient"
modelUtils "model-gateway/service/utils"
"time"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/util/gconv"
)
var ModelTaskStart = &modelTaskStartService{}
type modelTaskStartService struct{}
// CreateTask 创建任务
func (s *modelTaskStartService) CreateTask(ctx context.Context, req *dto.CallModelTaskStartReq) (res *dto.ModelCallRes, err error) {
startTime := time.Now()
id := req.Id
modelInfo := req.ModelInfo
newRequestParams := req.RequestParams
// 6) 模型请求
modelRespBody, err := httpclient.ModelHttpNormalRequest(ctx, modelInfo.BaseURL, modelInfo.RequestHeadMapping, modelInfo.HttpMethod, newRequestParams)
if err != nil {
return nil, fmt.Errorf("模型请求失败: %v", err)
}
if modelRespBody == nil {
return nil, fmt.Errorf("模型返回参数是空")
}
// 7) 更新视频任务信息(统一字段路径 GetByPath 基于该对象读取)
var respObj map[string]any
if err = json.Unmarshal(modelRespBody, &respObj); err != nil {
return nil, fmt.Errorf("模型返回参数解析失败:%v", err)
}
updateModelReq := dto.UpdateModelTaskStartReq{
Id: id,
OriginalResponseParams: respObj,
}
docMsg := new(dto.ModelCallRes)
docMsg.TaskId = id
// 统一解析模型错误(兼容 OpenAI 嵌套 error / 扁平 code 两种形态),无错误返回空串
if _, docMsg.ErrorMsg, err = parseModelError(modelRespBody); err != nil {
return nil, fmt.Errorf("模型返回参数解析失败:%v", err)
}
if docMsg.ErrorMsg != "" {
updateModelReq.ErrorMsg = docMsg.ErrorMsg
}
if docMsg.ErrorMsg == "" {
taskIDPath := modelUtils.CleanFieldPath(modelInfo.AsyncTaskMapping.TaskId)
docMsg.Content = map[string]any{
"respBody": modelUtils.GetByPathValue(respObj, taskIDPath),
}
}
if !g.IsEmpty(docMsg.Content) {
updateModelReq.ResponseParams = docMsg.Content
updateModelReq.TaskId = gconv.String(docMsg.Content["respBody"])
}
updateModelReq.DurationSeconds = int64(time.Since(startTime).Seconds())
// 8) 更新模型视频任务信息
_, err = dao.ModelTaskStart.Update(ctx, &updateModelReq)
if err != nil {
return nil, fmt.Errorf("更新模型视频任务信息失败: %v", err)
}
return docMsg, nil
}