fix(*): 模型请求协议 - 支持模型独立选协议并修正视频多参考请求

This commit is contained in:
ddCat committed 2026-07-28 23:05:15 +08:00
1 parent 7093b4e161
commit e3c501620d
20 files changed
+691 -190

No files matched your search

+25 -20
View File
@@ -663,7 +663,9 @@ func proxySystemRequest(c *gin.Context, svc *service.Service, user *model.User,
switch channel.InterfaceType { switch channel.InterfaceType {
case model.ChannelInterfaceOpenAIImage: case model.ChannelInterfaceOpenAIImage:
capability = "image" capability = "image"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo: case model.ChannelInterfaceOpenAIAudio:
capability = "audio"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceGeminiVeo:
capability = "video" capability = "video"
} }
order, err := svc.ReserveProxyBilling(user.ID, channel.ID, strings.TrimPrefix(modelName, "models/"), capability, c.GetHeader("X-Canvas-Scene"), c.GetHeader("X-Idempotency-Key"), proxyRequestVideoSeconds(c.GetHeader("Content-Type"), body)) order, err := svc.ReserveProxyBilling(user.ID, channel.ID, strings.TrimPrefix(modelName, "models/"), capability, c.GetHeader("X-Canvas-Scene"), c.GetHeader("X-Idempotency-Key"), proxyRequestVideoSeconds(c.GetHeader("Content-Type"), body))
@@ -752,7 +754,9 @@ func apiCallLog(user *model.User, channel *model.ModelChannel, billingOrderID st
switch channel.InterfaceType { switch channel.InterfaceType {
case model.ChannelInterfaceOpenAIImage: case model.ChannelInterfaceOpenAIImage:
capability = "image" capability = "image"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo: case model.ChannelInterfaceOpenAIAudio:
capability = "audio"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceGeminiVeo:
capability = "video" capability = "video"
} }
requestKind := "create" requestKind := "create"
@@ -763,24 +767,25 @@ func apiCallLog(user *model.User, channel *model.ModelChannel, billingOrderID st
} }
} }
return model.ApiCallLog{ return model.ApiCallLog{
UserID: user.ID, UserID: user.ID,
ChannelID: channel.ID, ChannelID: channel.ID,
BillingOrderID: billingOrderID, BillingOrderID: billingOrderID,
Source: "system-channel", Source: "system-channel",
Capability: capability, Capability: capability,
RequestKind: requestKind, RequestKind: requestKind,
Billable: method == http.MethodPost, Billable: method == http.MethodPost,
APIFormat: channel.APIFormat, APIFormat: channel.APIFormat,
Method: method, Method: method,
Path: path, Path: path,
Model: readPayloadModel(body), Model: readPayloadModel(body),
Status: status, Status: status,
StatusCode: statusCode, StatusCode: statusCode,
DurationMs: duration.Milliseconds(), DurationMs: duration.Milliseconds(),
Error: errorText, Error: errorText,
ConcurrencyLimit: concurrencyLimit, ConcurrencyLimit: concurrencyLimit,
UpstreamURL: target, UpstreamURL: target,
RequestBody: service.SanitizeAPICallPayload(body, contentType), RequestContentType: contentType,
RequestBody: service.SanitizeAPICallPayload(body, contentType),
} }
} }
+18 -7
View File
@@ -23,10 +23,13 @@ import (
) )
var ( var (
runtimeService *service.Service runtimeService *service.Service
geminiGeneratePath = regexp.MustCompile(`^/models/([^/:]+):(generateContent|streamGenerateContent)$`) geminiGeneratePath = regexp.MustCompile(`^/models/([^/:]+):(generateContent|streamGenerateContent)$`)
customGeminiRelayPath = regexp.MustCompile(`(?:^|/)models/[^/:]+:(generateContent|streamGenerateContent)$`) customGeminiRelayPath = regexp.MustCompile(`(?:^|/)models/[^/:]+:(generateContent|streamGenerateContent|predictLongRunning)$`)
openAIPostEndpoints = map[string]bool{ customVideoTaskPath = regexp.MustCompile(`(?:^|/)video/generations/[^/]+$`)
customXAIVideoTaskPath = regexp.MustCompile(`(?:^|/)videos/[^/]+$`)
customGeminiOperationPath = regexp.MustCompile(`(?:^|/)(?:models/[^/]+/)?operations/[^/]+$`)
openAIPostEndpoints = map[string]bool{
"/responses": true, "/chat/completions": true, "/images/generations": true, "/images/edits": true, "/responses": true, "/chat/completions": true, "/images/generations": true, "/images/edits": true,
"/audio/speech": true, "/audio/speech": true,
} }
@@ -57,7 +60,13 @@ func authorizeCustomRelay(method string, target *url.URL, apiFormat string, cont
return errors.New("自定义渠道调用格式无效") return errors.New("自定义渠道调用格式无效")
} }
if method == http.MethodGet { if method == http.MethodGet {
if len(query) != 0 || (requestPath != "/models" && !strings.HasSuffix(requestPath, "/models")) { allowed := requestPath == "/models" || strings.HasSuffix(requestPath, "/models")
if apiFormat == "openai" {
allowed = allowed || customVideoTaskPath.MatchString(requestPath) || customXAIVideoTaskPath.MatchString(requestPath)
} else {
allowed = allowed || customGeminiOperationPath.MatchString(requestPath)
}
if len(query) != 0 || !allowed {
return errors.New("自定义渠道不允许访问该上游接口") return errors.New("自定义渠道不允许访问该上游接口")
} }
return nil return nil
@@ -70,7 +79,7 @@ func authorizeCustomRelay(method string, target *url.URL, apiFormat string, cont
return errors.New("自定义渠道不允许使用该请求方法") return errors.New("自定义渠道不允许使用该请求方法")
} }
if apiFormat == "openai" { if apiFormat == "openai" {
if len(query) != 0 || (!strings.HasSuffix(requestPath, "/responses") && !strings.HasSuffix(requestPath, "/chat/completions")) { if len(query) != 0 || (!strings.HasSuffix(requestPath, "/responses") && !strings.HasSuffix(requestPath, "/chat/completions") && !strings.HasSuffix(requestPath, "/video/generations") && !strings.HasSuffix(requestPath, "/videos/generations")) {
return errors.New("自定义渠道不允许访问该上游接口") return errors.New("自定义渠道不允许访问该上游接口")
} }
return nil return nil
@@ -169,7 +178,9 @@ func interfaceAllowsProxyPath(interfaceType model.ChannelInterfaceType, requestP
return requestPath == "/responses" return requestPath == "/responses"
case model.ChannelInterfaceOpenAIImage: case model.ChannelInterfaceOpenAIImage:
return requestPath == "/images/generations" || requestPath == "/images/edits" return requestPath == "/images/generations" || requestPath == "/images/edits"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo: case model.ChannelInterfaceOpenAIAudio:
return requestPath == "/audio/speech"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceGeminiVeo:
return false return false
default: default:
return true return true
@@ -28,7 +28,13 @@ func TestAuthorizeCustomRelayAllowsModelsAndAgentEndpoints(t *testing.T) {
{method: http.MethodGet, target: "https://api.example.com/v1/models", apiFormat: "openai"}, {method: http.MethodGet, target: "https://api.example.com/v1/models", apiFormat: "openai"},
{method: http.MethodPost, target: "https://api.example.com/v1/responses", apiFormat: "openai", contentType: "application/json"}, {method: http.MethodPost, target: "https://api.example.com/v1/responses", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodPost, target: "https://api.example.com/v1/chat/completions", apiFormat: "openai", contentType: "application/json; charset=utf-8"}, {method: http.MethodPost, target: "https://api.example.com/v1/chat/completions", apiFormat: "openai", contentType: "application/json; charset=utf-8"},
{method: http.MethodPost, target: "https://api.example.com/v1/video/generations", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodGet, target: "https://api.example.com/v1/video/generations/task-1", apiFormat: "openai"},
{method: http.MethodPost, target: "https://api.x.ai/v1/videos/generations", apiFormat: "openai", contentType: "application/json"},
{method: http.MethodGet, target: "https://api.x.ai/v1/videos/request-1", apiFormat: "openai"},
{method: http.MethodPost, target: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse", apiFormat: "gemini", contentType: "application/json"}, {method: http.MethodPost, target: "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse", apiFormat: "gemini", contentType: "application/json"},
{method: http.MethodPost, target: "https://generativelanguage.googleapis.com/v1beta/models/veo-3.0-generate-preview:predictLongRunning", apiFormat: "gemini", contentType: "application/json"},
{method: http.MethodGet, target: "https://generativelanguage.googleapis.com/v1beta/operations/operation-1", apiFormat: "gemini"},
} }
for _, test := range tests { for _, test := range tests {
target, err := url.Parse(test.target) target, err := url.Parse(test.target)
+17 -13
View File
@@ -62,10 +62,12 @@ const (
ChannelInterfaceChatCompletion ChannelInterfaceType = "chat-completion" ChannelInterfaceChatCompletion ChannelInterfaceType = "chat-completion"
ChannelInterfaceOpenAIResponse ChannelInterfaceType = "openai-response" ChannelInterfaceOpenAIResponse ChannelInterfaceType = "openai-response"
ChannelInterfaceOpenAIImage ChannelInterfaceType = "openai-image" ChannelInterfaceOpenAIImage ChannelInterfaceType = "openai-image"
ChannelInterfaceOpenAIAudio ChannelInterfaceType = "openai-audio"
ChannelInterfaceNewAPIVideo ChannelInterfaceType = "newapi" ChannelInterfaceNewAPIVideo ChannelInterfaceType = "newapi"
ChannelInterfaceNewAPIChannel1 ChannelInterfaceType = "newapi-channel-1" ChannelInterfaceNewAPIChannel1 ChannelInterfaceType = "newapi-channel-1"
ChannelInterfaceNewAPIChannel2 ChannelInterfaceType = "newapi-channel-2" ChannelInterfaceNewAPIChannel2 ChannelInterfaceType = "newapi-channel-2"
ChannelInterfaceXAIVideo ChannelInterfaceType = "xai-video" ChannelInterfaceXAIVideo ChannelInterfaceType = "xai-video"
ChannelInterfaceGeminiVeo ChannelInterfaceType = "gemini-veo"
ApiCallStatusSucceeded ApiCallStatus = "succeeded" ApiCallStatusSucceeded ApiCallStatus = "succeeded"
ApiCallStatusFailed ApiCallStatus = "failed" ApiCallStatusFailed ApiCallStatus = "failed"
@@ -210,19 +212,20 @@ type ModelChannel struct {
} }
type ChannelModel struct { type ChannelModel struct {
ID string `json:"id" gorm:"primaryKey;size:36"` ID string `json:"id" gorm:"primaryKey;size:36"`
ChannelID string `json:"channelId" gorm:"size:36;index;uniqueIndex:idx_channel_model_key_active,priority:1,where:deleted_at IS NULL"` ChannelID string `json:"channelId" gorm:"size:36;index;uniqueIndex:idx_channel_model_key_active,priority:1,where:deleted_at IS NULL"`
ModelKey string `json:"modelKey" gorm:"size:120;uniqueIndex:idx_channel_model_key_active,priority:2,where:deleted_at IS NULL"` ModelKey string `json:"modelKey" gorm:"size:120;uniqueIndex:idx_channel_model_key_active,priority:2,where:deleted_at IS NULL"`
DisplayName string `json:"displayName" gorm:"size:160"` DisplayName string `json:"displayName" gorm:"size:160"`
Capability string `json:"capability" gorm:"size:32;index"` Capability string `json:"capability" gorm:"size:32;index"`
BillingMode string `json:"billingMode" gorm:"size:32"` Protocol ChannelInterfaceType `json:"protocol" gorm:"size:32;index"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"` BillingMode string `json:"billingMode" gorm:"size:32"`
PriceConfigured bool `json:"priceConfigured" gorm:"index"` UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
Enabled bool `json:"enabled" gorm:"index"` PriceConfigured bool `json:"priceConfigured" gorm:"index"`
PriceVersion int64 `json:"priceVersion"` Enabled bool `json:"enabled" gorm:"index"`
CreatedAt time.Time `json:"createdAt"` PriceVersion int64 `json:"priceVersion"`
UpdatedAt time.Time `json:"updatedAt"` CreatedAt time.Time `json:"createdAt"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
} }
type ApiCallLog struct { type ApiCallLog struct {
@@ -264,6 +267,7 @@ type ApiCallLog struct {
Error string `json:"error"` Error string `json:"error"`
ConcurrencyLimit int `json:"concurrencyLimit"` ConcurrencyLimit int `json:"concurrencyLimit"`
UpstreamURL string `json:"upstreamUrl"` UpstreamURL string `json:"upstreamUrl"`
RequestContentType string `json:"requestContentType,omitempty" gorm:"size:160"`
RequestBody string `json:"requestBody,omitempty" gorm:"type:text"` RequestBody string `json:"requestBody,omitempty" gorm:"type:text"`
ResponseBody string `json:"responseBody,omitempty" gorm:"type:text"` ResponseBody string `json:"responseBody,omitempty" gorm:"type:text"`
StartedAt time.Time `json:"startedAt"` StartedAt time.Time `json:"startedAt"`
+17 -9
View File
@@ -104,11 +104,12 @@ type PublicModelChannel struct {
} }
type PublicChannelModelPrice struct { type PublicChannelModelPrice struct {
Model string `json:"model"` Model string `json:"model"`
DisplayName string `json:"displayName"` DisplayName string `json:"displayName"`
Capability string `json:"capability"` Capability string `json:"capability"`
BillingMode string `json:"billingMode"` Protocol model.ChannelInterfaceType `json:"protocol"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"` BillingMode string `json:"billingMode"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
} }
func (s *Service) RequireAdmin(user *model.User) error { func (s *Service) RequireAdmin(user *model.User) error {
@@ -511,7 +512,7 @@ func (s *Service) LogAPICall(log model.ApiCallLog) error {
if err != nil { if err != nil {
return err return err
} }
incomingBytes := int64(len(log.Path) + len(log.Model) + len(log.ProviderRequestID) + len(log.ErrorCode) + len(log.Error) + len(log.UpstreamURL) + len(log.RequestBody) + len(log.ResponseBody)) incomingBytes := int64(len(log.Path) + len(log.Model) + len(log.ProviderRequestID) + len(log.ErrorCode) + len(log.Error) + len(log.UpstreamURL) + len(log.RequestContentType) + len(log.RequestBody) + len(log.ResponseBody))
if err := validateAPICallLogQuotaWithPolicy(usage, incomingBytes, policy.Resource); err != nil { if err := validateAPICallLogQuotaWithPolicy(usage, incomingBytes, policy.Resource); err != nil {
return err return err
} }
@@ -600,8 +601,11 @@ func channelFromRequest(req ChannelRequest, channel model.ModelChannel) (model.M
if req.APIKey != "" { if req.APIKey != "" {
channel.APIKey = req.APIKey channel.APIKey = req.APIKey
} }
// 系统渠道均由后端按已声明的接口类型分发,调用格式固定为 Bearer/OpenAI 兼容鉴权。 // Gemini Veo 使用 x-goog-api-key,其余系统协议使用 Bearer 鉴权。
channel.APIFormat = "openai" channel.APIFormat = "openai"
if interfaceType == model.ChannelInterfaceGeminiVeo {
channel.APIFormat = "gemini"
}
channel.InterfaceType = interfaceType channel.InterfaceType = interfaceType
if req.UseGlobalConcurrency != nil && *req.UseGlobalConcurrency { if req.UseGlobalConcurrency != nil && *req.UseGlobalConcurrency {
channel.ConcurrencyLimit = 0 channel.ConcurrencyLimit = 0
@@ -641,7 +645,7 @@ func mergeChannelRequest(req ChannelRequest, channel model.ModelChannel) Channel
func validChannelInterfaceType(value model.ChannelInterfaceType) bool { func validChannelInterfaceType(value model.ChannelInterfaceType) bool {
switch value { switch value {
case model.ChannelInterfaceChatCompletion, model.ChannelInterfaceOpenAIResponse, model.ChannelInterfaceOpenAIImage, model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo: case model.ChannelInterfaceChatCompletion, model.ChannelInterfaceOpenAIResponse, model.ChannelInterfaceOpenAIImage, model.ChannelInterfaceOpenAIAudio, model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceGeminiVeo:
return true return true
default: default:
return false return false
@@ -673,7 +677,11 @@ func publicChannel(channel model.ModelChannel, admin bool, channelModels []model
} }
models = append(models, item.ModelKey) models = append(models, item.ModelKey)
if item.Enabled && item.PriceConfigured { if item.Enabled && item.PriceConfigured {
modelCosts = append(modelCosts, PublicChannelModelPrice{Model: item.ModelKey, DisplayName: item.DisplayName, Capability: item.Capability, BillingMode: item.BillingMode, UnitPriceMicrocredits: item.UnitPriceMicrocredits}) protocol := item.Protocol
if protocol == "" {
protocol = channel.InterfaceType
}
modelCosts = append(modelCosts, PublicChannelModelPrice{Model: item.ModelKey, DisplayName: item.DisplayName, Capability: item.Capability, Protocol: protocol, BillingMode: item.BillingMode, UnitPriceMicrocredits: item.UnitPriceMicrocredits})
} }
} }
if len(models) == 0 { if len(models) == 0 {
@@ -55,6 +55,21 @@ func TestChannelFromRequestStoresXAIVideoInterfaceType(t *testing.T) {
} }
} }
func TestChannelFromRequestUsesGeminiAuthForVeo(t *testing.T) {
channel, err := channelFromRequest(ChannelRequest{
Name: "Gemini Veo",
BaseURL: "https://generativelanguage.googleapis.com",
APIKey: "key",
InterfaceType: "gemini-veo",
}, model.ModelChannel{})
if err != nil {
t.Fatalf("channelFromRequest() error = %v", err)
}
if channel.InterfaceType != model.ChannelInterfaceGeminiVeo || channel.APIFormat != "gemini" {
t.Fatalf("channel = %#v", channel)
}
}
func TestMergeChannelRequestSupportsEnabledOnlyPatch(t *testing.T) { func TestMergeChannelRequestSupportsEnabledOnlyPatch(t *testing.T) {
enabled := false enabled := false
req := mergeChannelRequest(ChannelRequest{Enabled: &enabled}, model.ModelChannel{ req := mergeChannelRequest(ChannelRequest{Enabled: &enabled}, model.ModelChannel{
+25 -5
View File
@@ -16,6 +16,7 @@ type ChannelModelRequest struct {
ModelKey string `json:"modelKey"` ModelKey string `json:"modelKey"`
DisplayName string `json:"displayName"` DisplayName string `json:"displayName"`
Capability string `json:"capability"` Capability string `json:"capability"`
Protocol string `json:"protocol"`
BillingMode string `json:"billingMode"` BillingMode string `json:"billingMode"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"` UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
PriceConfigured bool `json:"priceConfigured"` PriceConfigured bool `json:"priceConfigured"`
@@ -85,7 +86,7 @@ func (s *Service) FetchAdminChannelModels(ctx context.Context, actor *model.User
continue continue
} }
// 自动发现不能绕过定价边界;新模型由管理员定价后再手动启用。 // 自动发现不能绕过定价边界;新模型由管理员定价后再手动启用。
missing = append(missing, model.ChannelModel{ID: newID(), ChannelID: channelID, ModelKey: name, DisplayName: name, Capability: capabilityForChannel(*channel), BillingMode: "fixed_request", Enabled: false, PriceVersion: 1}) missing = append(missing, model.ChannelModel{ID: newID(), ChannelID: channelID, ModelKey: name, DisplayName: name, Capability: capabilityForChannel(*channel), Protocol: channel.InterfaceType, BillingMode: "fixed_request", Enabled: false, PriceVersion: 1})
} }
added, err := s.repo.CreateMissingChannelModels(missing) added, err := s.repo.CreateMissingChannelModels(missing)
if err != nil { if err != nil {
@@ -113,6 +114,16 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
if capability == "" { if capability == "" {
return nil, BadAuthRequest("请选择模型能力") return nil, BadAuthRequest("请选择模型能力")
} }
protocol := model.ChannelInterfaceType(strings.TrimSpace(req.Protocol))
if protocol == "" {
protocol = channel.InterfaceType
}
if !validChannelInterfaceType(protocol) {
return nil, BadAuthRequest("请选择有效的模型请求协议")
}
if expected := capabilityForProtocol(protocol); expected != "" && expected != capability {
return nil, BadAuthRequest("模型能力与请求协议不匹配")
}
billingMode := strings.TrimSpace(req.BillingMode) billingMode := strings.TrimSpace(req.BillingMode)
if billingMode == "" { if billingMode == "" {
billingMode = "fixed_request" billingMode = "fixed_request"
@@ -140,6 +151,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
item.DisplayName = modelKey item.DisplayName = modelKey
} }
item.Capability = capability item.Capability = capability
item.Protocol = protocol
item.BillingMode = billingMode item.BillingMode = billingMode
item.UnitPriceMicrocredits = req.UnitPriceMicrocredits item.UnitPriceMicrocredits = req.UnitPriceMicrocredits
item.PriceConfigured = req.PriceConfigured item.PriceConfigured = req.PriceConfigured
@@ -216,7 +228,7 @@ func (s *Service) syncInitialChannelModels(channel *model.ModelChannel, names []
} }
continue continue
} }
item := model.ChannelModel{ID: newID(), ChannelID: channel.ID, ModelKey: name, DisplayName: name, Capability: capabilityForChannel(*channel), BillingMode: "fixed_request", Enabled: true, PriceVersion: 1} item := model.ChannelModel{ID: newID(), ChannelID: channel.ID, ModelKey: name, DisplayName: name, Capability: capabilityForChannel(*channel), Protocol: channel.InterfaceType, BillingMode: "fixed_request", Enabled: true, PriceVersion: 1}
if err := s.repo.SaveChannelModel(&item); err != nil { if err := s.repo.SaveChannelModel(&item); err != nil {
return err return err
} }
@@ -266,12 +278,20 @@ func (s *Service) syncChannelModelNames(channel *model.ModelChannel) error {
} }
func capabilityForChannel(channel model.ModelChannel) string { func capabilityForChannel(channel model.ModelChannel) string {
switch channel.InterfaceType { return capabilityForProtocol(channel.InterfaceType)
}
func capabilityForProtocol(protocol model.ChannelInterfaceType) string {
switch protocol {
case model.ChannelInterfaceOpenAIImage: case model.ChannelInterfaceOpenAIImage:
return "image" return "image"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo: case model.ChannelInterfaceOpenAIAudio:
return "audio"
case model.ChannelInterfaceNewAPIVideo, model.ChannelInterfaceNewAPIChannel1, model.ChannelInterfaceNewAPIChannel2, model.ChannelInterfaceXAIVideo, model.ChannelInterfaceGeminiVeo:
return "video" return "video"
default: case model.ChannelInterfaceChatCompletion, model.ChannelInterfaceOpenAIResponse:
return "text" return "text"
default:
return ""
} }
} }
+202 -35
View File
@@ -12,6 +12,7 @@ import (
"mime/multipart" "mime/multipart"
"net/http" "net/http"
"net/textproto" "net/textproto"
"net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -157,7 +158,7 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
return nil, err return nil, err
} }
input.Config = config input.Config = config
if input.Config.APIFormat == "gemini" { if input.Config.APIFormat == "gemini" && input.Config.InterfaceType != string(model.ChannelInterfaceGeminiVeo) {
return nil, errors.New("后端任务队列暂不支持 Gemini 调用格式,请使用 OpenAI 兼容渠道") return nil, errors.New("后端任务队列暂不支持 Gemini 调用格式,请使用 OpenAI 兼容渠道")
} }
if strings.TrimSpace(input.Config.BaseURL) == "" || strings.TrimSpace(input.Config.APIKey) == "" || strings.TrimSpace(input.Config.Model) == "" { if strings.TrimSpace(input.Config.BaseURL) == "" || strings.TrimSpace(input.Config.APIKey) == "" || strings.TrimSpace(input.Config.Model) == "" {
@@ -167,7 +168,8 @@ func (s *Service) processCanvasGenerationTask(ctx context.Context, userID string
return nil, err return nil, err
} }
if resumedProviderRequestID(ctx) == "" { if resumedProviderRequestID(ctx) == "" {
if err := s.hydrateGenerationMedia(userID, &input, input.Config.InterfaceType == "newapi-channel-1"); err != nil { requirePublicURL := input.Config.InterfaceType == "newapi-channel-1" || input.Config.InterfaceType == "newapi-channel-2"
if err := s.hydrateGenerationMedia(userID, &input, requirePublicURL); err != nil {
return nil, err return nil, err
} }
} }
@@ -203,7 +205,7 @@ func (s *Service) hydrateGenerationMedia(userID string, input *canvasGenerationI
func (s *Service) hydrateProviderMedia(userID string, media *providerMedia, requirePublicURL bool) error { func (s *Service) hydrateProviderMedia(userID string, media *providerMedia, requirePublicURL bool) error {
if !strings.HasPrefix(media.StorageKey, "resource:") { if !strings.HasPrefix(media.StorageKey, "resource:") {
if requirePublicURL && strings.HasPrefix(strings.TrimSpace(media.DataURL), "data:") { if requirePublicURL && strings.HasPrefix(strings.TrimSpace(media.DataURL), "data:") {
return errors.New("NewAPI 渠道 1 的参考素材不能使用内嵌数据,请先上传到 OSS 或提供公网素材地址") return errors.New("当前 JSON 视频协议的参考素材不能使用内嵌数据,请先上传到 OSS 或提供公网素材地址")
} }
return nil return nil
} }
@@ -217,18 +219,18 @@ func (s *Service) hydrateProviderMedia(userID string, media *providerMedia, requ
return errors.New("任务参考资源尚未上传完成") return errors.New("任务参考资源尚未上传完成")
} }
if resource.Provider == "local" { if resource.Provider == "local" {
return errors.New("NewAPI 渠道 1 的参考素材需要公网可访问地址,请启用 OSS 后重新上传该素材") return errors.New("当前 JSON 视频协议的参考素材需要公网可访问地址,请启用 OSS 后重新上传该素材")
} }
setting, err := s.ossSettingForResource(userID, resource) setting, err := s.ossSettingForResource(userID, resource)
if err != nil { if err != nil {
return err return err
} }
if setting.Provider != "aliyun" { if setting.Provider != "aliyun" {
return errors.New("NewAPI 渠道 1 的参考素材暂时只支持阿里云 OSS 签名地址") return errors.New("当前 JSON 视频协议的私有参考素材暂时只支持阿里云 OSS 签名地址")
} }
signedURL, err := signedOSSObjectURL(setting, resource.ObjectKey, time.Now().Add(providerResourceURLTTL)) signedURL, err := signedOSSObjectURL(setting, resource.ObjectKey, time.Now().Add(providerResourceURLTTL))
if err != nil { if err != nil {
return fmt.Errorf("生成 NewAPI 渠道 1 参考素材地址失败:%w", err) return fmt.Errorf("生成 JSON 视频协议参考素材地址失败:%w", err)
} }
media.URL = signedURL media.URL = signedURL
media.DataURL = "" media.DataURL = ""
@@ -299,6 +301,15 @@ func (s *Service) resolveProviderConfig(config providerConfig) (providerConfig,
config.ChannelID = channel.ID config.ChannelID = channel.ID
config.APIFormat = channel.APIFormat config.APIFormat = channel.APIFormat
config.InterfaceType = string(channel.InterfaceType) config.InterfaceType = string(channel.InterfaceType)
if channelModel, modelErr := s.repo.ChannelModelByKey(channel.ID, modelName); modelErr == nil && channelModel.Protocol != "" {
config.InterfaceType = string(channelModel.Protocol)
}
// 模型协议是实际请求契约;混合渠道中鉴权格式也必须随模型协议切换。
if config.InterfaceType == string(model.ChannelInterfaceGeminiVeo) {
config.APIFormat = "gemini"
} else if config.InterfaceType != "" {
config.APIFormat = "openai"
}
config.BaseURL = channel.BaseURL config.BaseURL = channel.BaseURL
config.APIKey = channel.APIKey config.APIKey = channel.APIKey
config.Model = modelName config.Model = modelName
@@ -585,6 +596,9 @@ func runAudioTask(ctx context.Context, input canvasGenerationInput) (map[string]
} }
func runVideoTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) { func runVideoTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if input.Config.InterfaceType == "gemini-veo" {
return runGeminiVeoVideoTask(ctx, input)
}
if input.Config.InterfaceType == "newapi-channel-2" { if input.Config.InterfaceType == "newapi-channel-2" {
return runNewAPIChannel2VideoTask(ctx, input) return runNewAPIChannel2VideoTask(ctx, input)
} }
@@ -684,6 +698,126 @@ func runVideoTask(ctx context.Context, input canvasGenerationInput) (map[string]
return nil, errors.New("视频生成超时") return nil, errors.New("视频生成超时")
} }
func runGeminiVeoVideoTask(ctx context.Context, input canvasGenerationInput) (map[string]interface{}, error) {
if len(input.ReferenceImages) > 1 || len(input.ReferenceVideos) > 0 || len(input.ReferenceAudios) > 0 {
return nil, errors.New("Gemini Veo 当前只支持 1 张起始图,不支持参考视频或音频")
}
id := resumedProviderRequestID(ctx)
if id == "" {
instance := map[string]interface{}{"prompt": strings.TrimSpace(input.Prompt)}
if len(input.ReferenceImages) == 1 {
raw, mimeType, err := mediaBytes(input.ReferenceImages[0])
if err != nil {
return nil, fmt.Errorf("读取 Gemini Veo 起始图失败:%w", err)
}
instance["image"] = map[string]interface{}{"bytesBase64Encoded": base64.StdEncoding.EncodeToString(raw), "mimeType": mimeType}
}
body := map[string]interface{}{
"instances": []interface{}{instance},
"parameters": map[string]interface{}{
"aspectRatio": normalizeNewAPIChannel2Ratio(input.Config.Size, strings.ToLower(input.Config.Model)),
"durationSeconds": normalizeSeedanceVideosDuration(input.Config.VideoSeconds),
"resolution": normalizeNewAPIChannel2Resolution(input.Config.VQuality, strings.ToLower(input.Config.Model)),
"sampleCount": 1,
},
}
var created map[string]interface{}
if err := postGeminiJSON(ctx, input.Config, "/models/"+url.PathEscape(input.Config.Model)+":predictLongRunning", body, &created); err != nil {
return nil, err
}
id = strings.TrimSpace(stringField(created, "name"))
}
if id == "" {
return nil, errors.New("Gemini Veo 没有返回 operation name")
}
for deadline := providerPollingDeadline(ctx); time.Now().Before(deadline); {
var operation map[string]interface{}
if err := getGeminiJSON(ctx, input.Config, "/"+strings.TrimLeft(id, "/"), &operation); err != nil {
return nil, err
}
if errorValue, ok := operation["error"].(map[string]interface{}); ok && stringField(errorValue, "message") != "" {
return nil, fmt.Errorf("Gemini Veo 视频生成失败(任务 %s):%s", id, stringField(errorValue, "message"))
}
done, _ := operation["done"].(bool)
if done {
videoURL := findProviderMediaURL(operation["response"])
if videoURL == "" {
return nil, fmt.Errorf("Gemini Veo 任务 %s 已完成但没有返回视频地址", id)
}
data, mimeType, err := getGeminiBinary(withProviderRequestKind(ctx, "download"), input.Config, videoURL)
if err != nil {
return nil, fmt.Errorf("Gemini Veo 视频下载失败(任务 %s):%w", id, err)
}
mimeType = normalizedMediaMimeType(mimeType, data)
return map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}}, nil
}
if err := sleepContext(ctx, 5*time.Second); err != nil {
return nil, err
}
}
return nil, fmt.Errorf("Gemini Veo 视频生成超时(任务 %s)", id)
}
func postGeminiJSON(ctx context.Context, config providerConfig, path string, body interface{}, target interface{}) error {
data, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, geminiVeoURL(config.BaseURL, path), bytes.NewReader(data))
if err != nil {
return err
}
req.Header.Set("x-goog-api-key", config.APIKey)
req.Header.Set("Content-Type", "application/json")
return doJSON(req, target)
}
func getGeminiJSON(ctx context.Context, config providerConfig, path string, target interface{}) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, geminiVeoURL(config.BaseURL, path), nil)
if err != nil {
return err
}
req.Header.Set("x-goog-api-key", config.APIKey)
return doJSON(req, target)
}
func getGeminiBinary(ctx context.Context, config providerConfig, rawURL string) ([]byte, string, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
if err != nil {
return nil, "", err
}
req.Header.Set("x-goog-api-key", config.APIKey)
return doBinary(req)
}
func geminiVeoURL(baseURL string, path string) string {
base := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if !strings.HasSuffix(strings.ToLower(base), "/v1beta") {
base += "/v1beta"
}
return base + "/" + strings.TrimLeft(path, "/")
}
func findProviderMediaURL(value interface{}) string {
switch typed := value.(type) {
case map[string]interface{}:
for _, key := range []string{"uri", "url", "videoUri", "video_url"} {
if candidate := strings.TrimSpace(stringField(typed, key)); isPublicMediaURL(candidate) {
return candidate
}
}
for _, child := range typed {
if candidate := findProviderMediaURL(child); candidate != "" {
return candidate
}
}
case []interface{}:
for _, child := range typed {
if candidate := findProviderMediaURL(child); candidate != "" {
return candidate
}
}
}
return ""
}
func newAPIVideoResultURL(state map[string]interface{}) string { func newAPIVideoResultURL(state map[string]interface{}) string {
return nestedNewAPIVideoResultURL(state, false, 0) return nestedNewAPIVideoResultURL(state, false, 0)
} }
@@ -736,7 +870,7 @@ func runNewAPIChannel2VideoTask(ctx context.Context, input canvasGenerationInput
} }
} }
if id == "" { if id == "" {
return nil, errors.New("NewAPI 渠道 2 没有返回任务 ID") return nil, errors.New("NewAPI Video Generations 没有返回任务 ID")
} }
for deadline := time.Now().Add(newAPIChannel2VideoPollTimeout); time.Now().Before(deadline); { for deadline := time.Now().Add(newAPIChannel2VideoPollTimeout); time.Now().Before(deadline); {
@@ -752,32 +886,32 @@ func runNewAPIChannel2VideoTask(ctx context.Context, input canvasGenerationInput
case "SUCCESS": case "SUCCESS":
videoURL := strings.TrimSpace(stringField(state, "result_url")) videoURL := strings.TrimSpace(stringField(state, "result_url"))
if videoURL == "" { if videoURL == "" {
return nil, fmt.Errorf("NewAPI 渠道 2 任务 %s 已成功但没有返回视频地址", id) return nil, fmt.Errorf("NewAPI Video Generations 任务 %s 已成功但没有返回视频地址", id)
} }
data, mimeType, err := getExternalBinary(withProviderRequestKind(ctx, "download"), videoURL) data, mimeType, err := getExternalBinary(withProviderRequestKind(ctx, "download"), videoURL)
if err != nil { if err != nil {
return nil, fmt.Errorf("NewAPI 渠道 2 视频结果下载失败(任务 %s):%w", id, err) return nil, fmt.Errorf("NewAPI Video Generations 视频结果下载失败(任务 %s):%w", id, err)
} }
mimeType = normalizedMediaMimeType(mimeType, data) mimeType = normalizedMediaMimeType(mimeType, data)
return map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}}, nil return map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}}, nil
case "FAILURE": case "FAILURE":
reason := strings.TrimSpace(stringField(state, "fail_reason")) reason := strings.TrimSpace(stringField(state, "fail_reason"))
return nil, fmt.Errorf("NewAPI 渠道 2 视频生成失败(任务 %s):%s", id, defaultString(reason, "上游返回失败")) return nil, fmt.Errorf("NewAPI Video Generations 视频生成失败(任务 %s):%s", id, defaultString(reason, "上游返回失败"))
case "SUBMITTED", "QUEUED", "IN_PROGRESS", "NOT_START", "": case "SUBMITTED", "QUEUED", "IN_PROGRESS", "NOT_START", "":
// 按上游协议继续轮询;空状态也可能出现在任务刚写入队列时。 // 按上游协议继续轮询;空状态也可能出现在任务刚写入队列时。
default: default:
return nil, fmt.Errorf("NewAPI 渠道 2 任务 %s 返回未知状态:%s", id, status) return nil, fmt.Errorf("NewAPI Video Generations 任务 %s 返回未知状态:%s", id, status)
} }
if err := sleepContext(ctx, newAPIChannel2VideoPollInterval); err != nil { if err := sleepContext(ctx, newAPIChannel2VideoPollInterval); err != nil {
return nil, err return nil, err
} }
} }
return nil, fmt.Errorf("NewAPI 渠道 2 视频生成超时(任务 %s)", id) return nil, fmt.Errorf("NewAPI Video Generations 视频生成超时(任务 %s)", id)
} }
func newAPIChannel2VideoBody(input canvasGenerationInput) (map[string]interface{}, error) { func newAPIChannel2VideoBody(input canvasGenerationInput) (map[string]interface{}, error) {
if len(input.ReferenceVideos) > 0 || len(input.ReferenceAudios) > 0 { if len(input.ReferenceImages) > 9 || len(input.ReferenceVideos) > 3 || len(input.ReferenceAudios) > 3 {
return nil, errors.New("NewAPI 渠道 2 只支持参考图片,不支持参考视频或音频") return nil, errors.New("NewAPI Video Generations 最多支持 9 张参考图、3 个参考视频和 3 个参考音频")
} }
modelName := strings.ToLower(strings.TrimSpace(input.Config.Model)) modelName := strings.ToLower(strings.TrimSpace(input.Config.Model))
requiresSingleImage := modelName == "grok-video-1.5" || modelName == "grok-video-1.5-1080p" requiresSingleImage := modelName == "grok-video-1.5" || modelName == "grok-video-1.5-1080p"
@@ -785,19 +919,16 @@ func newAPIChannel2VideoBody(input canvasGenerationInput) (map[string]interface{
// 单图模型以实际参考图为准,兼容旧画布中未随连接关系更新的 text_to_video 元数据。 // 单图模型以实际参考图为准,兼容旧画布中未随连接关系更新的 text_to_video 元数据。
if shouldSendNewAPIVideoImages(input) || requiresSingleImage { if shouldSendNewAPIVideoImages(input) || requiresSingleImage {
for _, image := range input.ReferenceImages { for _, image := range input.ReferenceImages {
url, err := openAIImageInputURL(image) url, err := videoGenerationsMediaURL(image)
if err != nil { if err != nil {
return nil, err return nil, err
} }
images = append(images, url) images = append(images, url)
} }
} }
if len(images) > 7 {
return nil, errors.New("NewAPI 渠道 2 最多支持 7 张参考图")
}
if requiresSingleImage { if requiresSingleImage {
if len(images) != 1 { if len(images) != 1 {
return nil, fmt.Errorf("NewAPI 渠道 2 的 %s 必须且只能提供 1 张参考图(当前 %d 张)", input.Config.Model, len(images)) return nil, fmt.Errorf("NewAPI Video Generations 的 %s 必须且只能提供 1 张参考图(当前 %d 张)", input.Config.Model, len(images))
} }
} }
@@ -813,18 +944,49 @@ func newAPIChannel2VideoBody(input canvasGenerationInput) (map[string]interface{
ratio := normalizeNewAPIChannel2Ratio(input.Config.Size, modelName) ratio := normalizeNewAPIChannel2Ratio(input.Config.Size, modelName)
resolution := normalizeNewAPIChannel2Resolution(input.Config.VQuality, modelName) resolution := normalizeNewAPIChannel2Resolution(input.Config.VQuality, modelName)
body := map[string]interface{}{ body := map[string]interface{}{
"model": input.Config.Model, "model": input.Config.Model,
"prompt": strings.TrimSpace(input.Prompt), "prompt": strings.TrimSpace(input.Prompt),
"seconds": seconds, "seconds": seconds,
"aspect_ratio": ratio, "aspect_ratio": ratio,
"resolution": resolution, "resolution": resolution,
"generate_audio": parseBool(input.Config.VideoGenerateAudio, true),
} }
if len(images) > 0 { if len(images) > 0 {
body["image_urls"] = images body["image_urls"] = images
} }
videoURLs := make([]string, 0, len(input.ReferenceVideos))
for _, video := range input.ReferenceVideos {
url, err := videoGenerationsMediaURL(video)
if err != nil {
return nil, err
}
videoURLs = append(videoURLs, url)
}
if len(videoURLs) > 0 {
body["video_urls"] = videoURLs
}
audioURLs := make([]string, 0, len(input.ReferenceAudios))
for _, audio := range input.ReferenceAudios {
url, err := videoGenerationsMediaURL(audio)
if err != nil {
return nil, err
}
audioURLs = append(audioURLs, url)
}
if len(audioURLs) > 0 {
body["audio_urls"] = audioURLs
}
return body, nil return body, nil
} }
func videoGenerationsMediaURL(media providerMedia) (string, error) {
value := strings.TrimSpace(firstNonEmpty(media.URL, media.DataURL))
if isPublicMediaURL(value) || strings.HasPrefix(value, "data:") {
return value, nil
}
return "", errors.New("NewAPI Video Generations 的参考素材需要公网 URL;私有素材请先保存到 OSS")
}
func normalizeNewAPIChannel2Ratio(value string, modelName string) string { func normalizeNewAPIChannel2Ratio(value string, modelName string) string {
ratio := strings.TrimSpace(value) ratio := strings.TrimSpace(value)
if strings.Contains(ratio, "x") { if strings.Contains(ratio, "x") {
@@ -886,10 +1048,10 @@ func runNewAPIChannel1VideoTask(ctx context.Context, input canvasGenerationInput
} }
status := strings.ToUpper(strings.TrimSpace(stringField(created, "status"))) status := strings.ToUpper(strings.TrimSpace(stringField(created, "status")))
if strings.HasPrefix(status, "FAILED") { if strings.HasPrefix(status, "FAILED") {
return nil, fmt.Errorf("NewAPI 渠道 1 视频生成失败(任务 %s):%s", id, strings.TrimSpace(strings.TrimPrefix(status, "FAILED:"))) return nil, fmt.Errorf("NewAPI 媒体任务视频生成失败(任务 %s):%s", id, strings.TrimSpace(strings.TrimPrefix(status, "FAILED:")))
} }
if id == "" { if id == "" {
return nil, errors.New("NewAPI 渠道 1 没有返回任务 ID") return nil, errors.New("NewAPI 媒体任务没有返回任务 ID")
} }
for deadline := providerPollingDeadline(ctx); time.Now().Before(deadline); { for deadline := providerPollingDeadline(ctx); time.Now().Before(deadline); {
var state map[string]interface{} var state map[string]interface{}
@@ -904,27 +1066,27 @@ func runNewAPIChannel1VideoTask(ctx context.Context, input canvasGenerationInput
case status == "SUCCEEDED": case status == "SUCCEEDED":
videoURL := stringField(state, "object") videoURL := stringField(state, "object")
if videoURL == "" { if videoURL == "" {
return nil, fmt.Errorf("NewAPI 渠道 1 任务 %s 已完成但没有返回视频 URL", id) return nil, fmt.Errorf("NewAPI 媒体任务 %s 已完成但没有返回视频 URL", id)
} }
data, mimeType, err := getExternalBinary(withProviderRequestKind(ctx, "download"), videoURL) data, mimeType, err := getExternalBinary(withProviderRequestKind(ctx, "download"), videoURL)
if err != nil { if err != nil {
return nil, fmt.Errorf("NewAPI 渠道 1 视频结果下载失败(任务 %s):%w", id, err) return nil, fmt.Errorf("NewAPI 媒体任务视频结果下载失败(任务 %s):%w", id, err)
} }
return map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}}, nil return map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(mimeType, data), "mimeType": mimeType}}, nil
case strings.HasPrefix(status, "FAILED"): case strings.HasPrefix(status, "FAILED"):
message := strings.TrimSpace(strings.TrimPrefix(status, "FAILED:")) message := strings.TrimSpace(strings.TrimPrefix(status, "FAILED:"))
return nil, fmt.Errorf("NewAPI 渠道 1 视频生成失败(任务 %s):%s", id, defaultString(message, "上游返回失败")) return nil, fmt.Errorf("NewAPI 媒体任务视频生成失败(任务 %s):%s", id, defaultString(message, "上游返回失败"))
} }
if err := sleepContext(ctx, newAPIChannel1VideoPollInterval); err != nil { if err := sleepContext(ctx, newAPIChannel1VideoPollInterval); err != nil {
return nil, err return nil, err
} }
} }
return nil, fmt.Errorf("NewAPI 渠道 1 视频生成超时(任务 %s)", id) return nil, fmt.Errorf("NewAPI 媒体任务视频生成超时(任务 %s)", id)
} }
func newAPIChannel1VideoBody(input canvasGenerationInput) (map[string]interface{}, error) { func newAPIChannel1VideoBody(input canvasGenerationInput) (map[string]interface{}, error) {
if len(input.ReferenceImages) > 9 || len(input.ReferenceVideos) > 3 || len(input.ReferenceAudios) > 3 { if len(input.ReferenceImages) > 9 || len(input.ReferenceVideos) > 3 || len(input.ReferenceAudios) > 3 {
return nil, errors.New("NewAPI 渠道 1 最多支持 9 张参考图、3 个参考视频和 3 个参考音频") return nil, errors.New("NewAPI 媒体任务最多支持 9 张参考图、3 个参考视频和 3 个参考音频")
} }
media := make([]map[string]string, 0, len(input.ReferenceImages)+len(input.ReferenceVideos)+len(input.ReferenceAudios)) media := make([]map[string]string, 0, len(input.ReferenceImages)+len(input.ReferenceVideos)+len(input.ReferenceAudios))
if shouldSendNewAPIVideoImages(input) { if shouldSendNewAPIVideoImages(input) {
@@ -970,7 +1132,7 @@ func newAPIChannel1VideoBody(input canvasGenerationInput) (map[string]interface{
func newAPIChannel1MediaURL(media providerMedia) (string, error) { func newAPIChannel1MediaURL(media providerMedia) (string, error) {
value := strings.TrimSpace(media.URL) value := strings.TrimSpace(media.URL)
if !isPublicMediaURL(value) { if !isPublicMediaURL(value) {
return "", errors.New("NewAPI 渠道 1 的参考素材必须使用公网 HTTP(S) URL,请启用 OSS 或提供公网素材地址") return "", errors.New("NewAPI 媒体任务的参考素材必须使用公网 HTTP(S) URL,请启用 OSS 或提供公网素材地址")
} }
if _, err := ValidateOutboundURL(value); err != nil { if _, err := ValidateOutboundURL(value); err != nil {
return "", err return "", err
@@ -1012,7 +1174,8 @@ func validateGenerationInterface(mode string, interfaceType string) error {
allowed := map[string]map[string]bool{ allowed := map[string]map[string]bool{
"text": {"chat-completion": true, "openai-response": true}, "text": {"chat-completion": true, "openai-response": true},
"image": {"openai-image": true}, "image": {"openai-image": true},
"video": {"newapi": true, "newapi-channel-1": true, "newapi-channel-2": true, "xai-video": true}, "video": {"newapi": true, "newapi-channel-1": true, "newapi-channel-2": true, "xai-video": true, "gemini-veo": true},
"audio": {"openai-audio": true},
} }
if allowed[mode] != nil && !allowed[mode][interfaceType] { if allowed[mode] != nil && !allowed[mode][interfaceType] {
return fmt.Errorf("接口类型 %s 不支持%s生成", interfaceType, mode) return fmt.Errorf("接口类型 %s 不支持%s生成", interfaceType, mode)
@@ -1389,14 +1552,18 @@ func recordProviderRequest(req *http.Request, startedAt time.Time, statusCode in
if metadata.RequestKind != "" { if metadata.RequestKind != "" {
requestKind = metadata.RequestKind requestKind = metadata.RequestKind
} }
apiFormat := "openai"
if req.Header.Get("x-goog-api-key") != "" {
apiFormat = "gemini"
}
log := model.ApiCallLog{ log := model.ApiCallLog{
UserID: metadata.UserID, ChannelID: metadata.ChannelID, TaskID: metadata.TaskID, BillingOrderID: metadata.BillingOrderID, UserID: metadata.UserID, ChannelID: metadata.ChannelID, TaskID: metadata.TaskID, BillingOrderID: metadata.BillingOrderID,
Source: "backend-task", Capability: metadata.Capability, Operation: metadata.Operation, Source: "backend-task", Capability: metadata.Capability, Operation: metadata.Operation,
RequestKind: requestKind, Billable: req.Method == http.MethodPost, RequestKind: requestKind, Billable: req.Method == http.MethodPost,
APIFormat: "openai", Method: req.Method, Path: req.URL.Path, Model: metadata.Model, APIFormat: apiFormat, Method: req.Method, Path: req.URL.Path, Model: metadata.Model,
Status: status, StatusCode: statusCode, DurationMs: time.Since(startedAt).Milliseconds(), Status: status, StatusCode: statusCode, DurationMs: time.Since(startedAt).Milliseconds(),
Error: errorText, ConcurrencyLimit: metadata.ConcurrencyLimit, UpstreamURL: req.URL.Scheme + "://" + req.URL.Host + req.URL.Path, Error: errorText, ConcurrencyLimit: metadata.ConcurrencyLimit, UpstreamURL: req.URL.Scheme + "://" + req.URL.Host + req.URL.Path,
ProviderRequestID: metadata.ProviderRequestID, RequestBody: requestPayloadForLog(req), ResponseBody: SanitizeAPICallPayload(responseBody, ""), ProviderRequestID: metadata.ProviderRequestID, RequestContentType: req.Header.Get("Content-Type"), RequestBody: requestPayloadForLog(req), ResponseBody: SanitizeAPICallPayload(responseBody, ""),
} }
channelSlotFailure := false channelSlotFailure := false
if code, message := ChannelSlotFailureDetails(requestErr); code != "" { if code, message := ChannelSlotFailureDetails(requestErr); code != "" {
+50 -1
View File
@@ -695,6 +695,11 @@ func TestRunNewAPIChannel2VideoTaskDownloadsTemporaryResult(t *testing.T) {
if !ok || len(images) != 2 || images[0] != testReferenceImageDataURL { if !ok || len(images) != 2 || images[0] != testReferenceImageDataURL {
t.Errorf("image_urls = %#v", body["image_urls"]) t.Errorf("image_urls = %#v", body["image_urls"])
} }
videos, _ := body["video_urls"].([]interface{})
audios, _ := body["audio_urls"].([]interface{})
if len(videos) != 1 || len(audios) != 1 || body["generate_audio"] != true {
t.Errorf("multi-reference body = %#v", body)
}
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"task_id":"grok-task","status":"queued"}`)) _, _ = w.Write([]byte(`{"task_id":"grok-task","status":"queued"}`))
case "GET /v1/video/generations/grok-task": case "GET /v1/video/generations/grok-task":
@@ -716,7 +721,9 @@ func TestRunNewAPIChannel2VideoTaskDownloadsTemporaryResult(t *testing.T) {
{ID: "image-1", DataURL: testReferenceImageDataURL}, {ID: "image-1", DataURL: testReferenceImageDataURL},
{ID: "image-2", DataURL: testReferenceImageDataURL}, {ID: "image-2", DataURL: testReferenceImageDataURL},
}, },
Metadata: map[string]interface{}{"videoEditOperation": "image_to_video"}, ReferenceVideos: []providerMedia{{ID: "video-1", URL: server.URL + "/reference.mp4"}},
ReferenceAudios: []providerMedia{{ID: "audio-1", URL: server.URL + "/reference.mp3"}},
Metadata: map[string]interface{}{"videoEditOperation": "image_to_video"},
}) })
if err != nil { if err != nil {
t.Fatalf("runVideoTask() error = %v", err) t.Fatalf("runVideoTask() error = %v", err)
@@ -731,6 +738,48 @@ func TestRunNewAPIChannel2VideoTaskDownloadsTemporaryResult(t *testing.T) {
} }
} }
func TestRunGeminiVeoVideoTaskUsesLongRunningOperation(t *testing.T) {
t.Setenv("CANVAS_ALLOW_PRIVATE_UPSTREAMS", "true")
paths := make([]string, 0, 3)
var server *httptest.Server
server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
paths = append(paths, r.Method+" "+r.URL.Path)
if r.Header.Get("x-goog-api-key") != "test-key" {
t.Errorf("x-goog-api-key = %q", r.Header.Get("x-goog-api-key"))
}
switch r.Method + " " + r.URL.Path {
case "POST /v1beta/models/veo-test:predictLongRunning":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"name":"operations/op-1"}`))
case "GET /v1beta/operations/op-1":
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"done":true,"response":{"generatedSamples":[{"video":{"uri":"` + server.URL + `/video.mp4"}}]}}`))
case "GET /video.mp4":
w.Header().Set("Content-Type", "video/mp4")
_, _ = w.Write([]byte("video"))
default:
http.NotFound(w, r)
}
}))
defer server.Close()
result, err := runVideoTask(context.Background(), canvasGenerationInput{
Prompt: "make it move",
Config: providerConfig{BaseURL: server.URL, APIKey: "test-key", APIFormat: "gemini", Model: "veo-test", InterfaceType: "gemini-veo", VideoSeconds: "6", Size: "16:9", VQuality: "720"},
})
if err != nil {
t.Fatalf("runVideoTask() error = %v", err)
}
video := result["video"].(map[string]interface{})
if video["dataUrl"] != "data:video/mp4;base64,dmlkZW8=" {
t.Fatalf("video = %#v", video)
}
want := "POST /v1beta/models/veo-test:predictLongRunning,GET /v1beta/operations/op-1,GET /video.mp4"
if got := strings.Join(paths, ","); got != want {
t.Fatalf("paths = %q, want %q", got, want)
}
}
func TestNewAPIChannel2SingleImageModelsRequireOneReference(t *testing.T) { func TestNewAPIChannel2SingleImageModelsRequireOneReference(t *testing.T) {
_, err := newAPIChannel2VideoBody(canvasGenerationInput{Config: providerConfig{Model: "grok-video-1.5", VideoSeconds: "6"}}) _, err := newAPIChannel2VideoBody(canvasGenerationInput{Config: providerConfig{Model: "grok-video-1.5", VideoSeconds: "6"}})
if err == nil { if err == nil {
@@ -356,8 +356,7 @@ export function buildGenerationConfig(config: AiConfig, node: CanvasNodeData | u
export function supportsVideoReferenceAudio(config: AiConfig) { export function supportsVideoReferenceAudio(config: AiConfig) {
const interfaceType = resolveModelRequestConfig(config, config.model).interfaceType; const interfaceType = resolveModelRequestConfig(config, config.model).interfaceType;
if (interfaceType === "newapi-channel-2") return false; return interfaceType === "newapi-channel-1" || interfaceType === "newapi-channel-2" || isSeedanceVideoConfig(config);
return interfaceType === "newapi-channel-1" || isSeedanceVideoConfig(config);
} }
export function resetInterruptedGeneration(nodes: CanvasNodeData[]) { export function resetInterruptedGeneration(nodes: CanvasNodeData[]) {
+67
View File
@@ -0,0 +1,67 @@
export type ModelProtocol =
| "chat-completion"
| "openai-response"
| "openai-image"
| "openai-audio"
| "newapi"
| "newapi-channel-1"
| "newapi-channel-2"
| "xai-video"
| "gemini-veo";
export type ProtocolCapability = "text" | "image" | "video" | "audio";
export type ModelProtocolDefinition = {
value: ModelProtocol;
label: string;
capability: ProtocolCapability;
create: string;
contentType: string;
poll?: string;
media: string;
};
export const MODEL_PROTOCOLS: ModelProtocolDefinition[] = [
{ value: "chat-completion", label: "OpenAI Chat Completions", capability: "text", create: "POST /v1/chat/completions", contentType: "application/json", media: "文本与多模态消息" },
{ value: "openai-response", label: "OpenAI Responses", capability: "text", create: "POST /v1/responses", contentType: "application/json", media: "文本与多模态输入" },
{ value: "openai-image", label: "OpenAI Images", capability: "image", create: "POST /v1/images/generations", contentType: "application/json / multipart", media: "生成、编辑与参考图" },
{ value: "openai-audio", label: "OpenAI Audio", capability: "audio", create: "POST /v1/audio/speech", contentType: "application/json", media: "文本转语音" },
{ value: "newapi", label: "OpenAI / NewAPI Videos", capability: "video", create: "POST /v1/videos", poll: "GET /v1/videos/{task_id}", contentType: "multipart/form-data", media: "input_reference[] 参考图" },
{ value: "newapi-channel-1", label: "NewAPI 媒体任务", capability: "video", create: "POST /v1/videos", poll: "GET /v1/videos/{task_id}", contentType: "application/json", media: "图片、视频、音频公网 URL" },
{ value: "newapi-channel-2", label: "NewAPI Video Generations", capability: "video", create: "POST /v1/video/generations", poll: "GET /v1/video/generations/{task_id}", contentType: "application/json", media: "image_urls / video_urls / audio_urls" },
{ value: "xai-video", label: "xAI 官方视频", capability: "video", create: "POST /v1/videos/generations", poll: "GET /v1/videos/{request_id}", contentType: "application/json", media: "单张起始图" },
{ value: "gemini-veo", label: "Gemini Veo", capability: "video", create: "POST /v1beta/models/{model}:predictLongRunning", poll: "GET /v1beta/{operation_name}", contentType: "application/json", media: "文本与单张起始图" },
];
export const MODEL_PROTOCOL_OPTIONS = [
{ label: "文本", options: protocolOptions("text") },
{ label: "图片", options: protocolOptions("image") },
{ label: "视频", options: protocolOptions("video") },
{ label: "音频", options: protocolOptions("audio") },
];
export function modelProtocolDefinition(value?: string) {
return MODEL_PROTOCOLS.find((item) => item.value === value);
}
export function modelProtocolLabel(value?: string) {
return modelProtocolDefinition(value)?.label || "自动识别";
}
export function modelProtocolCapability(value?: string) {
return modelProtocolDefinition(value)?.capability;
}
export function modelProtocolSummary(value?: string) {
const protocol = modelProtocolDefinition(value);
if (!protocol) return "保存模型时选择协议后,将在这里显示实际请求方式。";
return [protocol.create, protocol.contentType, protocol.poll, protocol.media].filter(Boolean).join(" · ");
}
export function normalizeModelProtocol(value: unknown): ModelProtocol | undefined {
return typeof value === "string" && MODEL_PROTOCOLS.some((item) => item.value === value) ? value as ModelProtocol : undefined;
}
function protocolOptions(capability: ProtocolCapability) {
return MODEL_PROTOCOLS.filter((item) => item.capability === capability).map((item) => ({ label: `${item.label} · ${item.create.replace("POST ", "")}`, value: item.value }));
}
+6 -10
View File
@@ -7,6 +7,7 @@ import { useSearchParams } from "react-router";
import { ListToolbar, TableSurface } from "@/components/layout/workspace-page"; import { ListToolbar, TableSurface } from "@/components/layout/workspace-page";
import { useDebouncedValue } from "@/hooks/use-debounced-value"; import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { refreshSystemChannels } from "@/lib/user-session"; import { refreshSystemChannels } from "@/lib/user-session";
import { MODEL_PROTOCOL_OPTIONS, modelProtocolLabel, normalizeModelProtocol } from "@/lib/model-protocols";
import { createAdminChannel, deleteAdminChannel, listAdminChannels, updateAdminChannel } from "@/services/api/auth"; import { createAdminChannel, deleteAdminChannel, listAdminChannels, updateAdminChannel } from "@/services/api/auth";
import { defaultBaseUrlForChannelInterface, type ChannelInterfaceType, type ModelChannel } from "@/stores/use-config-store"; import { defaultBaseUrlForChannelInterface, type ChannelInterfaceType, type ModelChannel } from "@/stores/use-config-store";
import { useAdminContext } from "../admin-context"; import { useAdminContext } from "../admin-context";
@@ -16,11 +17,7 @@ import { ChannelModelManager } from "../components/channel-model-manager";
type ChannelFormValues = { name: string; baseUrl: string; apiKey?: string; interfaceType: ChannelInterfaceType; useGlobalConcurrency?: boolean; concurrencyLimit?: number; enabled?: boolean }; type ChannelFormValues = { name: string; baseUrl: string; apiKey?: string; interfaceType: ChannelInterfaceType; useGlobalConcurrency?: boolean; concurrencyLimit?: number; enabled?: boolean };
const interfaceTypeOptions = [ const interfaceTypeOptions = MODEL_PROTOCOL_OPTIONS;
{ label: "文本", options: [{ label: "Chat Completions", value: "chat-completion" }, { label: "OpenAI Responses", value: "openai-response" }] },
{ label: "图片", options: [{ label: "OpenAI Images", value: "openai-image" }] },
{ label: "视频", options: [{ label: "NewAPI 视频", value: "newapi" }, { label: "NewAPI 渠道 1", value: "newapi-channel-1" }, { label: "NewAPI 渠道 2", value: "newapi-channel-2" }, { label: "xAI / Sub2API 视频", value: "xai-video" }] },
];
export default function ChannelsPage() { export default function ChannelsPage() {
const { message, modal } = App.useApp(); const { message, modal } = App.useApp();
@@ -145,7 +142,7 @@ export default function ChannelsPage() {
const columns: ColumnsType<ModelChannel> = [ const columns: ColumnsType<ModelChannel> = [
{ title: "渠道", dataIndex: "name", render: (_, channel) => <div><div className="font-medium">{channel.name}</div><div className="max-w-lg truncate text-xs text-foreground/45">{channel.baseUrl}</div></div> }, { title: "渠道", dataIndex: "name", render: (_, channel) => <div><div className="font-medium">{channel.name}</div><div className="max-w-lg truncate text-xs text-foreground/45">{channel.baseUrl}</div></div> },
{ title: "接口类型", dataIndex: "interfaceType", width: 160, render: (value: ChannelInterfaceType) => <Tag variant="filled" color={value === "newapi-channel-1" ? "green" : value === "newapi" ? "orange" : value === "newapi-channel-2" ? "purple" : value === "xai-video" ? "cyan" : "blue"}>{interfaceTypeLabel(value)}</Tag> }, { title: "默认协议", dataIndex: "interfaceType", width: 220, render: (value: ChannelInterfaceType) => <Tag variant="filled" color={value === "newapi" ? "orange" : value === "newapi-channel-1" ? "green" : value === "newapi-channel-2" ? "purple" : value === "xai-video" ? "cyan" : "blue"}>{modelProtocolLabel(value)}</Tag> },
{ title: "模型", dataIndex: "models", width: 100, render: (models: string[]) => `${models?.length || 0} 个` }, { title: "模型", dataIndex: "models", width: 100, render: (models: string[]) => `${models?.length || 0} 个` },
{ title: "最大并发", dataIndex: "concurrencyLimit", width: 120, render: (value: number) => value > 0 ? value : <span className="text-foreground/45">跟随系统</span> }, { title: "最大并发", dataIndex: "concurrencyLimit", width: 120, render: (value: number) => value > 0 ? value : <span className="text-foreground/45">跟随系统</span> },
{ title: "密钥", dataIndex: "hasApiKey", width: 100, render: (configured) => <Tag variant="filled" color={configured ? "success" : "default"}>{configured ? "已配置" : "未配置"}</Tag> }, { title: "密钥", dataIndex: "hasApiKey", width: 100, render: (configured) => <Tag variant="filled" color={configured ? "success" : "default"}>{configured ? "已配置" : "未配置"}</Tag> },
@@ -161,7 +158,7 @@ export default function ChannelsPage() {
<AdminPageFrame title="系统渠道" description="渠道、模型与售价" actions={<Button type="primary" icon={<Plus className="size-4" />} onClick={() => openDrawer()}>新增系统渠道</Button>}> <AdminPageFrame title="系统渠道" description="渠道、模型与售价" actions={<Button type="primary" icon={<Plus className="size-4" />} onClick={() => openDrawer()}>新增系统渠道</Button>}>
<ListToolbar active={hasFilters} onReset={() => updateUrl({ filter: "", interfaceType: "all", status: "all", page: 1 })}> <ListToolbar active={hasFilters} onReset={() => updateUrl({ filter: "", interfaceType: "all", status: "all", page: 1 })}>
<Input id="admin-channel-search" aria-label="搜索系统渠道" autoComplete="off" allowClear className="app-list-search" prefix={<Search className="size-4 text-foreground/40" />} value={keyword} placeholder="搜索渠道名称或地址" onChange={(event) => updateUrl({ filter: event.target.value, page: 1 }, true)} /> <Input id="admin-channel-search" aria-label="搜索系统渠道" autoComplete="off" allowClear className="app-list-search" prefix={<Search className="size-4 text-foreground/40" />} value={keyword} placeholder="搜索渠道名称或地址" onChange={(event) => updateUrl({ filter: event.target.value, page: 1 }, true)} />
<Select className="w-40" value={interfaceType} onChange={(value) => updateUrl({ interfaceType: value, page: 1 })} options={[{ label: "全部接口", value: "all" }, ...interfaceTypeOptions.flatMap((group) => group.options)]} /> <Select className="w-40" value={interfaceType} onChange={(value) => updateUrl({ interfaceType: value, page: 1 })} options={[{ label: "全部协议", value: "all" }, ...interfaceTypeOptions.flatMap((group) => group.options)]} />
<Select className="w-32" value={status} onChange={(value) => updateUrl({ status: value, page: 1 })} options={[{ label: "全部状态", value: "all" }, { label: "已启用", value: "enabled" }, { label: "已停用", value: "disabled" }]} /> <Select className="w-32" value={status} onChange={(value) => updateUrl({ status: value, page: 1 })} options={[{ label: "全部状态", value: "all" }, { label: "已启用", value: "enabled" }, { label: "已停用", value: "disabled" }]} />
</ListToolbar> </ListToolbar>
<TableSurface> <TableSurface>
@@ -170,7 +167,7 @@ export default function ChannelsPage() {
<Drawer title={editingChannel ? "编辑系统渠道" : "新增系统渠道"} open={drawerOpen} size="min(560px, 100vw)" onClose={closeDrawer} maskClosable={!saving} destroyOnHidden extra={<Button type="primary" loading={saving} onClick={() => void save()}>保存</Button>}> <Drawer title={editingChannel ? "编辑系统渠道" : "新增系统渠道"} open={drawerOpen} size="min(560px, 100vw)" onClose={closeDrawer} maskClosable={!saving} destroyOnHidden extra={<Button type="primary" loading={saving} onClick={() => void save()}>保存</Button>}>
<Form form={form} layout="vertical" requiredMark={false}> <Form form={form} layout="vertical" requiredMark={false}>
<Form.Item name="name" label="渠道名称" rules={[{ required: true, message: "请填写渠道名称" }]}><Input placeholder="例如:OpenAI 官方渠道" /></Form.Item> <Form.Item name="name" label="渠道名称" rules={[{ required: true, message: "请填写渠道名称" }]}><Input placeholder="例如:OpenAI 官方渠道" /></Form.Item>
<Form.Item name="interfaceType" label="接口类型" rules={[{ required: true, message: "请选择接口类型" }]} extra="按生成能力选择实际上游协议;系统渠道统一使用 Bearer 鉴权。"><Select options={interfaceTypeOptions} onChange={(value: ChannelInterfaceType) => { const current = String(form.getFieldValue("baseUrl") || "").trim(); if (!current || current === defaultBaseUrlForChannelInterface()) form.setFieldValue("baseUrl", defaultBaseUrlForChannelInterface(value)); }} /></Form.Item> <Form.Item name="interfaceType" label="默认模型协议" rules={[{ required: true, message: "请选择默认模型协议" }]} extra="仅用于新增或拉取模型时预填;每个模型可在模型管理中选择自己的实际请求协议。"><Select options={interfaceTypeOptions} onChange={(value: ChannelInterfaceType) => { const current = String(form.getFieldValue("baseUrl") || "").trim(); const officialDefaults = [defaultBaseUrlForChannelInterface(), defaultBaseUrlForChannelInterface("gemini-veo")]; if (!current || officialDefaults.includes(current)) form.setFieldValue("baseUrl", defaultBaseUrlForChannelInterface(value)); }} /></Form.Item>
<Form.Item name="baseUrl" label="Base URL" rules={[{ required: true, message: "请填写 Base URL" }]}><Input placeholder="填写渠道 Base URL" /></Form.Item> <Form.Item name="baseUrl" label="Base URL" rules={[{ required: true, message: "请填写 Base URL" }]}><Input placeholder="填写渠道 Base URL" /></Form.Item>
<Form.Item name="apiKey" label={editingChannel ? `API Key(${configuredSecretText})` : "API Key"} rules={editingChannel ? [] : [{ required: true, message: "请填写 API Key" }]}><Input.Password autoComplete="new-password" placeholder={editingChannel ? "留空保留原密钥" : "系统渠道密钥"} /></Form.Item> <Form.Item name="apiKey" label={editingChannel ? `API Key(${configuredSecretText})` : "API Key"} rules={editingChannel ? [] : [{ required: true, message: "请填写 API Key" }]}><Input.Password autoComplete="new-password" placeholder={editingChannel ? "留空保留原密钥" : "系统渠道密钥"} /></Form.Item>
<Form.Item name="useGlobalConcurrency" label="跟随系统并发配置" valuePropName="checked"><Switch /></Form.Item> <Form.Item name="useGlobalConcurrency" label="跟随系统并发配置" valuePropName="checked"><Switch /></Form.Item>
@@ -185,5 +182,4 @@ export default function ChannelsPage() {
function positiveInt(value: string | null, fallback: number) { const parsed = Number(value); return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; } function positiveInt(value: string | null, fallback: number) { const parsed = Number(value); return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback; }
function normalizePageSize(value: string | null) { const parsed = positiveInt(value, 20); return [20, 50, 100].includes(parsed) ? parsed : 20; } function normalizePageSize(value: string | null) { const parsed = positiveInt(value, 20); return [20, 50, 100].includes(parsed) ? parsed : 20; }
function normalizeStatus(value: string | null): "all" | "enabled" | "disabled" { return value === "enabled" || value === "disabled" ? value : "all"; } function normalizeStatus(value: string | null): "all" | "enabled" | "disabled" { return value === "enabled" || value === "disabled" ? value : "all"; }
function normalizeInterface(value: string | null): "all" | ChannelInterfaceType { return ["chat-completion", "openai-response", "openai-image", "newapi", "newapi-channel-1", "newapi-channel-2", "xai-video"].includes(value || "") ? value as ChannelInterfaceType : "all"; } function normalizeInterface(value: string | null): "all" | ChannelInterfaceType { return normalizeModelProtocol(value) || "all"; }
function interfaceTypeLabel(value?: ChannelInterfaceType) { return ({ "chat-completion": "Chat Completions", "openai-response": "OpenAI Responses", "openai-image": "OpenAI Images", newapi: "NewAPI 视频", "newapi-channel-1": "NewAPI 渠道 1", "newapi-channel-2": "NewAPI 渠道 2", "xai-video": "xAI / Sub2API 视频" } as Record<string, string>)[value || ""] || "未设置"; }
@@ -42,6 +42,7 @@ function LogDetail({ log }: { log: ApiCallLog }) {
["计费", log.costAvailable ? `${log.currency || "USD"} ${(log.estimatedCostMicros / 1_000_000).toFixed(6)}` : "未配置价格"], ["计费", log.costAvailable ? `${log.currency || "USD"} ${(log.estimatedCostMicros / 1_000_000).toFixed(6)}` : "未配置价格"],
["错误信息", [log.errorCode, log.error].filter(Boolean).join(" · ") || "--"], ["错误信息", [log.errorCode, log.error].filter(Boolean).join(" · ") || "--"],
["方法与路径", `${log.method} ${log.path}`], ["方法与路径", `${log.method} ${log.path}`],
["请求 Content-Type", log.requestContentType || "--"],
["HTTP 状态", String(log.statusCode || "--")], ["HTTP 状态", String(log.statusCode || "--")],
["任务 ID", log.taskId || "--"], ["任务 ID", log.taskId || "--"],
["供应商任务 ID", log.providerRequestId || "--"], ["供应商任务 ID", log.providerRequestId || "--"],
@@ -4,6 +4,7 @@ import type { ColumnsType } from "antd/es/table";
import { ArrowLeft, Plus, RefreshCw, Search, Trash2 } from "lucide-react"; import { ArrowLeft, Plus, RefreshCw, Search, Trash2 } from "lucide-react";
import { ListToolbar, TableSurface } from "@/components/layout/workspace-page"; import { ListToolbar, TableSurface } from "@/components/layout/workspace-page";
import { MODEL_PROTOCOL_OPTIONS, modelProtocolCapability, modelProtocolDefinition, modelProtocolLabel, modelProtocolSummary, type ModelProtocol } from "@/lib/model-protocols";
import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, updateAdminChannelModel, type ChannelModel } from "@/services/api/wallet"; import { createAdminChannelModel, deleteAdminChannelModel, fetchAdminChannelModels, listAdminChannelModels, updateAdminChannelModel, type ChannelModel } from "@/services/api/wallet";
import type { ModelChannel } from "@/stores/use-config-store"; import type { ModelChannel } from "@/stores/use-config-store";
@@ -11,6 +12,7 @@ type FormValues = {
modelKey: string; modelKey: string;
displayName?: string; displayName?: string;
capability: ChannelModel["capability"]; capability: ChannelModel["capability"];
protocol: ModelProtocol;
billingMode: ChannelModel["billingMode"]; billingMode: ChannelModel["billingMode"];
unitPrice: number; unitPrice: number;
enabled: boolean; enabled: boolean;
@@ -32,6 +34,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
const [form] = Form.useForm<FormValues>(); const [form] = Form.useForm<FormValues>();
const billingMode = Form.useWatch("billingMode", form) || "fixed_request"; const billingMode = Form.useWatch("billingMode", form) || "fixed_request";
const modelCapability = Form.useWatch("capability", form); const modelCapability = Form.useWatch("capability", form);
const modelProtocol = Form.useWatch("protocol", form);
const reload = async () => { const reload = async () => {
if (!channel) return; if (!channel) return;
@@ -74,13 +77,13 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
const startCreate = () => { const startCreate = () => {
setEditing(null); setEditing(null);
form.setFieldsValue({ modelKey: "", displayName: "", capability: capabilityFromInterface(channel?.interfaceType), billingMode: "fixed_request", unitPrice: 0, enabled: true }); form.setFieldsValue({ modelKey: "", displayName: "", capability: capabilityFromInterface(channel?.interfaceType), protocol: channel.interfaceType || "chat-completion", billingMode: "fixed_request", unitPrice: 0, enabled: true });
setEditorOpen(true); setEditorOpen(true);
}; };
const startEdit = (item: ChannelModel) => { const startEdit = (item: ChannelModel) => {
setEditing(item); setEditing(item);
form.setFieldsValue({ modelKey: item.modelKey, displayName: item.displayName, capability: item.capability, billingMode: item.billingMode, unitPrice: item.unitPriceMicrocredits / 1_000_000, enabled: item.enabled }); form.setFieldsValue({ modelKey: item.modelKey, displayName: item.displayName, capability: item.capability, protocol: item.protocol || channel.interfaceType || "chat-completion", billingMode: item.billingMode, unitPrice: item.unitPriceMicrocredits / 1_000_000, enabled: item.enabled });
setEditorOpen(true); setEditorOpen(true);
}; };
@@ -92,6 +95,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
modelKey: values.modelKey.trim(), modelKey: values.modelKey.trim(),
displayName: values.displayName?.trim() || values.modelKey.trim(), displayName: values.displayName?.trim() || values.modelKey.trim(),
capability: values.capability, capability: values.capability,
protocol: values.protocol,
billingMode: values.billingMode, billingMode: values.billingMode,
unitPriceMicrocredits: Math.round(values.unitPrice * 1_000_000), unitPriceMicrocredits: Math.round(values.unitPrice * 1_000_000),
priceConfigured: true, priceConfigured: true,
@@ -133,6 +137,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
), ),
}, },
{ title: "能力", dataIndex: "capability", width: 90, render: capabilityLabel }, { title: "能力", dataIndex: "capability", width: 90, render: capabilityLabel },
{ title: "请求协议", dataIndex: "protocol", width: 230, render: (value: ModelProtocol) => <div><div className="text-xs font-medium">{modelProtocolLabel(value || channel.interfaceType)}</div><div className="truncate text-[10px] text-foreground/45">{modelProtocolDefinition(value || channel.interfaceType)?.create}</div></div> },
{ title: "计费", width: 165, render: (_, item) => (item.priceConfigured ? `${formatCredits(item.unitPriceMicrocredits)} 积分 / ${item.billingMode === "per_second" ? "秒" : "次"}` : <Tag color="orange">未配置价格</Tag>) }, { title: "计费", width: 165, render: (_, item) => (item.priceConfigured ? `${formatCredits(item.unitPriceMicrocredits)} 积分 / ${item.billingMode === "per_second" ? "秒" : "次"}` : <Tag color="orange">未配置价格</Tag>) },
{ title: "版本", dataIndex: "priceVersion", width: 75, render: (value) => `v${value}` }, { title: "版本", dataIndex: "priceVersion", width: 75, render: (value) => `v${value}` },
{ title: "状态", dataIndex: "enabled", width: 85, render: (enabled) => (enabled ? <Tag color="green">启用</Tag> : <Tag>停用</Tag>) }, { title: "状态", dataIndex: "enabled", width: 85, render: (enabled) => (enabled ? <Tag color="green">启用</Tag> : <Tag>停用</Tag>) },
@@ -166,7 +171,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
<Button aria-label="返回系统渠道" icon={<ArrowLeft className="size-4" />} onClick={onClose} /> <Button aria-label="返回系统渠道" icon={<ArrowLeft className="size-4" />} onClick={onClose} />
<div className="min-w-0"> <div className="min-w-0">
<h2 className="truncate text-lg font-semibold">{channel.name} / 模型管理</h2> <h2 className="truncate text-lg font-semibold">{channel.name} / 模型管理</h2>
<p className="mt-1 text-xs text-foreground/50">维护模型能力、计费单位、积分单价与启用状态。</p> <p className="mt-1 text-xs text-foreground/50">维护模型能力、请求协议、计费与启用状态。</p>
</div> </div>
</div> </div>
<Space wrap> <Space wrap>
@@ -192,10 +197,10 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
columns={columns} columns={columns}
dataSource={filteredItems} dataSource={filteredItems}
pagination={{ current: page, pageSize, total: filteredItems.length, showSizeChanger: true, pageSizeOptions: [20, 50, 100], showTotal: (total, range) => `${range[0]}-${range[1]} / 共 ${total} 个模型`, onChange: (nextPage, nextPageSize) => { setPage(nextPageSize !== pageSize ? 1 : nextPage); setPageSize(nextPageSize); } }} pagination={{ current: page, pageSize, total: filteredItems.length, showSizeChanger: true, pageSizeOptions: [20, 50, 100], showTotal: (total, range) => `${range[0]}-${range[1]} / 共 ${total} 个模型`, onChange: (nextPage, nextPageSize) => { setPage(nextPageSize !== pageSize ? 1 : nextPage); setPageSize(nextPageSize); } }}
scroll={{ x: 760 }} scroll={{ x: 990 }}
/> />
</TableSurface> </TableSurface>
<Drawer title={editing ? "编辑模型" : "新增模型"} open={editorOpen} size="min(520px, 100vw)" onClose={() => setEditorOpen(false)} styles={{ body: { paddingBottom: 88 } }} extra={editing ? <Button size="small" icon={<Plus className="size-3.5" />} onClick={startCreate}>新增</Button> : null}> <Drawer title={editing ? "编辑模型" : "新增模型"} open={editorOpen} size="min(720px, 100vw)" onClose={() => setEditorOpen(false)} styles={{ body: { paddingBottom: 88 } }} extra={editing ? <Button size="small" icon={<Plus className="size-3.5" />} onClick={startCreate}>新增</Button> : null}>
<Form form={form} layout="vertical" requiredMark={false}> <Form form={form} layout="vertical" requiredMark={false}>
<Form.Item name="modelKey" label="模型标识" rules={[{ required: true, message: "请输入模型标识" }]}> <Form.Item name="modelKey" label="模型标识" rules={[{ required: true, message: "请输入模型标识" }]}>
<Input placeholder="gpt-image-2" /> <Input placeholder="gpt-image-2" />
@@ -204,8 +209,15 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
<Input placeholder="不填则使用模型标识" /> <Input placeholder="不填则使用模型标识" />
</Form.Item> </Form.Item>
<Form.Item name="capability" label="能力" rules={[{ required: true }]}> <Form.Item name="capability" label="能力" rules={[{ required: true }]}>
<Select onChange={(value) => { if (value !== "video") form.setFieldValue("billingMode", "fixed_request"); }} options={[{ label: "文本", value: "text" }, { label: "图片", value: "image" }, { label: "视频", value: "video" }, { label: "音频", value: "audio" }]} /> <Select onChange={(value) => { if (value !== "video") form.setFieldValue("billingMode", "fixed_request"); const current = form.getFieldValue("protocol") as ModelProtocol; if (modelProtocolCapability(current) !== value) form.setFieldValue("protocol", MODEL_PROTOCOL_OPTIONS.flatMap((group) => group.options).find((item) => modelProtocolCapability(item.value) === value)?.value); }} options={[{ label: "文本", value: "text" }, { label: "图片", value: "image" }, { label: "视频", value: "video" }, { label: "音频", value: "audio" }]} />
</Form.Item> </Form.Item>
<Form.Item name="protocol" label="请求协议" rules={[{ required: true, message: "请选择模型请求协议" }]} extra="协议决定创建路径、Content-Type、请求字段和轮询方式。">
<Select options={MODEL_PROTOCOL_OPTIONS.map((group) => ({ ...group, options: group.options.filter((item) => modelProtocolCapability(item.value) === modelCapability) }))} />
</Form.Item>
<div className="mb-5 rounded-md border border-border/70 bg-foreground/[.025] px-3 py-2.5">
<div className="text-xs font-semibold">实际请求预览</div>
<div className="mt-1 font-mono text-[11px] leading-5 text-foreground/60">{modelProtocolSummary(modelProtocol)}</div>
</div>
<Form.Item name="billingMode" label="计费方式" rules={[{ required: true }]}> <Form.Item name="billingMode" label="计费方式" rules={[{ required: true }]}>
<Segmented block options={[{ label: "按次计费", value: "fixed_request" }, { label: "按秒计费", value: "per_second", disabled: modelCapability !== "video" }]} /> <Segmented block options={[{ label: "按次计费", value: "fixed_request" }, { label: "按秒计费", value: "per_second", disabled: modelCapability !== "video" }]} />
</Form.Item> </Form.Item>
@@ -223,9 +235,7 @@ export function ChannelModelManager({ channel, onClose, onChanged }: { channel:
} }
function capabilityFromInterface(value?: ModelChannel["interfaceType"]): ChannelModel["capability"] { function capabilityFromInterface(value?: ModelChannel["interfaceType"]): ChannelModel["capability"] {
if (value === "openai-image") return "image"; return modelProtocolCapability(value) || "text";
if (value === "newapi" || value === "newapi-channel-1" || value === "newapi-channel-2" || value === "xai-video") return "video";
return "text";
} }
function capabilityLabel(value: ChannelModel["capability"]) { function capabilityLabel(value: ChannelModel["capability"]) {
@@ -1,56 +1,49 @@
import { InputNumber, Segmented } from "antd"; import { InputNumber, Segmented, Select } from "antd";
import { modelOptionName, type ModelChannel } from "@/stores/use-config-store"; import { MODEL_PROTOCOL_OPTIONS, modelProtocolCapability, modelProtocolDefinition, modelProtocolLabel, type ModelProtocol } from "@/lib/model-protocols";
import { modelMatchesCapability, modelOptionName, type ModelChannel } from "@/stores/use-config-store";
type ModelCost = NonNullable<ModelChannel["modelCosts"]>[number]; type ModelCost = NonNullable<ModelChannel["modelCosts"]>[number];
export function ChannelVideoPricing({ channel, onChange }: { channel: ModelChannel; onChange: (costs: ModelCost[]) => void }) { export function ChannelModelSettings({ channel, onChange }: { channel: ModelChannel; onChange: (costs: ModelCost[]) => void }) {
if (!isVideoChannel(channel) || !channel.models.length) return null; if (!channel.models.length) return null;
const updateCost = (model: string, patch: Partial<ModelCost>) => { const updateCost = (model: string, patch: Partial<ModelCost>) => {
const current = channel.modelCosts?.find((item) => item.model === model) || { const current = channel.modelCosts?.find((item) => item.model === model) || {
model, model,
capability: "video" as const, capability: modelProtocolCapability(defaultProtocolForModel(channel, model)) || "text",
protocol: defaultProtocolForModel(channel, model),
billingMode: "fixed_request" as const, billingMode: "fixed_request" as const,
unitPriceMicrocredits: 0, unitPriceMicrocredits: 0,
}; };
const next = [...(channel.modelCosts || []).filter((item) => item.model !== model), { ...current, ...patch, model, capability: "video" as const }]; const next = [...(channel.modelCosts || []).filter((item) => item.model !== model), { ...current, ...patch, model }];
onChange(next.filter((item) => channel.models.includes(item.model))); onChange(next.filter((item) => channel.models.includes(item.model)));
}; };
return ( return (
<div className="mt-3 border-t border-border/70 pt-3"> <div className="mt-3 border-t border-border/70 pt-3">
<div className="mb-2 flex items-center justify-between gap-3"> <div className="mb-2 flex items-center justify-between gap-3">
<div><div className="text-xs font-medium">视频模型价格</div><div className="mt-0.5 text-[10px] text-foreground/42">仅用于记录自定义渠道成本,不扣平台积分</div></div> <div><div className="text-xs font-medium">模型请求协议</div><div className="mt-0.5 text-[10px] text-foreground/42">每个模型独立决定请求路径和报文;视频价格仅用于成本记录</div></div>
<span className="text-[10px] text-foreground/35">{channel.models.length} 个模型</span> <span className="text-[10px] text-foreground/35">{channel.models.length} 个模型</span>
</div> </div>
<div className="divide-y divide-border/60 rounded-md border border-border/70"> <div className="divide-y divide-border/60 rounded-md border border-border/70">
{channel.models.map((rawModel) => { {channel.models.map((rawModel) => {
const model = modelOptionName(rawModel); const model = modelOptionName(rawModel);
const cost = channel.modelCosts?.find((item) => item.model === model); const cost = channel.modelCosts?.find((item) => item.model === model);
const protocol = cost?.protocol || defaultProtocolForModel(channel, model);
const capability = cost?.capability || modelProtocolCapability(protocol) || "text";
const billingMode = cost?.billingMode || "fixed_request"; const billingMode = cost?.billingMode || "fixed_request";
return ( return (
<div key={model} className="grid gap-2 px-2.5 py-2 sm:grid-cols-[minmax(0,1fr)_176px_160px] sm:items-center"> <div key={model} className="grid gap-2 px-2.5 py-2.5 lg:grid-cols-[minmax(140px,1fr)_minmax(280px,1.6fr)_176px_160px] lg:items-center">
<span className="truncate text-xs font-medium" title={model}>{model}</span> <div className="min-w-0"><div className="truncate text-xs font-medium" title={model}>{model}</div><div className="mt-0.5 truncate font-mono text-[10px] text-foreground/40" title={modelProtocolDefinition(protocol)?.create}>{modelProtocolDefinition(protocol)?.create}</div></div>
<Segmented <Select<ModelProtocol>
size="small" size="small"
block value={protocol}
value={billingMode} options={MODEL_PROTOCOL_OPTIONS}
options={[{ label: "按次", value: "fixed_request" }, { label: "按秒", value: "per_second" }]} onChange={(value) => updateCost(model, { protocol: value, capability: modelProtocolCapability(value) || capability, billingMode: modelProtocolCapability(value) === "video" ? billingMode : "fixed_request" })}
onChange={(value) => updateCost(model, { billingMode: value as ModelCost["billingMode"] })}
/>
<InputNumber
size="small"
min={0}
max={1_000_000}
precision={6}
step={0.1}
className="w-full"
placeholder={billingMode === "per_second" ? "每秒价格" : "每次价格"}
addonAfter={`积分/${billingMode === "per_second" ? "秒" : "次"}`}
value={cost ? cost.unitPriceMicrocredits / 1_000_000 : null}
onChange={(value) => updateCost(model, { unitPriceMicrocredits: Math.round(Number(value || 0) * 1_000_000) })}
/> />
{capability === "video" ? <Segmented size="small" block value={billingMode} options={[{ label: "按次", value: "fixed_request" }, { label: "按秒", value: "per_second" }]} onChange={(value) => updateCost(model, { billingMode: value as ModelCost["billingMode"] })} /> : <span className="text-center text-[10px] text-foreground/35">{modelProtocolLabel(protocol)}</span>}
{capability === "video" ? <InputNumber size="small" min={0} max={1_000_000} precision={6} step={0.1} className="w-full" placeholder={billingMode === "per_second" ? "每秒价格" : "每次价格"} addonAfter={`积分/${billingMode === "per_second" ? "秒" : "次"}`} value={cost ? cost.unitPriceMicrocredits / 1_000_000 : null} onChange={(value) => updateCost(model, { unitPriceMicrocredits: Math.round(Number(value || 0) * 1_000_000) })} /> : <span />}
</div> </div>
); );
})} })}
@@ -59,6 +52,10 @@ export function ChannelVideoPricing({ channel, onChange }: { channel: ModelChann
); );
} }
function isVideoChannel(channel: ModelChannel) { function defaultProtocolForModel(channel: ModelChannel, model: string): ModelProtocol {
return channel.interfaceType === "newapi" || channel.interfaceType === "newapi-channel-1" || channel.interfaceType === "newapi-channel-2" || channel.interfaceType === "xai-video"; if (channel.interfaceType) return channel.interfaceType;
if (channel.apiFormat === "gemini" && modelMatchesCapability(model, "video")) return "gemini-veo";
if (modelMatchesCapability(model, "video")) return "newapi";
if (modelMatchesCapability(model, "image")) return "openai-image";
return "chat-completion";
} }
+10 -34
View File
@@ -7,6 +7,7 @@ import { UserOSSSettingsForm } from "@/components/layout/user-oss-settings-form"
import { WorkspaceState } from "@/components/layout/workspace-state"; import { WorkspaceState } from "@/components/layout/workspace-state";
import { WorkspaceSignalIcon } from "@/components/ui/aceternity/workspace-signal-icon"; import { WorkspaceSignalIcon } from "@/components/ui/aceternity/workspace-signal-icon";
import { refreshSystemChannels } from "@/lib/user-session"; import { refreshSystemChannels } from "@/lib/user-session";
import { MODEL_PROTOCOL_OPTIONS, modelProtocolLabel } from "@/lib/model-protocols";
import { fetchChannelModels } from "@/services/api/image"; import { fetchChannelModels } from "@/services/api/image";
import { audioFormatOptions, audioVoiceOptions, normalizeAudioSpeedValue } from "@/lib/audio-generation"; import { audioFormatOptions, audioVoiceOptions, normalizeAudioSpeedValue } from "@/lib/audio-generation";
import { import {
@@ -22,7 +23,7 @@ import {
type ModelChannel, type ModelChannel,
} from "@/stores/use-config-store"; } from "@/stores/use-config-store";
import { useUserStore } from "@/stores/use-user-store"; import { useUserStore } from "@/stores/use-user-store";
import { ChannelVideoPricing } from "./channel-video-pricing"; import { ChannelModelSettings } from "./channel-video-pricing";
import { ModelDefaultGrid } from "./model-default-grid"; import { ModelDefaultGrid } from "./model-default-grid";
type ConfigSectionKey = "channels" | "models" | "preferences" | "storage"; type ConfigSectionKey = "channels" | "models" | "preferences" | "storage";
@@ -38,24 +39,8 @@ type UserChannelProtocol = ChannelInterfaceType | "auto" | "gemini";
const channelProtocolOptions = [ const channelProtocolOptions = [
{ label: "OpenAI 自动兼容", value: "auto" }, { label: "OpenAI 自动兼容", value: "auto" },
{ label: "Gemini 原生", value: "gemini" }, { label: "Google Gemini(模型级选择)", value: "gemini" },
{ ...MODEL_PROTOCOL_OPTIONS,
label: "文本",
options: [
{ label: "Chat Completions", value: "chat-completion" },
{ label: "OpenAI Responses", value: "openai-response" },
],
},
{ label: "图片", options: [{ label: "OpenAI Images", value: "openai-image" }] },
{
label: "视频",
options: [
{ label: "NewAPI 视频", value: "newapi" },
{ label: "NewAPI 渠道 1", value: "newapi-channel-1" },
{ label: "NewAPI 渠道 2", value: "newapi-channel-2" },
{ label: "xAI / Sub2API 视频", value: "xai-video" },
],
},
]; ];
function isConfigSection(value: string | null): value is ConfigSectionKey { function isConfigSection(value: string | null): value is ConfigSectionKey {
@@ -134,12 +119,11 @@ export default function SettingsPage() {
}; };
const updateChannelProtocol = (channel: ModelChannel, protocol: UserChannelProtocol) => { const updateChannelProtocol = (channel: ModelChannel, protocol: UserChannelProtocol) => {
const apiFormat = protocol === "gemini" ? "gemini" : "openai"; const apiFormat = protocol === "gemini" || protocol === "gemini-veo" ? "gemini" : "openai";
const interfaceType = protocol === "auto" || protocol === "gemini" ? undefined : protocol; const interfaceType = protocol === "auto" || protocol === "gemini" ? undefined : protocol;
const defaultBaseUrl = protocol === "gemini" ? defaultBaseUrlForApiFormat("gemini") : defaultBaseUrlForChannelInterface(interfaceType); const defaultBaseUrl = protocol === "gemini" ? defaultBaseUrlForApiFormat("gemini") : defaultBaseUrlForChannelInterface(interfaceType);
const baseUrl = isKnownDefaultBaseUrl(channel.baseUrl) ? defaultBaseUrl : channel.baseUrl; const baseUrl = isKnownDefaultBaseUrl(channel.baseUrl) ? defaultBaseUrl : channel.baseUrl;
const videoProtocol = interfaceType === "newapi" || interfaceType === "newapi-channel-1" || interfaceType === "newapi-channel-2" || interfaceType === "xai-video"; updateChannel(channel.id, { apiFormat, interfaceType, baseUrl });
updateChannel(channel.id, { apiFormat, interfaceType, baseUrl, modelCosts: videoProtocol ? channel.modelCosts : [] });
}; };
const addChannel = () => { const addChannel = () => {
@@ -296,7 +280,7 @@ export default function SettingsPage() {
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="flex w-fit max-w-full flex-wrap items-center gap-1.5 text-xs text-foreground/65"> <div className="flex w-fit max-w-full flex-wrap items-center gap-1.5 text-xs text-foreground/65">
<Info className="size-3.5 shrink-0" /> <Info className="size-3.5 shrink-0" />
<span>模型会按渠道协议和后台能力自动归类,拉取完成后可直接选择默认模型。</span> <span>渠道保存连接和默认协议;拉取模型后,请为需要特殊路径的模型单独选择请求协议。</span>
<Button type="link" size="small" className="h-auto p-0 text-xs font-semibold" onClick={() => selectSection("models")}> <Button type="link" size="small" className="h-auto p-0 text-xs font-semibold" onClick={() => selectSection("models")}>
打开模型选择 打开模型选择
</Button> </Button>
@@ -366,7 +350,7 @@ export default function SettingsPage() {
onBlur={(event) => updateChannel(channel.id, { name: event.target.value.trim() || "未命名渠道" })} onBlur={(event) => updateChannel(channel.id, { name: event.target.value.trim() || "未命名渠道" })}
/> />
</Form.Item> </Form.Item>
<Form.Item label="接口协议" htmlFor={`channel-${channel.id}-protocol`} className="mb-0 lg:col-span-3"> <Form.Item label="默认模型协议" htmlFor={`channel-${channel.id}-protocol`} className="mb-0 lg:col-span-3" extra="用于新模型预填,单个模型可在下方覆盖。">
<Select<UserChannelProtocol> <Select<UserChannelProtocol>
id={`channel-${channel.id}-protocol`} id={`channel-${channel.id}-protocol`}
value={channelProtocolValue(channel)} value={channelProtocolValue(channel)}
@@ -408,7 +392,7 @@ export default function SettingsPage() {
/> />
</Form.Item> </Form.Item>
</div> </div>
<ChannelVideoPricing channel={channel} onChange={(modelCosts) => updateChannel(channel.id, { modelCosts })} /> <ChannelModelSettings channel={channel} onChange={(modelCosts) => updateChannel(channel.id, { modelCosts })} />
</section> </section>
))} ))}
</div> </div>
@@ -620,16 +604,8 @@ function channelProtocolLabel(channel: ModelChannel) {
return "OpenAI Responses"; return "OpenAI Responses";
case "openai-image": case "openai-image":
return "OpenAI Images"; return "OpenAI Images";
case "newapi":
return "NewAPI 视频";
case "newapi-channel-1":
return "NewAPI 渠道 1";
case "newapi-channel-2":
return "NewAPI 渠道 2";
case "xai-video":
return "xAI / Sub2API 视频";
default: default:
return "OpenAI 自动兼容"; return protocol === "auto" ? "OpenAI 自动兼容" : modelProtocolLabel(protocol);
} }
} }
+1
View File
@@ -76,6 +76,7 @@ export type ApiCallLog = {
error?: string; error?: string;
concurrencyLimit: number; concurrencyLimit: number;
upstreamUrl: string; upstreamUrl: string;
requestContentType?: string;
requestBody?: string; requestBody?: string;
responseBody?: string; responseBody?: string;
startedAt?: string; startedAt?: string;
+172 -7
View File
@@ -2,13 +2,15 @@ import axios from "axios";
import { dataUrlToFile } from "@/lib/image-utils"; import { dataUrlToFile } from "@/lib/image-utils";
import { getMediaBlob, uploadMediaFile, type UploadedFile } from "@/services/file-storage"; import { getMediaBlob, uploadMediaFile, type UploadedFile } from "@/services/file-storage";
import { getResourceOSSUrl } from "@/services/api/resources";
import { channelRequest } from "@/services/api/custom-channel-relay";
import { imageToDataUrl } from "@/services/image-storage"; import { imageToDataUrl } from "@/services/image-storage";
import { boolConfig, buildSeedancePromptText, isArkPlanBaseUrl, isSeedanceVideoConfig, normalizeSeedanceDuration, normalizeSeedanceRatio, normalizeSeedanceResolution, seedanceVideoReferenceError, SEEDANCE_REFERENCE_LIMITS } from "@/lib/seedance-video"; import { boolConfig, buildSeedancePromptText, isArkPlanBaseUrl, isSeedanceVideoConfig, normalizeSeedanceDuration, normalizeSeedanceRatio, normalizeSeedanceResolution, seedanceVideoReferenceError, SEEDANCE_REFERENCE_LIMITS } from "@/lib/seedance-video";
import { buildApiUrl, isSystemProxyBaseUrl, modelOptionName, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store"; import { buildApiUrl, isSystemProxyBaseUrl, modelOptionName, resolveModelRequestConfig, type AiConfig } from "@/stores/use-config-store";
import type { ReferenceImage } from "@/types/image"; import type { ReferenceImage } from "@/types/image";
import type { ReferenceAudio, ReferenceVideo } from "@/types/media"; import type { ReferenceAudio, ReferenceVideo } from "@/types/media";
type VideoResponse = { id?: string; request_id?: string; task_id?: string; status?: string; error?: { message?: string } }; type VideoResponse = { id?: string; request_id?: string; task_id?: string; status?: string; error?: { message?: string }; video?: { url?: string }; video_url?: string; result_url?: string };
type ApiVideoResponse = VideoResponse | { code?: number; data?: VideoResponse | null; msg?: string }; type ApiVideoResponse = VideoResponse | { code?: number; data?: VideoResponse | null; msg?: string };
type ResolvedAiConfig = ReturnType<typeof resolveModelRequestConfig>; type ResolvedAiConfig = ReturnType<typeof resolveModelRequestConfig>;
type SeedanceTask = { type SeedanceTask = {
@@ -24,7 +26,7 @@ type ApiEnvelope<T> = T | { code?: number; data?: T | null; msg?: string };
type RequestOptions = { signal?: AbortSignal }; type RequestOptions = { signal?: AbortSignal };
export type VideoGenerationResult = { blob?: Blob; url?: string; mimeType?: string }; export type VideoGenerationResult = { blob?: Blob; url?: string; mimeType?: string };
export type VideoGenerationTask = { id: string; provider: "openai" | "seedance"; model: string }; export type VideoGenerationTask = { id: string; provider: "openai" | "seedance" | "video-generations" | "gemini-veo"; model: string };
export type VideoGenerationTaskState = { status: "pending" } | { status: "completed"; result: VideoGenerationResult } | { status: "failed"; error: string }; export type VideoGenerationTaskState = { status: "pending" } | { status: "completed"; result: VideoGenerationResult } | { status: "failed"; error: string };
function aiApiUrl(config: AiConfig, path: string) { function aiApiUrl(config: AiConfig, path: string) {
@@ -41,7 +43,7 @@ function aiHeaders(config: AiConfig, contentType?: string) {
export async function requestVideoGeneration(config: AiConfig, prompt: string, references: ReferenceImage[] = [], videoReferences: ReferenceVideo[] = [], audioReferences: ReferenceAudio[] = [], options?: RequestOptions): Promise<VideoGenerationResult> { export async function requestVideoGeneration(config: AiConfig, prompt: string, references: ReferenceImage[] = [], videoReferences: ReferenceVideo[] = [], audioReferences: ReferenceAudio[] = [], options?: RequestOptions): Promise<VideoGenerationResult> {
const task = await createVideoGenerationTask(config, prompt, references, videoReferences, audioReferences, options); const task = await createVideoGenerationTask(config, prompt, references, videoReferences, audioReferences, options);
const delayMs = task.provider === "seedance" ? 5000 : 2500; const delayMs = task.provider === "openai" ? 2500 : 5000;
for (let attempt = 0; attempt < 120; attempt += 1) { for (let attempt = 0; attempt < 120; attempt += 1) {
if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError"); if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");
const state = await pollVideoGenerationTask(config, task, options); const state = await pollVideoGenerationTask(config, task, options);
@@ -57,6 +59,12 @@ export async function createVideoGenerationTask(config: AiConfig, prompt: string
const selectedModel = (config.model || config.videoModel).trim(); const selectedModel = (config.model || config.videoModel).trim();
const requestConfig = resolveModelRequestConfig(config, selectedModel); const requestConfig = resolveModelRequestConfig(config, selectedModel);
assertVideoConfig(requestConfig, requestConfig.model); assertVideoConfig(requestConfig, requestConfig.model);
if (requestConfig.interfaceType === "newapi-channel-2") {
return createVideoGenerationsTask(requestConfig, selectedModel, prompt, references, videoReferences, audioReferences, options);
}
if (requestConfig.interfaceType === "gemini-veo") {
return createGeminiVeoTask(requestConfig, selectedModel, prompt, references, videoReferences, audioReferences, options);
}
if (isSeedanceVideoConfig(requestConfig)) { if (isSeedanceVideoConfig(requestConfig)) {
return createSeedanceTask(requestConfig, selectedModel, prompt, references, videoReferences, audioReferences, options); return createSeedanceTask(requestConfig, selectedModel, prompt, references, videoReferences, audioReferences, options);
} }
@@ -69,7 +77,162 @@ export async function createVideoGenerationTask(config: AiConfig, prompt: string
export async function pollVideoGenerationTask(config: AiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> { export async function pollVideoGenerationTask(config: AiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> {
const requestConfig = resolveModelRequestConfig(config, task.model); const requestConfig = resolveModelRequestConfig(config, task.model);
assertVideoConfig(requestConfig, requestConfig.model); assertVideoConfig(requestConfig, requestConfig.model);
return task.provider === "seedance" ? pollSeedanceTask(requestConfig, task, options) : pollOpenAIVideoTask(requestConfig, task, options); if (task.provider === "seedance") return pollSeedanceTask(requestConfig, task, options);
if (task.provider === "video-generations") return pollVideoGenerationsTask(requestConfig, task, options);
if (task.provider === "gemini-veo") return pollGeminiVeoTask(requestConfig, task, options);
return pollOpenAIVideoTask(requestConfig, task, options);
}
async function createVideoGenerationsTask(config: ResolvedAiConfig, model: string, prompt: string, references: ReferenceImage[], videoReferences: ReferenceVideo[], audioReferences: ReferenceAudio[], options?: RequestOptions): Promise<VideoGenerationTask> {
if (references.length > 9 || videoReferences.length > 3 || audioReferences.length > 3) throw new Error("NewAPI Video Generations 最多支持 9 张参考图、3 个参考视频和 3 个参考音频");
const [imageUrls, videoUrls, audioUrls] = await Promise.all([
Promise.all(references.map((item) => resolveVideoGenerationsUrl(item.url || item.dataUrl, item.storageKey))),
Promise.all(videoReferences.map((item) => resolveVideoGenerationsUrl(item.url, item.storageKey))),
Promise.all(audioReferences.map((item) => resolveVideoGenerationsUrl(item.url, item.storageKey))),
]);
const payload = {
model: modelOptionName(model),
prompt: prompt.trim(),
seconds: normalizeVideoSeconds(config.videoSeconds),
aspect_ratio: normalizeVideoSize(config.size) || "16:9",
resolution: normalizeVideoResolution(config.vquality),
generate_audio: boolConfig(config.videoGenerateAudio, true),
...(imageUrls.length ? { image_urls: imageUrls } : {}),
...(videoUrls.length ? { video_urls: videoUrls } : {}),
...(audioUrls.length ? { audio_urls: audioUrls } : {}),
};
try {
const created = unwrapVideoResponse(await channelPost<ApiVideoResponse>(config, aiApiUrl(config, "/video/generations"), payload, options));
const id = videoTaskId(created);
if (!id) throw new Error("NewAPI Video Generations 没有返回任务 ID");
return { id, provider: "video-generations", model };
} catch (error) {
throw new Error(readAxiosError(error, "NewAPI Video Generations 任务创建失败"));
}
}
async function pollVideoGenerationsTask(config: ResolvedAiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> {
try {
const raw = await channelGet<ApiEnvelope<Record<string, unknown>>>(config, aiApiUrl(config, `/video/generations/${encodeURIComponent(task.id)}`), options);
const state = unwrapEnvelopeRecord(raw);
const status = String(state.status || "").toUpperCase();
if (status === "SUCCESS" || status === "SUCCEEDED" || status === "COMPLETED") {
const url = String(state.result_url || state.video_url || state.url || "");
if (!url) return { status: "failed", error: "视频任务已完成但没有返回视频地址" };
return { status: "completed", result: await videoResultFromUrl(url, options) };
}
if (status === "FAILURE" || status === "FAILED" || status === "CANCELLED") return { status: "failed", error: String(state.fail_reason || state.error || "视频生成失败") };
return { status: "pending" };
} catch (error) {
throw new Error(readAxiosError(error, "NewAPI Video Generations 任务查询失败"));
}
}
async function resolveVideoGenerationsUrl(value: string | undefined, storageKey?: string) {
if (storageKey?.startsWith("resource:")) return getResourceOSSUrl(storageKey);
if (isPublicMediaUrl(value || "")) return String(value);
throw new Error("NewAPI Video Generations 的参考素材需要公网 URL;请先把素材保存到 OSS");
}
type GeminiVeoOperation = {
name?: string;
done?: boolean;
error?: { message?: string };
response?: Record<string, unknown>;
};
async function createGeminiVeoTask(config: ResolvedAiConfig, model: string, prompt: string, references: ReferenceImage[], videoReferences: ReferenceVideo[], audioReferences: ReferenceAudio[], options?: RequestOptions): Promise<VideoGenerationTask> {
if (references.length > 1 || videoReferences.length || audioReferences.length) throw new Error("Gemini Veo 当前只支持 1 张起始图,不支持参考视频或音频");
const instance: Record<string, unknown> = { prompt: prompt.trim() };
if (references[0]) {
const dataUrl = await imageToDataUrl(references[0]);
const matched = /^data:([^;,]+);base64,(.+)$/s.exec(dataUrl);
if (!matched) throw new Error("Gemini Veo 起始图读取失败");
instance.image = { bytesBase64Encoded: matched[2], mimeType: matched[1] };
}
const payload = {
instances: [instance],
parameters: {
aspectRatio: normalizeVideoSize(config.size) || "16:9",
durationSeconds: Number.parseInt(normalizeVideoSeconds(config.videoSeconds), 10) || 6,
resolution: normalizeVideoResolution(config.vquality),
sampleCount: 1,
},
};
try {
const response = await channelPost<GeminiVeoOperation>(config, geminiVeoCreateUrl(config, modelOptionName(model)), payload, options);
if (!response.name) throw new Error("Gemini Veo 没有返回 operation name");
return { id: response.name, provider: "gemini-veo", model };
} catch (error) {
throw new Error(readAxiosError(error, "Gemini Veo 任务创建失败"));
}
}
async function pollGeminiVeoTask(config: ResolvedAiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> {
try {
const operation = await channelGet<GeminiVeoOperation>(config, geminiVeoOperationUrl(config, task.id), options);
if (operation.error?.message) return { status: "failed", error: operation.error.message };
if (!operation.done) return { status: "pending" };
const url = findGeminiVideoURL(operation.response);
if (!url) return { status: "failed", error: "Gemini Veo 任务已完成但没有返回视频地址" };
const blob = (await axios.get<Blob>(url, { headers: geminiVeoHeaders(config), responseType: "blob", signal: options?.signal })).data;
await assertVideoBlob(blob);
return { status: "completed", result: { blob } };
} catch (error) {
throw new Error(readAxiosError(error, "Gemini Veo 任务查询失败"));
}
}
function geminiVeoCreateUrl(config: ResolvedAiConfig, model: string) {
return `${geminiVeoBaseUrl(config)}/models/${encodeURIComponent(model)}:predictLongRunning`;
}
function geminiVeoOperationUrl(config: ResolvedAiConfig, operationName: string) {
return `${geminiVeoBaseUrl(config)}/${operationName.replace(/^\/+/, "")}`;
}
function geminiVeoBaseUrl(config: ResolvedAiConfig) {
const base = config.baseUrl.replace(/\/+$/, "");
return /\/v1beta$/i.test(base) ? base : `${base}/v1beta`;
}
function geminiVeoHeaders(config: ResolvedAiConfig, contentType?: string) {
return { "x-goog-api-key": config.apiKey, ...(contentType ? { "Content-Type": contentType } : {}) };
}
async function channelPost<T>(config: ResolvedAiConfig, upstreamUrl: string, body: unknown, options?: RequestOptions) {
const request = channelRequest(config, upstreamUrl, { "Content-Type": "application/json" });
return (await axios.post<T>(request.url, body, { headers: request.headers, withCredentials: request.credentials === "include", signal: options?.signal })).data;
}
async function channelGet<T>(config: ResolvedAiConfig, upstreamUrl: string, options?: RequestOptions) {
const request = channelRequest(config, upstreamUrl);
return (await axios.get<T>(request.url, { headers: request.headers, withCredentials: request.credentials === "include", signal: options?.signal })).data;
}
function findGeminiVideoURL(value: unknown): string {
if (!value || typeof value !== "object") return "";
if (Array.isArray(value)) {
for (const item of value) {
const found = findGeminiVideoURL(item);
if (found) return found;
}
return "";
}
const record = value as Record<string, unknown>;
for (const key of ["uri", "url", "videoUri", "video_url"]) {
if (typeof record[key] === "string" && /^https?:\/\//i.test(record[key])) return record[key];
}
for (const child of Object.values(record)) {
const found = findGeminiVideoURL(child);
if (found) return found;
}
return "";
}
function unwrapEnvelopeRecord(value: ApiEnvelope<Record<string, unknown>>) {
if (value && typeof value === "object" && "data" in value && value.data && typeof value.data === "object") return value.data;
return value as Record<string, unknown>;
} }
export async function storeGeneratedVideo(result: VideoGenerationResult): Promise<UploadedFile> { export async function storeGeneratedVideo(result: VideoGenerationResult): Promise<UploadedFile> {
@@ -93,7 +256,7 @@ async function createOpenAIVideoTask(config: ResolvedAiConfig, model: string, pr
}; };
try { try {
const createPath = config.interfaceType === "xai-video" ? "/videos/generations" : "/videos"; const createPath = config.interfaceType === "xai-video" ? "/videos/generations" : "/videos";
const created = unwrapVideoResponse((await axios.post<ApiVideoResponse>(aiApiUrl(config, createPath), payload, { headers: aiHeaders(config, "application/json"), signal: options?.signal })).data); const created = unwrapVideoResponse(config.interfaceType === "xai-video" ? await channelPost<ApiVideoResponse>(config, aiApiUrl(config, createPath), payload, options) : (await axios.post<ApiVideoResponse>(aiApiUrl(config, createPath), payload, { headers: aiHeaders(config, "application/json"), signal: options?.signal })).data);
const id = videoTaskId(created); const id = videoTaskId(created);
if (!id) throw new Error("视频接口没有返回任务 ID"); if (!id) throw new Error("视频接口没有返回任务 ID");
return { id, provider: "openai", model }; return { id, provider: "openai", model };
@@ -121,8 +284,10 @@ async function createOpenAIVideoTask(config: ResolvedAiConfig, model: string, pr
async function pollOpenAIVideoTask(config: ResolvedAiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> { async function pollOpenAIVideoTask(config: ResolvedAiConfig, task: VideoGenerationTask, options?: RequestOptions): Promise<VideoGenerationTaskState> {
try { try {
const video = unwrapVideoResponse((await axios.get<ApiVideoResponse>(aiApiUrl(config, `/videos/${task.id}`), { headers: aiHeaders(config), signal: options?.signal })).data); const video = unwrapVideoResponse(config.interfaceType === "xai-video" ? await channelGet<ApiVideoResponse>(config, aiApiUrl(config, `/videos/${task.id}`), options) : (await axios.get<ApiVideoResponse>(aiApiUrl(config, `/videos/${task.id}`), { headers: aiHeaders(config), signal: options?.signal })).data);
if (video.status === "completed" || video.status === "succeeded" || video.status === "success" || video.status === "done") { if (video.status === "completed" || video.status === "succeeded" || video.status === "success" || video.status === "done") {
const resultUrl = video.video?.url || video.video_url || video.result_url;
if (resultUrl) return { status: "completed", result: await videoResultFromUrl(resultUrl, options) };
const content = await axios.get<Blob>(aiApiUrl(config, `/videos/${task.id}/content`), { headers: aiHeaders(config), responseType: "blob", signal: options?.signal }); const content = await axios.get<Blob>(aiApiUrl(config, `/videos/${task.id}/content`), { headers: aiHeaders(config), responseType: "blob", signal: options?.signal });
await assertVideoBlob(content.data); await assertVideoBlob(content.data);
return { status: "completed", result: { blob: content.data } }; return { status: "completed", result: { blob: content.data } };
@@ -316,7 +481,7 @@ function assertVideoConfig(config: AiConfig, model: string) {
if (!model) throw new Error("请先配置视频模型"); if (!model) throw new Error("请先配置视频模型");
if (!config.baseUrl.trim()) throw new Error("请先配置 Base URL"); if (!config.baseUrl.trim()) throw new Error("请先配置 Base URL");
if (!config.apiKey.trim()) throw new Error("请先配置 API Key"); if (!config.apiKey.trim()) throw new Error("请先配置 API Key");
if (config.apiFormat === "gemini") throw new Error("Gemini 调用格式暂不支持视频生成,请使用 OpenAI 格式渠道"); if (config.apiFormat === "gemini" && config.interfaceType !== "gemini-veo") throw new Error("当前 Gemini 文本协议不支持视频生成,请为该模型选择 Gemini Veo 协议");
} }
function normalizeVideoSeconds(value: string) { function normalizeVideoSeconds(value: string) {
+1
View File
@@ -65,6 +65,7 @@ export type ChannelModel = {
modelKey: string; modelKey: string;
displayName: string; displayName: string;
capability: "text" | "image" | "video" | "audio"; capability: "text" | "image" | "video" | "audio";
protocol: import("@/lib/model-protocols").ModelProtocol;
billingMode: "fixed_request" | "per_second"; billingMode: "fixed_request" | "per_second";
unitPriceMicrocredits: number; unitPriceMicrocredits: number;
priceConfigured: boolean; priceConfigured: boolean;
+13 -10
View File
@@ -4,10 +4,11 @@ import { createJSONStorage, persist } from "zustand/middleware";
import { nanoid } from "nanoid"; import { nanoid } from "nanoid";
import { scopedLocalStorage } from "@/lib/user-scope"; import { scopedLocalStorage } from "@/lib/user-scope";
import { modelProtocolCapability, normalizeModelProtocol, type ModelProtocol } from "@/lib/model-protocols";
import { normalizeVideoDuration, normalizeVideoResolution } from "@/lib/video-generation-options"; import { normalizeVideoDuration, normalizeVideoResolution } from "@/lib/video-generation-options";
export type ApiCallFormat = "openai" | "gemini"; export type ApiCallFormat = "openai" | "gemini";
export type ChannelInterfaceType = "chat-completion" | "openai-response" | "openai-image" | "newapi" | "newapi-channel-1" | "newapi-channel-2" | "xai-video"; export type ChannelInterfaceType = ModelProtocol;
export type ModelChannel = { export type ModelChannel = {
id: string; id: string;
@@ -25,6 +26,7 @@ export type ModelChannel = {
model: string; model: string;
displayName?: string; displayName?: string;
capability: ModelCapability; capability: ModelCapability;
protocol?: ModelProtocol;
billingMode: "fixed_request" | "per_second"; billingMode: "fixed_request" | "per_second";
unitPriceMicrocredits: number; unitPriceMicrocredits: number;
}>; }>;
@@ -299,7 +301,7 @@ export function createModelChannel(channel?: Partial<ModelChannel>): ModelChanne
scope: channel?.scope === "system" ? "system" : "user", scope: channel?.scope === "system" ? "system" : "user",
enabled: channel?.enabled !== false, enabled: channel?.enabled !== false,
hasApiKey: channel?.hasApiKey, hasApiKey: channel?.hasApiKey,
modelCosts: channel?.modelCosts, modelCosts: channel?.modelCosts?.map((item) => ({ ...item, protocol: normalizeModelProtocol(item.protocol) })),
}; };
} }
@@ -373,13 +375,16 @@ export function resolveModelChannel(config: AiConfig, value: string) {
export function resolveModelRequestConfig(config: AiConfig, value: string) { export function resolveModelRequestConfig(config: AiConfig, value: string) {
const channel = resolveModelChannel(config, value); const channel = resolveModelChannel(config, value);
const model = modelOptionName(value || config.model);
const modelProtocol = channel.modelCosts?.find((item) => item.model === model)?.protocol;
const interfaceType = modelProtocol || channel.interfaceType;
return { return {
...config, ...config,
model: modelOptionName(value || config.model), model,
baseUrl: channel.baseUrl, baseUrl: channel.baseUrl,
apiKey: channel.apiKey, apiKey: channel.apiKey,
apiFormat: channel.apiFormat, apiFormat: interfaceType ? (interfaceType === "gemini-veo" ? "gemini" as const : "openai" as const) : channel.apiFormat,
interfaceType: channel.interfaceType, interfaceType,
channelId: channel.scope === "system" ? channel.id : "", channelId: channel.scope === "system" ? channel.id : "",
}; };
} }
@@ -426,15 +431,13 @@ export function defaultBaseUrlForApiFormat(apiFormat: ApiCallFormat) {
} }
export function defaultBaseUrlForChannelInterface(interfaceType?: ChannelInterfaceType) { export function defaultBaseUrlForChannelInterface(interfaceType?: ChannelInterfaceType) {
if (interfaceType === "gemini-veo") return GEMINI_BASE_URL;
if (interfaceType === "newapi" || interfaceType === "newapi-channel-1" || interfaceType === "newapi-channel-2" || interfaceType === "xai-video") return ""; if (interfaceType === "newapi" || interfaceType === "newapi-channel-1" || interfaceType === "newapi-channel-2" || interfaceType === "xai-video") return "";
return OPENAI_BASE_URL; return OPENAI_BASE_URL;
} }
function capabilityForChannelInterface(interfaceType?: ChannelInterfaceType): ModelCapability | undefined { function capabilityForChannelInterface(interfaceType?: ChannelInterfaceType): ModelCapability | undefined {
if (interfaceType === "chat-completion" || interfaceType === "openai-response") return "text"; return modelProtocolCapability(interfaceType);
if (interfaceType === "openai-image") return "image";
if (interfaceType === "newapi" || interfaceType === "newapi-channel-1" || interfaceType === "newapi-channel-2" || interfaceType === "xai-video") return "video";
return undefined;
} }
function normalizeApiFormat(apiFormat: unknown): ApiCallFormat { function normalizeApiFormat(apiFormat: unknown): ApiCallFormat {
@@ -442,7 +445,7 @@ function normalizeApiFormat(apiFormat: unknown): ApiCallFormat {
} }
function normalizeChannelInterfaceType(value: unknown): ChannelInterfaceType | undefined { function normalizeChannelInterfaceType(value: unknown): ChannelInterfaceType | undefined {
return value === "chat-completion" || value === "openai-response" || value === "openai-image" || value === "newapi" || value === "newapi-channel-1" || value === "newapi-channel-2" || value === "xai-video" ? value : undefined; return normalizeModelProtocol(value);
} }
function uniqueRawModels(models: string[]) { function uniqueRawModels(models: string[]) {