Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion model/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo)
privateData := TaskPrivateData{}
if relayInfo != nil && relayInfo.ChannelMeta != nil {
if relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeGemini ||
relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeVertexAi {
relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeVertexAi ||
relayInfo.ChannelMeta.ChannelType == constant.ChannelTypeXai {
privateData.Key = relayInfo.ChannelMeta.ApiKey
Comment on lines 176 to 179

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Persist xAI's resolved header overrides, not just the task key.

Adding privateData.Key for ChannelTypeXai is necessary, but it still leaves async follow-up requests short of the full auth context. relay/channel/task/xai/adaptor.go rebuilds polling requests from the bearer key alone, so any submit-time {client_header:*} / header-override auth will be lost after task creation.

Based on learnings, async video task flows should reuse the effective authentication context (API key + header overrides) captured at task submit time rather than re-deriving it from channel.Key at each call site.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@model/task.go` around lines 176 - 179, When handling ChannelTypeXai in the
task creation branch that currently only sets privateData.Key =
relayInfo.ChannelMeta.ApiKey, also persist the submit-time header overrides (the
effective auth context) into the task's private data so async follow-ups can
reuse them; specifically, copy relayInfo.ChannelMeta's client header /
header-override field(s) (e.g., client_header, header_overrides) into a new or
existing privateData field (e.g., privateData.HeaderOverrides or
privateData.ClientHeaders) so relay/channel/task/xai/adaptor.go can reconstruct
requests from the full auth context rather than just channel.Key.

}
if relayInfo.UpstreamModelName != "" {
Expand Down
283 changes: 283 additions & 0 deletions relay/channel/task/xai/adaptor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,283 @@
package xai

import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
"time"

"github.com/QuantumNous/new-api/common"
"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"
relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)

// ============================
// Adaptor implementation
// ============================

type TaskAdaptor struct {
taskcommon.BaseBilling
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)
}

func (a *TaskAdaptor) BuildRequestURL(_ *relaycommon.RelayInfo) (string, error) {
return fmt.Sprintf("%s/v1/videos/generations", a.baseURL), nil
}

// EstimateBilling returns OtherRatios based on duration seconds.
// xAI video currently reuses the per-call model price as the per-second price.
func (a *TaskAdaptor) EstimateBilling(c *gin.Context, _ *relaycommon.RelayInfo) map[string]float64 {
v, ok := c.Get("task_request")
if !ok {
return nil
}
req, ok := v.(relaycommon.TaskSubmitReq)
if !ok {
return nil
}

// 1.获取视频时长
actualSeconds := ResolveDurationSeconds(req.Metadata, req.Duration, req.Seconds)
if actualSeconds <= 0 {
actualSeconds = 1
}
// 2. 获取分辨率
resolution := ResolveResolution(req.Metadata, req.Size)

// 3. 决定分辨率倍率
resMultiplier := 1.0 // 默认倍率
if strings.Contains(resolution, "480") {
resMultiplier = 0.5 // 0.1 * 0.5 = 0.05
} else if strings.Contains(resolution, "720") {
resMultiplier = 0.7 // 0.1 * 0.7 = 0.07
} else if strings.Contains(resolution, "1080") {
// 假设你以后想加 1080p 是 $0.1/秒
resMultiplier = 1.0
}
// 4. 统计图片数量并计算图片计费单位
// 统计普通请求里的图片
imageCount := len(req.Images)

// 如果有文件上传形式的图片,也算一张
// (参考你代码里的 ExtractMultipartImageURL 逻辑)
if imageURL := ExtractMultipartImageURL(c, nil); imageURL != "" {
imageCount++
}

// 每张图 $0.002,基准 $0.1,所以每张图合 0.02 个单位
imageBillingUnits := float64(imageCount) * 0.02
Comment on lines +79 to +90

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Align image billing with the single-image request shape and stated price.

This path bills len(req.Images) plus a multipart upload, but BuildRequestBody() only ever forwards one image (input_reference or req.Images[0]). It also uses 0.02 base units per image, which is $0.002 when the base unit is $0.1; the PR objective says $0.02 per image. As written, multi-image requests are billed for inputs that are dropped, and each billed image is still underpriced by 10x.

💸 Proposed fix
-	// 统计普通请求里的图片
-	imageCount := len(req.Images)
+	imageCount := 0
+	if len(req.Images) > 0 {
+		imageCount = 1
+	}

-	// 如果有文件上传形式的图片,也算一张
-	// (参考你代码里的 ExtractMultipartImageURL 逻辑)
+	// multipart input takes precedence over req.Images[0]
 	if imageURL := ExtractMultipartImageURL(c, nil); imageURL != "" {
-		imageCount++
+		imageCount = 1
 	}

-	// 每张图 $0.002,基准 $0.1,所以每张图合 0.02 个单位
-	imageBillingUnits := float64(imageCount) * 0.02
+	// 每张图 $0.02,基准 $0.1,所以每张图合 0.2 个单位
+	imageBillingUnits := float64(imageCount) * 0.2
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// 4. 统计图片数量并计算图片计费单位
// 统计普通请求里的图片
imageCount := len(req.Images)
// 如果有文件上传形式的图片,也算一张
// (参考你代码里的 ExtractMultipartImageURL 逻辑)
if imageURL := ExtractMultipartImageURL(c, nil); imageURL != "" {
imageCount++
}
// 每张图 $0.002,基准 $0.1,所以每张图合 0.02 个单位
imageBillingUnits := float64(imageCount) * 0.02
// 4. 统计图片数量并计算图片计费单位
imageCount := 0
if len(req.Images) > 0 {
imageCount = 1
}
// multipart input takes precedence over req.Images[0]
if imageURL := ExtractMultipartImageURL(c, nil); imageURL != "" {
imageCount = 1
}
// 每张图 $0.02,基准 $0.1,所以每张图合 0.2 个单位
imageBillingUnits := float64(imageCount) * 0.2
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/task/xai/adaptor.go` around lines 79 - 90, The code currently
counts all entries in req.Images plus a multipart-upload image and multiplies by
0.02 units each, but BuildRequestBody only ever forwards a single image and 0.02
units is 10x too small (0.02 USD per image with a $0.1 base unit equals 0.2
units). Change the logic to treat images as at-most-one-billable input: compute
a boolean like hasImage := len(req.Images) > 0 || ExtractMultipartImageURL(c,
nil) != "" and set imageCount = 1 if hasImage else 0, then compute
imageBillingUnits := float64(imageCount) * 0.2 (0.2 units per image). Update
references to imageCount/imageBillingUnits and keep ExtractMultipartImageURL and
BuildRequestBody behavior unchanged.


// 计算总倍率 计费价格是每秒
totalUnits := (float64(actualSeconds) * resMultiplier) + imageBillingUnits

return map[string]float64{
"total_units": totalUnits,
}
}

func (a *TaskAdaptor) BuildRequestHeader(_ *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+a.apiKey)
return nil
}

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")
}

