293 lines
8.3 KiB
Go
Raw Normal View History

2025-10-18 14:45:13 +08:00
package gemini
import (
"bytes"
"fmt"
"io"
"net/http"
2025-10-31 15:29:17 +08:00
"regexp"
2025-10-18 14:45:13 +08:00
"strings"
"time"
2025-10-31 15:29:17 +08:00
"github.com/QuantumNous/new-api/common"
2025-10-18 14:45:13 +08:00
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/model"
"github.com/QuantumNous/new-api/relay/channel"
taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
2025-10-18 14:45:13 +08:00
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
"github.com/QuantumNous/new-api/setting/model_setting"
"github.com/gin-gonic/gin"
2025-10-18 21:37:39 +08:00
"github.com/pkg/errors"
2025-10-18 14:45:13 +08:00
)
// ============================
// Adaptor implementation
// ============================
type TaskAdaptor struct {
taskcommon.BaseBilling
2025-10-18 14:45:13 +08:00
ChannelType int
apiKey string
baseURL string
}
func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
a.ChannelType = info.ChannelType
a.baseURL = info.ChannelBaseUrl
a.apiKey = info.ApiKey
}
// ValidateRequestAndSetAction parses body, validates fields and sets default action.
func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionTextGenerate)
2025-10-18 14:45:13 +08:00
}
// BuildRequestURL constructs the Gemini API predictLongRunning endpoint for Veo.
2025-10-18 14:45:13 +08:00
func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
feat(task): add model redirection, per-call billing, and multipart retry fix for async tasks 1. Async task model redirection (aligned with sync tasks): - Integrate ModelMappedHelper in RelayTaskSubmit after model name determination, populating OriginModelName / UpstreamModelName on RelayInfo. - All task adaptors now send UpstreamModelName to upstream providers: - Gemini & Vertex: BuildRequestURL uses UpstreamModelName. - Doubao & Ali: BuildRequestBody conditionally overwrites body.Model. - Vidu, Kling, Hailuo, Jimeng: convertToRequestPayload accepts RelayInfo and unconditionally uses info.UpstreamModelName. - Sora: BuildRequestBody parses JSON and multipart bodies to replace the "model" field with UpstreamModelName. - Frontend log visibility: LogTaskConsumption and taskBillingOther now emit is_model_mapped / upstream_model_name in the "other" JSON field. - Billing safety: RecalculateTaskQuotaByTokens reads model name from BillingContext.OriginModelName (via taskModelName) instead of task.Data["model"], preventing billing leaks from upstream model names. 2. Per-call billing (TaskPricePatches lifecycle): - Rename TaskBillingContext.ModelName → OriginModelName; add PerCallBilling bool field, populated from TaskPricePatches at submission time. - settleTaskBillingOnComplete short-circuits when PerCallBilling is true, skipping both adaptor adjustments and token-based recalculation. - Remove ModelName from TaskSubmitResult; use relayInfo.OriginModelName consistently in controller/relay.go for billing context and logging. 3. Multipart retry boundary mismatch fix: - Root cause: after Sora (or OpenAI audio) rebuilds a multipart body with a new boundary and overwrites c.Request.Header["Content-Type"], subsequent calls to ParseMultipartFormReusable on retry would parse the cached original body with the wrong boundary, causing "NextPart: EOF". - Fix: ParseMultipartFormReusable now caches the original Content-Type in gin context key "_original_multipart_ct" on first call and reuses it for all subsequent parses, making multipart parsing retry-safe globally. - Sora adaptor reverted to the standard pattern (direct header set/get), which is now safe thanks to the root fix. 4. Tests: - task_billing_test.go: update makeTask to use OriginModelName; add PerCallBilling settlement tests (skip adaptor adjust, skip token recalc); add non-per-call adaptor adjustment test with refund verification.
2026-02-22 15:32:33 +08:00
modelName := info.UpstreamModelName
2025-10-18 14:45:13 +08:00
version := model_setting.GetGeminiVersionSetting(modelName)
return fmt.Sprintf(
"%s/%s/models/%s:predictLongRunning",
2025-10-18 14:45:13 +08:00
a.baseURL,
version,
modelName,
), nil
}
// BuildRequestHeader sets required headers.
func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("x-goog-api-key", a.apiKey)
return nil
}
// BuildRequestBody converts request into the Veo predictLongRunning format.
2025-10-18 14:45:13 +08:00
func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
v, ok := c.Get("task_request")
if !ok {
return nil, fmt.Errorf("request not found in context")
}
req, ok := v.(relaycommon.TaskSubmitReq)
if !ok {
return nil, fmt.Errorf("unexpected task_request type")
}
2025-10-18 14:45:13 +08:00
instance := VeoInstance{Prompt: req.Prompt}
if img := ExtractMultipartImage(c, info); img != nil {
instance.Image = img
} else if len(req.Images) > 0 {
if parsed := ParseImageInput(req.Images[0]); parsed != nil {
instance.Image = parsed
info.Action = constant.TaskActionGenerate
}
}
params := &VeoParameters{}
if err := taskcommon.UnmarshalMetadata(req.Metadata, params); err != nil {
2025-10-18 21:37:39 +08:00
return nil, errors.Wrap(err, "unmarshal metadata failed")
2025-10-18 14:45:13 +08:00
}
if params.DurationSeconds == 0 && req.Duration > 0 {
params.DurationSeconds = req.Duration
}
if params.Resolution == "" && req.Size != "" {
params.Resolution = SizeToVeoResolution(req.Size)
}
if params.AspectRatio == "" && req.Size != "" {
params.AspectRatio = SizeToVeoAspectRatio(req.Size)
}
params.Resolution = strings.ToLower(params.Resolution)
params.SampleCount = 1
body := VeoRequestPayload{
Instances: []VeoInstance{instance},
Parameters: params,
}
2025-10-18 14:45:13 +08:00
data, err := common.Marshal(body)
2025-10-18 14:45:13 +08:00
if err != nil {
return nil, err
}
return bytes.NewReader(data), nil
}
// DoRequest delegates to common helper.
func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
return channel.DoTaskApiRequest(a, c, info, requestBody)
}
// DoResponse handles upstream response, returns taskID etc.
func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", nil, service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
}
_ = resp.Body.Close()
var s submitResponse
if err := common.Unmarshal(responseBody, &s); err != nil {
2025-10-18 14:45:13 +08:00
return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
}
if strings.TrimSpace(s.Name) == "" {
return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing operation name"), "invalid_response", http.StatusInternalServerError)
}
taskID = taskcommon.EncodeLocalTaskID(s.Name)
2025-10-18 20:31:11 +08:00
ov := dto.NewOpenAIVideo()
ov.ID = info.PublicTaskID
ov.TaskID = info.PublicTaskID
2025-10-18 20:31:11 +08:00
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)
return taskID, responseBody, nil
2025-10-18 14:45:13 +08:00
}
func (a *TaskAdaptor) GetModelList() []string {
return []string{
"veo-3.0-generate-001",
"veo-3.0-fast-generate-001",
"veo-3.1-generate-preview",
"veo-3.1-fast-generate-preview",
}
2025-10-18 14:45:13 +08:00
}
func (a *TaskAdaptor) GetChannelName() string {
return "gemini"
}
// EstimateBilling returns OtherRatios based on durationSeconds and resolution.
func (a *TaskAdaptor) EstimateBilling(c *gin.Context, info *relaycommon.RelayInfo) map[string]float64 {
v, ok := c.Get("task_request")
if !ok {
return nil
}
req, ok := v.(relaycommon.TaskSubmitReq)
if !ok {
return nil
}
seconds := ResolveVeoDuration(req.Metadata, req.Duration, req.Seconds)
resolution := ResolveVeoResolution(req.Metadata, req.Size)
resRatio := VeoResolutionRatio(info.UpstreamModelName, resolution)
return map[string]float64{
"seconds": float64(seconds),
"resolution": resRatio,
}
}
// FetchTask polls task status via the Gemini operations GET endpoint.
func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
2025-10-18 14:45:13 +08:00
taskID, ok := body["task_id"].(string)
if !ok {
return nil, fmt.Errorf("invalid task_id")
}
upstreamName, err := taskcommon.DecodeLocalTaskID(taskID)
2025-10-18 14:45:13 +08:00
if err != nil {
return nil, fmt.Errorf("decode task_id failed: %w", err)
}
2025-10-18 20:31:11 +08:00
version := model_setting.GetGeminiVersionSetting("default")
2025-10-18 14:45:13 +08:00
url := fmt.Sprintf("%s/%s/%s", baseUrl, version, upstreamName)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("x-goog-api-key", key)
client, err := service.GetHttpClientWithProxy(proxy)
if err != nil {
return nil, fmt.Errorf("new proxy http client failed: %w", err)
}
return client.Do(req)
2025-10-18 14:45:13 +08:00
}
func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
var op operationResponse
if err := common.Unmarshal(respBody, &op); err != nil {
2025-10-18 14:45:13 +08:00
return nil, fmt.Errorf("unmarshal operation response failed: %w", err)
}
ti := &relaycommon.TaskInfo{}
if op.Error.Message != "" {
ti.Status = model.TaskStatusFailure
ti.Reason = op.Error.Message
ti.Progress = "100%"
return ti, nil
}
if !op.Done {
ti.Status = model.TaskStatusInProgress
ti.Progress = "50%"
return ti, nil
}
ti.Status = model.TaskStatusSuccess
ti.Progress = "100%"
ti.TaskID = taskcommon.EncodeLocalTaskID(op.Name)
if len(op.Response.GenerateVideoResponse.GeneratedVideos) > 0 {
if uri := op.Response.GenerateVideoResponse.GeneratedVideos[0].Video.URI; uri != "" {
ti.RemoteUrl = uri
}
}
2025-10-18 14:45:13 +08:00
return ti, nil
}
2025-10-31 15:29:17 +08:00
func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
upstreamTaskID := task.GetUpstreamTaskID()
upstreamName, err := taskcommon.DecodeLocalTaskID(upstreamTaskID)
2025-10-31 15:29:17 +08:00
if err != nil {
upstreamName = ""
}
modelName := extractModelFromOperationName(upstreamName)
if strings.TrimSpace(modelName) == "" {
modelName = "veo-3.0-generate-001"
}
video := dto.NewOpenAIVideo()
video.ID = task.TaskID
video.Model = modelName
video.Status = task.Status.ToVideoStatus()
video.SetProgressStr(task.Progress)
video.CreatedAt = task.CreatedAt
if task.FinishTime > 0 {
video.CompletedAt = task.FinishTime
} else if task.UpdatedAt > 0 {
video.CompletedAt = task.UpdatedAt
}
return common.Marshal(video)
}
2025-10-18 14:45:13 +08:00
// ============================
// helpers
// ============================
2025-10-31 15:29:17 +08:00
var modelRe = regexp.MustCompile(`models/([^/]+)/operations/`)
func extractModelFromOperationName(name string) string {
if name == "" {
return ""
}
if m := modelRe.FindStringSubmatch(name); len(m) == 2 {
return m[1]
}
if idx := strings.Index(name, "models/"); idx >= 0 {
s := name[idx+len("models/"):]
if p := strings.Index(s, "/operations/"); p > 0 {
return s[:p]
}
}
return ""
}