meta := &requestMetadata{}
if err := taskcommon.UnmarshalMetadata(req.Metadata, meta); err != nil {
return nil, errors.Wrap(err, "unmarshal metadata failed")
}

duration := ResolveDurationSeconds(req.Metadata, req.Duration, req.Seconds)
if meta.Duration != nil && *meta.Duration > 0 {
duration = *meta.Duration
}

aspectRatio := ResolveAspectRatio(req.Metadata, req.Size)
if strings.TrimSpace(meta.AspectRatio) != "" {
aspectRatio = strings.TrimSpace(meta.AspectRatio)
}

resolution := ResolveResolution(req.Metadata, req.Size)
if strings.TrimSpace(meta.Resolution) != "" {
resolution = strings.ToLower(strings.TrimSpace(meta.Resolution))
}

var imageURL string
if u := ExtractMultipartImageURL(c, info); u != "" {
imageURL = u
} else if len(req.Images) > 0 {
if u := ParseImageURL(req.Images[0]); u != "" {
imageURL = u
info.Action = constant.TaskActionGenerate
}
}

body := VideoGenerationRequest{
Model: info.UpstreamModelName,
Prompt: req.Prompt,
Duration: duration,
AspectRatio: aspectRatio,
Resolution: resolution,
Seed: meta.Seed,
}
if strings.TrimSpace(imageURL) != "" {
body.Image = &VideoInputImageURL{URL: imageURL}
}

data, err := common.Marshal(body)
if err != nil {
return nil, err
}
return bytes.NewReader(data), nil
}

func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
return channel.DoTaskApiRequest(a, c, info, requestBody)
}

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 {
return "", nil, service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
}
if strings.TrimSpace(s.RequestID) == "" {
return "", nil, service.TaskErrorWrapper(fmt.Errorf("missing request_id"), "invalid_response", http.StatusInternalServerError)
}

ov := dto.NewOpenAIVideo()
ov.ID = info.PublicTaskID
ov.TaskID = info.PublicTaskID
ov.CreatedAt = time.Now().Unix()
ov.Model = info.OriginModelName
c.JSON(http.StatusOK, ov)

return s.RequestID, responseBody, nil
}

func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
taskID, ok := body["task_id"].(string)
if !ok || strings.TrimSpace(taskID) == "" {
return nil, fmt.Errorf("invalid task_id")
}

uri := fmt.Sprintf("%s/v1/videos/%s", baseUrl, taskID)
req, err := http.NewRequest(http.MethodGet, uri, nil)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", "Bearer "+key)

client, err := service.GetHttpClientWithProxy(proxy)
if err != nil {
return nil, fmt.Errorf("new proxy http client failed: %w", err)
}
return client.Do(req)
}

func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
var sr statusResponse
if err := common.Unmarshal(respBody, &sr); err != nil {
return nil, fmt.Errorf("unmarshal status response failed: %w", err)
}

ti := &relaycommon.TaskInfo{}
status := strings.ToLower(strings.TrimSpace(sr.Status))
switch status {
case "pending", "queued":
ti.Status = model.TaskStatusQueued
ti.Progress = taskcommon.ProgressQueued
case "processing", "in_progress", "generating":
ti.Status = model.TaskStatusInProgress
ti.Progress = taskcommon.ProgressInProgress
case "done", "completed", "success":
ti.Status = model.TaskStatusSuccess
ti.Progress = taskcommon.ProgressComplete
if sr.Video != nil && strings.TrimSpace(sr.Video.URL) != "" {
ti.Url = strings.TrimSpace(sr.Video.URL)
}
case "expired":
ti.Status = model.TaskStatusFailure
ti.Progress = taskcommon.ProgressComplete
ti.Reason = "task expired"
case "failed", "error":
ti.Status = model.TaskStatusFailure
ti.Progress = taskcommon.ProgressComplete
if sr.Error != nil && strings.TrimSpace(sr.Error.Message) != "" {
ti.Reason = strings.TrimSpace(sr.Error.Message)
} else {
ti.Reason = "task failed"
}
default:
// Unknown status — let caller decide how to handle it
}
return ti, nil
}

func (a *TaskAdaptor) ConvertToOpenAIVideo(task *model.Task) ([]byte, error) {
video := dto.NewOpenAIVideo()
video.ID = task.TaskID
video.TaskID = task.TaskID
video.Model = task.Properties.OriginModelName
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
}
if task.Status == model.TaskStatusFailure && strings.TrimSpace(task.FailReason) != "" {
video.Error = &dto.OpenAIVideoError{
Message: task.FailReason,
Code: "task_failed",
}
}
return common.Marshal(video)
}

func (a *TaskAdaptor) GetModelList() []string {
return []string{"grok-imagine-video"}
}

func (a *TaskAdaptor) GetChannelName() string {
return "xai"
}
44 changes: 44 additions & 0 deletions relay/channel/task/xai/adaptor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package xai

import (
"net/http/httptest"
"testing"

relaycommon "github.com/QuantumNous/new-api/relay/common"
"github.com/gin-gonic/gin"
)

func TestEstimateBillingUsesDurationSeconds(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)

ctx.Set("task_request", relaycommon.TaskSubmitReq{
Duration: 10,
})

adaptor := &TaskAdaptor{}
ratios := adaptor.EstimateBilling(ctx, nil)
if ratios["seconds"] != 10 {
t.Fatalf("expected seconds ratio 10, got %v", ratios["seconds"])
}
}

func TestEstimateBillingMetadataOverridesRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)

ctx.Set("task_request", relaycommon.TaskSubmitReq{
Duration: 6,
Metadata: map[string]any{
"duration": 12,
},
})

adaptor := &TaskAdaptor{}
ratios := adaptor.EstimateBilling(ctx, nil)
if ratios["seconds"] != 12 {
t.Fatalf("expected seconds ratio 12, got %v", ratios["seconds"])
}
}
42 changes: 42 additions & 0 deletions relay/channel/task/xai/dto.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package xai

// VideoGenerationRequest is the request body for xAI video generation API.
// Docs: POST /v1/videos/generations
type VideoGenerationRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
Duration int `json:"duration,omitempty"`
AspectRatio string `json:"aspect_ratio,omitempty"`
Resolution string `json:"resolution,omitempty"`
Seed *int `json:"seed,omitempty"`
Image *VideoInputImageURL `json:"image,omitempty"`
}

type VideoInputImageURL struct {
URL string `json:"url"`
}

type submitResponse struct {
RequestID string `json:"request_id"`
}

type statusResponse struct {
Status string `json:"status"`
Model string `json:"model,omitempty"`
Video *struct {
URL string `json:"url,omitempty"`
Duration int `json:"duration,omitempty"`
RespectModeration *bool `json:"respect_moderation,omitempty"`
} `json:"video,omitempty"`
Error *struct {
Message string `json:"message,omitempty"`
Code string `json:"code,omitempty"`
} `json:"error,omitempty"`
}

type requestMetadata struct {
Duration *int `json:"duration,omitempty"`
AspectRatio string `json:"aspect_ratio,omitempty"`
Resolution string `json:"resolution,omitempty"`
Seed *int `json:"seed,omitempty"`
}
Loading
Loading