feat(image): 以插件声明统一图片参数、尺寸选择与定价合同 (#760)

* feat(image): 图片参数 - 统一插件声明配置与生成合同

* docs(image): 图片参数 - 说明声明合同与验证边界

* fix(plugins): 图片声明 - 保留内联素材支持并同步制品文档

* fix(image): 参数合同 - 对齐审批意图和尺寸预检调用方

* fix(image): 调用链 - 保留公开意图并接通独立分辨率

* fix(image): 图片参数 - 补齐分辨率接线与目录价格投影
This commit is contained in:
huiku authored and GitHub committed 2026-10-13 19:18:21 +08:00
1 parent 88de4ce422
commit 7466119867
104 files changed
+6013 -568

No files matched your search

@@ -219,6 +219,29 @@ func TestRepriceTierFieldValidation(t *testing.T) {
}
}
func TestNormalizeChannelModelTierSelectorAcceptsLegacyTypoWithoutCollidingWithPixelTier(t *testing.T) {
for _, key := range []string{"resoluton"} {
t.Run(key, func(t *testing.T) {
selector, resolution, videoSeconds, err := normalizeChannelModelTierSelector("image", ChannelModelPriceTierRequest{
Selector: map[string]string{key: "2K"},
})
if err != nil {
t.Fatal(err)
}
if selector["imageResolution"] != "2k" || selector[key] != "" || resolution != "*" || videoSeconds != 0 {
t.Fatalf("selector=%v resolution=%q videoSeconds=%d", selector, resolution, videoSeconds)
}
})
}
}
func TestImageTierSelectorDoesNotOverwriteIndependentResolution(t *testing.T) {
selector, _, _, err := normalizeChannelModelTierSelector("image", ChannelModelPriceTierRequest{Selector: map[string]string{"imageResolution": "1k", "resolution": "2k"}})
if err != nil || selector["imageResolution"] != "1k" || selector["resolution"] != "2k" {
t.Fatalf("selector = %#v, err=%v", selector, err)
}
}
func TestBatchRepricingRollsBackOnConcurrentChange(t *testing.T) {
for _, target := range []string{"model", "tier"} {
t.Run(target, func(t *testing.T) {
@@ -263,7 +286,7 @@ func TestNormalizeChannelModelTierSelectorAcceptsResolutionTypo(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if selector["resolution"] != "2k" || selector["resoluton"] != "" || resolution != "*" || videoSeconds != 0 {
if selector["imageResolution"] != "2k" || selector["resoluton"] != "" || resolution != "*" || videoSeconds != 0 {
t.Fatalf("selector=%v resolution=%q videoSeconds=%d", selector, resolution, videoSeconds)
}
}
+7 -5
View File
@@ -106,7 +106,7 @@ func (s *Service) AdminChannelModels(actor *model.User, channelID string) ([]mod
if decodeErr != nil || config == nil {
continue
}
normalized, normalizeErr := NormalizeModelCapabilityConfigForModel(items[index].Capability, string(items[index].Protocol), firstNonEmpty(items[index].ProviderModelKey, items[index].ModelKey), config)
normalized, normalizeErr := NormalizeModelCapabilityConfigForModel(items[index].Capability, string(items[index].Protocol), firstNonEmpty(items[index].ProviderModelKey, items[index].ModelKey), config, s.protocolRegistry())
if normalizeErr != nil || normalized == nil {
continue
}
@@ -171,9 +171,11 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
return nil, BadAuthRequest("该渠道已存在模型 " + modelKey + ",请直接编辑已有模型")
}
if capability == "text" || capability == "image" || capability == "video" {
if _, err := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig); err != nil {
return nil, err
validated, validateErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig, s.protocolRegistry())
if validateErr != nil {
return nil, validateErr
}
req.CapabilityConfig = validated
}
tiers, err := s.normalizeChannelModelPriceTiers(req, capability, protocol, providerModelKey)
if err != nil {
@@ -216,7 +218,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
item.Protocol = protocol
s.applyChannelModelPriceTierSummary(item, tiers)
if capability == "text" || capability == "image" || capability == "video" {
capabilityConfig, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig)
capabilityConfig, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig, s.protocolRegistry())
if normalizeErr != nil {
return nil, normalizeErr
}
@@ -235,7 +237,7 @@ func (s *Service) SaveAdminChannelModel(actor *model.User, channelID string, id
if req.Enabled != nil {
item.Enabled = *req.Enabled
}
if err := validateChannelModelTierCapabilities(tiers, item.CapabilityConfigJSON, capability); err != nil {
if err := validateChannelModelTierCapabilities(tiers, item.CapabilityConfigJSON, capability, string(protocol)); err != nil {
return nil, err
}
// 渠道模型及所有价格档必须同时落库,不能出现“能力已开放但规格价格尚未更新”的窗口。
+77 -6
View File
@@ -8,9 +8,44 @@ import (
"strings"
"yingce/backend/internal/model"
protocolcontract "yingce/backend/internal/protocol"
)
func validateChannelModelTierCapabilities(tiers []model.ChannelModelPriceTier, rawCapabilityConfig string, capability string) error {
func validateChannelModelTierCapabilities(tiers []model.ChannelModelPriceTier, rawCapabilityConfig string, capability string, protocol string) error {
if capability == "image" {
config, err := DecodeModelCapabilityConfig(rawCapabilityConfig)
if err != nil || config == nil || config.Image == nil {
return BadAuthRequest("图片模型能力配置无效,无法校验价格档规格")
}
image := config.Image
if image.Parameters != nil {
for _, tier := range tiers {
if err := validateImageParameterPriceSelector(image.Parameters, tier.Selector); err != nil {
return err
}
}
return nil
}
normalizeLegacyImageResolutionConfig(protocol, image)
for _, tier := range tiers {
if value := strings.TrimSpace(tier.Selector["imageResolution"]); value != "" && value != "*" && !image.Resolution.Supported {
return BadAuthRequest("价格档使用了未启用的图片分辨率条件")
}
if value := strings.TrimSpace(tier.Selector["imageResolution"]); value != "" && value != "*" && !containsCapabilityString(image.Resolution.Values, value) {
return BadAuthRequest("价格档分辨率不在该图片模型支持范围内:" + value)
}
if value := strings.TrimSpace(tier.Selector["quality"]); value != "" && value != "*" {
if image.Quality.Supported {
if !containsCapabilityString(image.Quality.Values, value) {
return BadAuthRequest("价格档质量不在该图片模型支持范围内:" + value)
}
} else if !legacyImageResolutionProtocol(protocol) || !image.Resolution.Supported || !containsCapabilityString(image.Resolution.Values, value) {
return BadAuthRequest("价格档使用了未启用的图片质量条件")
}
}
}
return nil
}
if capability != "video" {
return nil
}
@@ -80,7 +115,11 @@ func (s *Service) normalizeChannelModelPriceTiers(req ChannelModelRequest, capab
result := make([]model.ChannelModelPriceTier, 0, len(inputs))
seen := make(map[string]bool, len(inputs))
for _, input := range inputs {
selector, resolution, videoSeconds, selectorErr := normalizeChannelModelTierSelector(capability, input)
var parameters []protocolcontract.ImageParameter
if req.CapabilityConfig != nil && req.CapabilityConfig.Image != nil {
parameters = req.CapabilityConfig.Image.Parameters
}
selector, resolution, videoSeconds, selectorErr := normalizeChannelModelTierSelector(capability, input, parameters)
if selectorErr != nil {
return nil, selectorErr
}
@@ -126,7 +165,27 @@ func (s *Service) normalizeChannelModelPriceTiers(req ChannelModelRequest, capab
return result, nil
}
func normalizeChannelModelTierSelector(capability string, input ChannelModelPriceTierRequest) (map[string]string, string, int, error) {
func normalizeChannelModelTierSelector(capability string, input ChannelModelPriceTierRequest, parameters ...[]protocolcontract.ImageParameter) (map[string]string, string, int, error) {
if capability == "image" && len(parameters) > 0 && parameters[0] != nil {
if input.VideoSeconds != 0 || input.Resolution != "" && input.Resolution != "*" {
return nil, "", 0, BadAuthRequest("图片价格不接受视频规格")
}
selector := make(map[string]string, len(input.Selector))
for name, value := range input.Selector {
name, value = strings.TrimSpace(name), strings.TrimSpace(value)
if name == "" || value == "" || value == "*" {
continue
}
if _, exists := selector[name]; exists {
return nil, "", 0, BadAuthRequest("价格档存在重复规格条件:" + name)
}
selector[name] = value
}
if err := validateImageParameterPriceSelector(parameters[0], selector); err != nil {
return nil, "", 0, err
}
return selector, "*", 0, nil
}
selector := make(map[string]string, len(input.Selector)+3)
for rawKey, rawValue := range input.Selector {
key := strings.TrimSpace(rawKey)
@@ -137,14 +196,21 @@ func normalizeChannelModelTierSelector(capability string, input ChannelModelPric
switch key {
case "operation":
value = strings.ToLower(value)
case "quality", "size":
case "quality", "imageResolution", "size":
value = strings.ToLower(value)
if value == "auto" || value == "any" {
value = "*"
}
case "resoluton":
// Normalize the historical misspelling at the input boundary.
key = "imageResolution"
value = strings.ToLower(strings.TrimSpace(value))
if value == "auto" || value == "any" {
value = "*"
}
case "vquality":
value = normalizeChannelModelTierResolution(value)
case "resolution", "resoluton":
case "resolution":
// 兼容图片价格档的标准字段,以及历史接口误拼写 resoluton。
key = "resolution"
value = strings.ToLower(strings.TrimSpace(value))
@@ -178,7 +244,12 @@ func normalizeChannelModelTierSelector(capability string, input ChannelModelPric
return nil, "", 0, BadAuthRequest("视频价格档音频条件必须为 true、false 或 *")
}
default:
return nil, "", 0, BadAuthRequest("价格档不支持规格字段:" + key)
if capability != "image" {
return nil, "", 0, BadAuthRequest("价格档不支持规格字段:" + key)
}
}
if existing, exists := selector[key]; exists && existing != value {
return nil, "", 0, BadAuthRequest("价格档存在重复规格条件:" + key)
}
selector[key] = value
}
@@ -25,7 +25,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
return nil, err
}
if capability == "text" || capability == "image" || capability == "video" {
if _, err := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig); err != nil {
if _, err := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig, s.protocolRegistry()); err != nil {
return nil, err
}
}
@@ -58,7 +58,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
var videoProfile *VideoCapabilityConfig
switch capability {
case "image":
profile, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig)
profile, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig, s.protocolRegistry())
if normalizeErr != nil {
return nil, normalizeErr
}
@@ -67,7 +67,7 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
case "video":
// 视频测试必须带上模型能力画像:声明式协议只按画像里的枚举回填分辨率名(如 480 -> 480p),
// 没有画像时会把裸数字发给上游,火山方舟等供应商会直接拒绝。
profile, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig)
profile, normalizeErr := NormalizeModelCapabilityConfigForModel(capability, string(protocol), providerModelKey, req.CapabilityConfig, s.protocolRegistry())
if normalizeErr != nil {
return nil, normalizeErr
}
@@ -102,6 +102,15 @@ func (s *Service) TestAdminChannelModel(ctx context.Context, actor *model.User,
}
if capability == "image" {
input.ImageCapability = imageProfile
if imageProfile.Parameters != nil {
input.Config.ImageParameters = imageParameterDefaults(imageProfile.Parameters)
}
if imageProfile.Resolution.Supported {
input.Config.ImageResolution = imageProfile.Resolution.Default
}
if err := applyImageParameterValues(&input.Config, imageProfile); err != nil {
return nil, err
}
}
if capability == "video" {
input.VideoCapability = videoProfile
@@ -184,12 +184,12 @@ func TestCloudAgentImageApprovalEditsAreValidatedAndIdempotent(t *testing.T) {
t.Fatal(err)
}
id := state.Approval.ID
settings := CloudAgentMediaSettings{ChannelID: "channel", ChannelModelKey: "grok-image-alternative", Size: "16:9", Quality: "1k"}
settings := CloudAgentMediaSettings{ChannelID: "channel", ChannelModelKey: "grok-image-alternative", Size: "16:9", ImageResolution: "1k"}
for _, invalid := range []CloudAgentMediaSettings{
{ChannelID: "channel", ChannelModelKey: "missing", Size: "16:9", Quality: "1k"},
{ChannelID: "channel", ChannelModelKey: "text-test", Size: "16:9", Quality: "1k"},
{ChannelID: "channel", ChannelModelKey: "missing", Size: "16:9", ImageResolution: "1k"},
{ChannelID: "channel", ChannelModelKey: "text-test", Size: "16:9", ImageResolution: "1k"},
{LogicalModelID: "mixed", ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "16:9"},
{ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "invalid-size", Quality: "1k"},
{ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "invalid-size", ImageResolution: "1k"},
{ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "16:9", Quality: "invalid-quality"},
} {
if err := s.DecideCloudAgentApproval("user", run.ID, id, "approve", "", &invalid); err == nil {
@@ -242,7 +242,7 @@ func TestCloudAgentImageApprovalEditsAreValidatedAndIdempotent(t *testing.T) {
if err := json.Unmarshal([]byte(task.InputJSON), &input); err != nil {
t.Fatal(err)
}
if input.Config.Model != settings.ChannelModelKey || input.Config.Size != settings.Size || input.Config.Quality != settings.Quality || task.Prompt != approvedArgs.Prompt || len(input.ReferenceImages) != 1 {
if input.Config.Model != settings.ChannelModelKey || input.Config.Size != settings.Size || input.Config.ImageResolution != settings.ImageResolution || input.Config.Quality != settings.Quality || task.Prompt != approvedArgs.Prompt || len(input.ReferenceImages) != 1 {
t.Fatalf("approved inputs were lost: %+v", input.Config)
}
var count int64
@@ -33,6 +33,12 @@ func cloudAgentGenerationSpec(a cloudAgentMediaArgs, refs map[string]any, resolv
} else if a.Mode == "image" {
count := 1
options.Count = &count
if a.ImageResolution != "" {
options.ImageResolution = &a.ImageResolution
}
if a.ImageParameters != "" {
options.ImageParameters = &a.ImageParameters
}
if a.Quality != "" {
options.Quality = &a.Quality
}
@@ -104,6 +104,8 @@ type cloudAgentMediaArgs struct {
ChannelModelKey string `json:"channelModelKey"`
Duration int `json:"durationSeconds"`
Size string `json:"size"`
ImageResolution string `json:"imageResolution"`
ImageParameters string `json:"imageParameters,omitempty"`
Quality string `json:"quality"`
VideoGenerateAudio *bool `json:"videoGenerateAudio"`
VideoWatermark *bool `json:"videoWatermark"`
@@ -15,6 +15,8 @@ type CloudAgentMediaSettings struct {
ChannelID string `json:"channelId,omitempty"`
ChannelModelKey string `json:"channelModelKey,omitempty"`
Size string `json:"size"`
ImageResolution string `json:"imageResolution,omitempty"`
ImageParameters string `json:"imageParameters,omitempty"`
Quality string `json:"quality"`
DurationSeconds *int `json:"durationSeconds,omitempty"`
VideoGenerateAudio *bool `json:"videoGenerateAudio,omitempty"`
@@ -41,7 +43,8 @@ func (s *Service) updateCloudAgentMediaApproval(repo *repository.Repository, run
return BadAuthRequest("仅图片或视频生成审批支持修改模型和规格")
}
args.LogicalModelID, args.ChannelID, args.ChannelModelKey = settings.LogicalModelID, settings.ChannelID, settings.ChannelModelKey
args.Size, args.Quality = settings.Size, settings.Quality
args.Size, args.ImageResolution, args.Quality = settings.Size, settings.ImageResolution, settings.Quality
args.ImageParameters = settings.ImageParameters
if args.Mode == "video" {
if settings.DurationSeconds != nil {
if *settings.DurationSeconds < 0 {
@@ -75,14 +78,12 @@ func (s *Service) updateCloudAgentMediaApproval(repo *repository.Repository, run
if err != nil {
return err
}
var resolved struct {
Config map[string]any `json:"config"`
}
var resolved map[string]any
if err := json.Unmarshal([]byte(task.InputJSON), &resolved); err != nil {
return err
}
requested, _ := req.Input["config"].(map[string]any)
if err := validateCloudAgentResolvedMediaOptions(requested, resolved.Config); err != nil {
if err := validateCloudAgentResolvedMediaOptions(requested, resolved); err != nil {
return err
}
name, err := s.cloudAgentMediaModelName(args)
@@ -128,9 +129,36 @@ func replaceCloudAgentPreparedLeases(repo *repository.Repository, userID, runID,
return repo.ReplaceCloudAgentResourceLeases(userID, runID, approvalID, ids, prepared.Quote.ExpiresAt)
}
func validateCloudAgentResolvedMediaOptions(requested, resolved map[string]any) error {
for _, key := range []string{"size", "videoSeconds", "vquality", "quality", "count", "videoGenerateAudio", "videoWatermark", "videoArkPrivateAssetUpload"} {
if value := stringValue(requested[key]); value != "" && !strings.EqualFold(value, stringValue(resolved[key])) {
func validateCloudAgentResolvedMediaOptions(requested, resolvedInput map[string]any) error {
resolvedOptions, _ := resolvedInput["capabilityOptions"].(map[string]any)
resolvedConfig, _ := resolvedInput["config"].(map[string]any)
if raw := requested["imageParameters"]; raw != nil {
var values map[string]any
if encoded, ok := raw.(string); ok {
if err := json.Unmarshal([]byte(encoded), &values); err != nil {
return creationConflict("图片参数格式无效")
}
} else {
values, _ = raw.(map[string]any)
}
for name, value := range values {
if resolvedOptions[name] != value {
return creationConflict("模型解析后的图片参数与审批内容不同")
}
}
}
for _, key := range []string{"size", "imageResolution", "videoSeconds", "vquality", "quality", "count", "videoGenerateAudio", "videoWatermark", "videoArkPrivateAssetUpload"} {
requestedValue := stringValue(requested[key])
if key == "quality" && requestedValue != "" {
if _, declared := resolvedOptions[key]; !declared && !strings.EqualFold(requestedValue, stringValue(resolvedOptions["imageResolution"])) {
return creationConflict("所选图片模型未声明质量参数,请使用模型声明的图片分辨率或质量选项")
}
}
resolved := stringValue(resolvedOptions[key])
if resolved == "" {
resolved = stringValue(resolvedConfig[key])
}
if requestedValue != "" && !strings.EqualFold(requestedValue, resolved) {
return creationConflict("模型解析后的生成规格与审批参数不同,请重新读取目录并审批")
}
}
+119 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
@@ -325,7 +326,7 @@ func TestCloudAgentImageCreatesReferencedNode(t *testing.T) {
if err = json.Unmarshal([]byte(task.InputJSON), &input); err != nil {
t.Fatal(err)
}
if task.Operation != "image_to_image" || len(input.ReferenceImages) != 1 || input.Config.Count != "1" || input.Config.Quality != "2k" {
if task.Operation != "image_to_image" || len(input.ReferenceImages) != 1 || input.Config.Count != "1" || input.Config.ImageResolution != "2k" || input.Config.Quality != "" {
t.Fatal("image generation contract was lost")
}
canvas, _ := s.repo.CanvasProjectForUser("user", "agent-canvas")
@@ -570,6 +571,123 @@ func TestCloudAgentModelListFiltersActualReferences(t *testing.T) {
}
}
func TestCloudAgentImageCatalogTreatsUnselectedPricedOptionsAsCandidates(t *testing.T) {
s, db, _, _ := creationTestService(t)
imageModel := seedAgentLogicalImageModel(t, s, db)
intent := ModelRequestIntent{Capability: "image", Inputs: map[string]int{}, Options: map[string]any{}}
models, err := s.PublicLogicalModels(&intent)
if err != nil {
t.Fatal(err)
}
if len(models) != 1 || models[0].ID != imageModel.ID || !models[0].Available || len(models[0].PriceTiers) != 9 {
t.Fatalf("unselected image options should expose the priced candidate and all 9 tiers: %#v", models)
}
adminModels, err := s.AdminLogicalModels(&model.User{ID: "admin", Role: model.UserRoleAdmin})
if err != nil {
t.Fatal(err)
}
if len(adminModels) != 1 || len(adminModels[0].PriceTiers) != 9 {
t.Fatalf("admin projection should expose the route's 9 configured tiers: %#v", adminModels)
}
catalog, err := s.cloudAgentModelList(&intent)
if err != nil {
t.Fatal(err)
}
var logicalEntry map[string]any
for _, entry := range catalog.(map[string]any)["models"].([]map[string]any) {
if entry["selection"].(map[string]any)["logicalModelId"] == imageModel.ID {
logicalEntry = entry
break
}
}
if logicalEntry == nil || len(logicalEntry["priceTiers"].([]PublicLogicalModelPriceTier)) != 9 {
t.Fatalf("agent catalog did not expose the logical candidate with 9 price tiers: %#v", logicalEntry)
}
defaultRoute, err := s.ResolveLogicalModel(imageModel.ID, intent)
if err != nil || defaultRoute.PriceTier == nil {
t.Fatalf("declared model defaults must resolve a priced specification: %v", err)
}
selectedIntent := ModelRequestIntent{Capability: "image", Inputs: map[string]int{}, Options: map[string]any{"imageResolution": "4k", "quality": "max"}}
routed, err := s.ResolveLogicalModel(imageModel.ID, selectedIntent)
if err != nil || routed.PriceTier == nil || routed.PriceTier.ID != "agent-image-4k-max" {
t.Fatalf("complete selection should resolve only its exact price tier: routed=%#v error=%v", routed, err)
}
}
func TestCloudAgentImageCatalogRejectsUnpricedExplicitCombination(t *testing.T) {
s, db, _, _ := creationTestService(t)
imageModel := seedAgentLogicalImageModel(t, s, db)
if err := db.Where("channel_model_id = ? AND selector_json = ?", "agent-image-cm", "{\"imageResolution\":\"4k\",\"quality\":\"max\"}").Delete(&model.ChannelModelPriceTier{}).Error; err != nil {
t.Fatal(err)
}
s.invalidateRouteCatalog()
intent := ModelRequestIntent{Capability: "image", Inputs: map[string]int{}, Options: map[string]any{"imageResolution": "4k", "quality": "max"}}
models, err := s.PublicLogicalModels(&intent)
if err != nil {
t.Fatal(err)
}
if len(models) != 1 || models[0].ID != imageModel.ID || models[0].Available {
t.Fatalf("supported but unpriced explicit combination must not be available: %#v", models)
}
catalog, err := s.cloudAgentModelList(&intent)
if err != nil {
t.Fatal(err)
}
encoded, _ := json.Marshal(catalog)
if strings.Contains(string(encoded), "\"logicalModelId\":\""+imageModel.ID+"\"") {
t.Fatalf("agent exposed a model with no price tier for the explicit combination: %s", encoded)
}
if _, err := s.ResolveLogicalModel(imageModel.ID, intent); err == nil {
t.Fatal("strict routing accepted an explicitly unpriced combination")
}
}
func seedAgentLogicalImageModel(t *testing.T, s *Service, db *gorm.DB) model.LogicalModel {
t.Helper()
if err := db.Create(&model.SystemSetting{Key: featureAvailabilitySettingKey, ValueJSON: "{\"frontendModelsEnabled\":true}"}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ModelChannel{ID: "agent-image-channel", Scope: model.ChannelScopeSystem, Enabled: true, Name: "Agent image test"}).Error; err != nil {
t.Fatal(err)
}
config := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceOpenAIImage), "gpt-image-2.5-sunburst")
config.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"1k", "2k", "4k"}, Default: "1k"}
config.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"medium", "high", "max"}, Default: "medium"}
if err := db.Create(&model.ChannelModel{ID: "agent-image-cm", ChannelID: "agent-image-channel", ModelKey: "gpt-image-2.5-sunburst", DisplayName: "Sunburst", Capability: "image", Protocol: model.ChannelInterfaceOpenAIImage, CapabilityConfigJSON: mustEncodeModelCapabilityConfig(t, config), BillingMode: "fixed_request", PriceConfigured: true, Enabled: true}).Error; err != nil {
t.Fatal(err)
}
for _, resolution := range []string{"1k", "2k", "4k"} {
for _, quality := range []string{"medium", "high", "max"} {
selector := fmt.Sprintf("{\"imageResolution\":%q,\"quality\":%q}", resolution, quality)
if err := db.Create(&model.ChannelModelPriceTier{ID: "agent-image-" + resolution + "-" + quality, ChannelModelID: "agent-image-cm", SelectorKey: selector, SelectorJSON: selector, BillingMode: "fixed_request", UnitPriceMicrocredits: 100, PriceConfigured: true, Enabled: true}).Error; err != nil {
t.Fatal(err)
}
}
}
spec, err := CapabilitySpecFromModelCapabilityConfig(config, "image")
if err != nil {
t.Fatal(err)
}
specJSON, err := json.Marshal(spec)
if err != nil {
t.Fatal(err)
}
imageModel := model.LogicalModel{ID: "agent-sunburst", Code: "agent-sunburst", Name: "Sunburst", Capability: "image", Enabled: true, ActiveRevisionID: "agent-sunburst-revision", PricePolicy: "channel", BillingMode: "fixed_request"}
revision := model.LogicalModelRevision{ID: imageModel.ActiveRevisionID, LogicalModelID: imageModel.ID, Version: 1, CapabilitySpecJSON: string(specJSON), DefaultOptionsJSON: "{}"}
route := model.LogicalModelRoute{ID: "agent-sunburst-route", LogicalModelRevisionID: revision.ID, ChannelModelID: "agent-image-cm", Enabled: true, Weight: 1}
for _, row := range []any{&imageModel, &revision, &route} {
if err := db.Create(row).Error; err != nil {
t.Fatal(err)
}
}
s.invalidateRouteCatalog()
return imageModel
}
func TestCloudAgentMediaDraftReuseLifecycle(t *testing.T) {
for _, tc := range []struct {
name, status, ownerUser, ownerCanvas string
@@ -156,7 +156,10 @@ func cloudAgentResolvedMediaHash(task *model.Task) (string, error) {
}
config, _ := input["config"].(map[string]any)
public := map[string]any{}
for _, key := range []string{"channelId", "channelModelKey", "providerModelKey", "priceTierId", "model", "apiFormat", "interfaceType", "capabilityConfig", "size", "quality", "transparentBackground", "count", "videoSeconds", "vquality", "videoGenerateAudio", "videoWatermark", "audioVoice", "audioFormat", "audioSpeed", "audioInstructions"} {
if values, exists := config["imageParameters"]; exists {
public["imageParameters"] = values
}
for _, key := range []string{"channelId", "channelModelKey", "providerModelKey", "priceTierId", "model", "apiFormat", "interfaceType", "capabilityConfig", "size", "imageResolution", "quality", "transparentBackground", "count", "videoSeconds", "vquality", "videoGenerateAudio", "videoWatermark", "audioVoice", "audioFormat", "audioSpeed", "audioInstructions"} {
if value, exists := config[key]; exists {
public[key] = value
}
@@ -99,8 +99,7 @@ func (s *Service) enqueueCloudAgentTask(run *model.CloudAgentExecution, state *c
}
if media != nil {
requested, _ := req.Input["config"].(map[string]any)
resolved, _ := input["config"].(map[string]any)
if err := validateCloudAgentResolvedMediaOptions(requested, resolved); err != nil {
if err := validateCloudAgentResolvedMediaOptions(requested, input); err != nil {
return s.cloudAgentMediaError(run, state, "admission", false, false, err)
}
}
+38 -13
View File
@@ -543,7 +543,11 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
}
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
priceTierID, _ := config["priceTierId"].(string)
snapshotCreditCost(order, channelModelPriceTierForBilling(*channelModel, priceTierID, capability, intent), requestedBillingQuantity(capability, config), tokenEstimate)
costTier, err := s.channelModelPriceTierForBilling(*channelModel, priceTierID, capability, intent)
if err != nil {
return nil, err
}
snapshotCreditCost(order, costTier, requestedBillingQuantity(capability, config), tokenEstimate)
return order, nil
}
@@ -587,7 +591,10 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
if err != nil {
return nil, err
}
tier := channelModelPriceTierForBilling(*item, priceTierID, capability, intents...)
tier, err := s.channelModelPriceTierForBilling(*item, priceTierID, capability, intents...)
if err != nil {
return nil, err
}
if tier == nil {
return nil, BadAuthRequest("当前模型尚未配置所选规格的用户积分价格")
}
@@ -657,24 +664,42 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
return order, nil
}
func channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierID string, capability string, intents ...ModelRequestIntent) *model.ChannelModelPriceTier {
func (s *Service) channelModelPriceTierForBilling(channelModel model.ChannelModel, priceTierID string, capability string, intents ...ModelRequestIntent) (*model.ChannelModelPriceTier, error) {
intent := ModelRequestIntent{Capability: capability, Options: map[string]any{}}
if len(intents) > 0 {
intent = intents[0]
if normalizeCapability(intent.Capability) == "" {
intent.Capability = capability
}
}
var specs []CapabilitySpec
if normalizeCapability(capability) == "image" && strings.TrimSpace(channelModel.CapabilityConfigJSON) != "" {
spec, err := channelModelCapabilitySpec(channelModel, s.protocolRegistry())
if err != nil {
return nil, err
}
specs = append(specs, spec)
intent = normalizeImageSizeIntent(spec, intent)
}
if priceTierID != "" {
for index := range channelModel.PriceTiers {
tier := &channelModel.PriceTiers[index]
if tier.ID == priceTierID && tier.Enabled && tier.PriceConfigured {
return tier
if len(specs) > 0 && specs[0].ImageParameters != nil {
selector := model.DecodeSKUSelector(tier.SelectorJSON)
if err := validateImageParameterPriceSelector(specs[0].ImageParameters, selector); err != nil {
return nil, err
}
if matched, _ := matchSKUSelector(selector, imagePriceSelectorForParameters(specs[0].ImageParameters, intent)); !matched {
return nil, BadAuthRequest("价格档与实际图片参数不一致")
}
}
return tier, nil
}
}
return nil
return nil, nil
}
if len(intents) > 0 {
intent := intents[0]
if normalizeCapability(intent.Capability) == "" {
intent.Capability = capability
}
return channelModelPriceTierForIntent(channelModel, intent)
}
return channelModelPriceTierForIntent(channelModel, ModelRequestIntent{Capability: capability, Options: map[string]any{}})
return channelModelPriceTierForIntent(channelModel, intent, specs...), nil
}
func estimateTaskTokens(input map[string]any) tokenBillingEstimate {
+532
View File
@@ -0,0 +1,532 @@
package app
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"yingce/backend/internal/model"
"yingce/backend/internal/protocol"
)
func resolveImageCapabilityParameters(image *ImageCapabilityConfig, definitions []protocol.ImageParameter, model string) error {
configured := image.Parameters
if configured == nil {
// Import existing declarations once. A resolution-only plugin may import
// old quality tiers only when every value is explicitly in its contract.
hasQuality := false
for _, p := range definitions {
if p.Name == "quality" && p.AppliesTo(model) {
hasQuality = true
}
}
for _, definition := range definitions {
if !definition.AppliesTo(model) {
continue
}
p := definition
enabled := p.IsEnabled()
var values []string
var initial string
switch p.Name {
case "size":
enabled = image.Size.Parameter != "none"
values, initial = image.Size.Values, image.Size.Default
case "imageResolution":
enabled = image.Resolution.Supported
values, initial = image.Resolution.Values, image.Resolution.Default
if !enabled && !hasQuality && image.Quality.Supported {
valid := len(image.Quality.Values) > 0
for _, value := range image.Quality.Values {
valid = valid && definition.Accepts(value)
}
if valid {
enabled, values, initial = true, image.Quality.Values, image.Quality.Default
}
}
case "quality":
enabled, values, initial = image.Quality.Supported, image.Quality.Values, image.Quality.Default
case "transparentBackground":
enabled, p.Default = image.TransparentBackground.Supported, image.TransparentBackground.Default
case "count":
maximum := float64(image.MaxOutputs)
if p.Max == nil || maximum < *p.Max {
p.Max = &maximum
}
}
if len(values) > 0 {
p.Values = nil
for _, value := range values {
if definition.Accepts(value) {
p.Values = append(p.Values, value)
}
}
if len(p.Values) == 0 {
enabled = false
}
if p.Accepts(initial) {
p.Default = initial
} else if len(p.Values) > 0 {
p.Default = p.Values[0]
}
}
p.Enabled = &enabled
configured = append(configured, p)
}
}
parameters, err := protocol.ResolveImageParameters(definitions, configured, model)
if err != nil {
return BadAuthRequest("图片参数配置无效:" + err.Error())
}
image.Parameters = parameters
return projectImageParameters(image)
}
// Legacy structs are an execution projection, never a second editable source.
func projectImageParameters(image *ImageCapabilityConfig) error {
if err := protocol.ValidateImageParameters(image.Parameters); err != nil {
return BadAuthRequest(err.Error())
}
image.Quality = ImageQualityConfig{Default: "auto", Values: []string{}}
image.Resolution = ImageResolutionConfig{Default: "auto", Values: []string{}}
image.TransparentBackground = VideoBooleanConfig{}
image.ResolutionUsesQuality = false
image.MaxOutputs = 1
sizeEnabled := false
for _, p := range image.Parameters {
if !p.IsEnabled() {
continue
}
values := make([]string, 0, len(p.Values))
for _, value := range p.Values {
values = append(values, fmt.Sprint(value))
}
initial := "auto"
if p.Default != nil {
initial = fmt.Sprint(p.Default)
} else if len(values) > 0 {
initial = values[0]
}
switch p.Name {
case "size":
sizeEnabled = true
image.Size.Parameter = "aspect_ratio"
if p.Encoding == "pixels" {
image.Size.Parameter = "size"
for _, value := range values {
if strings.Contains(value, ":") {
image.Size.Parameter = "aspect_ratio"
break
}
}
}
image.Size.Values, image.Size.Default = values, initial
image.Size.AllowCustom = len(p.Values) == 0
case "imageResolution":
image.Resolution = ImageResolutionConfig{Supported: true, Values: values, Default: initial}
case "quality":
image.Quality = ImageQualityConfig{Supported: true, Values: values, Default: initial}
case "transparentBackground":
image.TransparentBackground = VideoBooleanConfig{Supported: true, Default: p.Default == true}
case "count":
if p.Max != nil {
image.MaxOutputs = int(*p.Max)
}
}
}
if !sizeEnabled {
image.Size = ImageSizeConfig{Parameter: "none", Default: "auto", Values: []string{}}
}
if sizeEnabled {
presets := make([]ImageSizePreset, 0, len(image.Size.Presets))
for _, preset := range image.Size.Presets {
value := preset.Ratio
if image.Size.Parameter == "size" {
value = preset.Size
}
if (image.Size.AllowCustom || containsCapabilityString(image.Size.Values, value)) && (!image.Resolution.Supported || len(image.Resolution.Values) == 0 || containsCapabilityString(image.Resolution.Values, preset.Tier)) {
presets = append(presets, preset)
}
}
image.Size.Presets = presets
}
return nil
}
func publicImageParameters(parameters []protocol.ImageParameter) []protocol.ImageParameter {
result := make([]protocol.ImageParameter, 0, len(parameters))
for _, p := range parameters {
p.Binding, p.Models = "", nil
p.Encoding = ""
result = append(result, p)
}
return result
}
// Disabled resolution keeps its presets for editing; execution uses one explicit
// default group. Multiple groups without a default must not pick by array order.
func singleImageSizeTier(image *ImageCapabilityConfig) (string, bool) {
if image.Size.DefaultTier != "" {
return image.Size.DefaultTier, true
}
for _, field := range image.Parameters {
if field.Name == "imageResolution" && field.Default != nil && field.Default != "auto" {
return fmt.Sprint(field.Default), true
}
}
for _, preset := range image.Size.Presets {
if preset.Size == image.Size.Default {
return preset.Tier, true
}
}
if len(image.Size.Presets) == 0 {
return "", true
}
tier := image.Size.Presets[0].Tier
for _, preset := range image.Size.Presets {
if preset.Tier != tier {
return "", false
}
}
return tier, true
}
func activeImageSizePresets(image *ImageCapabilityConfig) []ImageSizePreset {
if image.Parameters == nil || image.Resolution.Supported {
return image.Size.Presets
}
tier, ok := singleImageSizeTier(image)
if !ok {
return nil
}
result := make([]ImageSizePreset, 0, len(image.Size.Presets))
for _, preset := range image.Size.Presets {
if preset.Tier == tier {
result = append(result, preset)
}
}
return result
}
func imageParameterConstraints(parameters []protocol.ImageParameter) map[string]OptionConstraint {
result := map[string]OptionConstraint{}
for _, p := range parameters {
if !p.IsEnabled() {
continue
}
constraint := OptionConstraint{Values: p.Values, Min: p.Min, Max: p.Max, Step: p.Step}
if len(p.Values) > 0 {
constraint.Min, constraint.Max, constraint.Step = nil, nil, nil
}
if len(p.Values) == 0 && p.Type == "boolean" {
constraint.Values = []any{false, true}
}
if len(p.Values) == 0 && p.Type == "string" {
constraint.Values = []any{"*"}
}
if len(p.Values) == 0 && (p.Type == "number" || p.Type == "integer") && (p.Min == nil || p.Max == nil) {
constraint = OptionConstraint{Values: []any{"*"}}
}
result[p.Name] = constraint
}
return result
}
func imageParameterDefaults(parameters []protocol.ImageParameter) map[string]any {
result := map[string]any{}
for _, p := range parameters {
if p.IsEnabled() && p.Default != nil {
result[p.Name] = p.Default
}
}
return result
}
func imageParameterValue(p protocol.ImageParameter, value any) any {
text, ok := value.(string)
if !ok || p.Type == "string" {
return value
}
switch p.Type {
case "boolean":
if v, err := strconv.ParseBool(text); err == nil {
return v
}
case "number", "integer":
if v, err := strconv.ParseFloat(text, 64); err == nil {
return v
}
}
return value
}
func resolveImageParameterValues(parameters []protocol.ImageParameter, values map[string]any) (map[string]any, error) {
allowed := map[string]protocol.ImageParameter{}
result := imageParameterDefaults(parameters)
for _, p := range parameters {
if p.IsEnabled() {
allowed[p.Name] = p
}
}
for name, value := range values {
p, ok := allowed[name]
if !ok {
return nil, ModelCapabilityNotSupported("当前图片模型未启用参数:" + name)
}
value = imageParameterValue(p, value)
if !p.Accepts(value) {
return nil, ModelCapabilityNotSupported("图片参数超出支持范围:" + p.Label)
}
if value != nil && value != "" {
result[name] = value
}
}
for _, p := range parameters {
if p.IsEnabled() && p.Required && (result[p.Name] == nil || result[p.Name] == "") {
return nil, ModelCapabilityNotSupported("请填写图片参数:" + p.Label)
}
}
return result, nil
}
func validateImageParameterPriceSelector(parameters []protocol.ImageParameter, selector map[string]string) error {
allowed := map[string]protocol.ImageParameter{}
for _, p := range parameters {
if p.IsEnabled() && p.Pricing {
allowed[p.Name] = p
}
}
for name, value := range selector {
if name == "operation" {
if value != "text_to_image" && value != "image_to_image" && value != "" && value != "*" {
return BadAuthRequest("图片价格生成方式无效")
}
continue
}
p, ok := allowed[name]
if !ok {
return BadAuthRequest("当前图片模型未声明此计价参数:" + name)
}
if value == "" || value == "*" {
continue
}
if !p.Accepts(imageParameterValue(p, value)) {
return BadAuthRequest("价格档参数不在支持范围内:" + p.Label)
}
}
return nil
}
func declaredImageParameterValues(config map[string]any, parameters []protocol.ImageParameter) map[string]any {
values := map[string]any{}
for _, p := range parameters {
if !p.IsEnabled() {
continue
}
if value, exists := config[p.Name]; exists && value != nil && strings.TrimSpace(fmt.Sprint(value)) != "" {
values[p.Name] = value
}
}
if extras, ok := config["imageParameters"].(map[string]any); ok {
for name, value := range extras {
values[name] = value
}
}
if encoded, ok := config["imageParameters"].(string); ok && encoded != "" {
var extras map[string]any
if json.Unmarshal([]byte(encoded), &extras) == nil {
for name, value := range extras {
values[name] = value
}
} else {
values["invalidImageParameters"] = encoded
}
}
return values
}
// Admission and worker execution use the same validated values. Core fields are
// only a transport projection; unknown or disabled extension values fail here.
func applyImageParameterValues(config *providerConfig, profile *ImageCapabilityConfig) error {
if profile == nil || profile.Parameters == nil {
return nil
}
values := declaredImageParameterValues(map[string]any{
"size": config.Size, "imageResolution": config.ImageResolution, "quality": config.Quality,
"count": config.Count, "transparentBackground": config.TransparentBackground, "imageParameters": config.ImageParameters,
}, profile.Parameters)
for _, field := range profile.Parameters {
if field.Name == "size" && !field.Accepts(values["size"]) {
size, resolution := fmt.Sprint(values["size"]), config.ImageResolution
if pixels := resolveImageTaskSize(profile, config.InterfaceType, size, resolution); field.Encoding == "pixels" && field.Accepts(pixels) {
values["size"] = pixels
} else if ratio := imageSizeRatioForDeclaredPreset(profile, size, resolution); ratio != "" && field.Accepts(ratio) {
values["size"] = ratio
}
}
}
resolved, err := resolveImageParameterValues(profile.Parameters, values)
if err != nil {
return err
}
config.ImageParameters = resolved
text := func(name string) string {
if value, exists := resolved[name]; exists {
return fmt.Sprint(value)
}
return ""
}
config.Size, config.ImageResolution, config.Quality = text("size"), text("imageResolution"), text("quality")
config.Count, config.TransparentBackground = text("count"), text("transparentBackground")
if imageSizePixelOutbound(profile, config.InterfaceType) {
config.Size = resolveImageTaskSize(profile, config.InterfaceType, config.Size, config.ImageResolution)
if strings.Contains(config.Size, ":") {
return BadAuthRequest("当前比例与分辨率缺少明确的像素尺寸映射")
}
}
return nil
}
func imagePriceSelectorForParameters(parameters []protocol.ImageParameter, intent ModelRequestIntent) map[string]string {
selector := map[string]string{"operation": "text_to_image"}
if intent.Inputs["image"] > 0 {
selector["operation"] = "image_to_image"
}
for _, p := range parameters {
if value, ok := intent.Options[p.Name]; ok && p.IsEnabled() && p.Pricing && value != nil {
selector[p.Name] = fmt.Sprint(value)
}
}
return selector
}
func imagePriceParametersForChannel(channelModel model.ChannelModel, specs ...CapabilitySpec) []protocol.ImageParameter {
if len(specs) > 0 {
return specs[0].ImageParameters
}
config, err := DecodeModelCapabilityConfig(channelModel.CapabilityConfigJSON)
if err == nil && config != nil && config.Image != nil {
return config.Image.Parameters
}
return nil
}
// Read projection follows live route declarations. Explicit omissions in a new
// frontend schema remain omissions; a legacy snapshot imports available fields
// once. The saved route graph and administrator restrictions remain untouched.
func effectiveImageParameterSpec(spec CapabilitySpec, routes []CapabilitySpec) CapabilitySpec {
if spec.Capability != "image" {
return spec
}
sources := map[string]protocol.ImageParameter{}
conflicts := map[string]bool{}
order := []string{}
for _, route := range routes {
for _, p := range route.ImageParameters {
if !p.IsEnabled() {
continue
}
previous, exists := sources[p.Name]
if !exists {
sources[p.Name] = p
order = append(order, p.Name)
continue
}
if previous.Type != p.Type {
conflicts[p.Name] = true
continue
}
previous.Pricing = previous.Pricing && p.Pricing
if len(previous.Values) > 0 && len(p.Values) > 0 {
for _, candidate := range p.Values {
found := false
for _, value := range previous.Values {
found = found || protocol.ImageParameterValuesEqual(candidate, value)
}
if !found {
previous.Values = append(previous.Values, candidate)
}
}
} else if p.Min != nil && p.Max != nil && previous.Min != nil && previous.Max != nil {
minimum, maximum := min(*p.Min, *previous.Min), max(*p.Max, *previous.Max)
candidate := OptionConstraint{Min: &minimum, Max: &maximum, Step: previous.Step}
if optionConstraintCovered(candidate, p.Name, routes) {
previous.Min, previous.Max = &minimum, &maximum
}
}
sources[p.Name] = previous
}
}
hasContract := false
for _, route := range routes {
hasContract = hasContract || route.ImageParameters != nil
}
if !hasContract {
return spec
}
result := spec
result.ImageParameters = []protocol.ImageParameter{}
result.Options = map[string]OptionConstraint{}
for _, name := range order {
if conflicts[name] {
log.Printf("image parameter omitted because route types conflict: %s", name)
continue
}
p := sources[name]
constraint, selected := spec.Options[name]
if !selected {
known := false
for _, previous := range spec.ImageParameters {
known = known || previous.Name == name
}
if known {
disabled := false
p.Enabled = &disabled
result.ImageParameters = append(result.ImageParameters, p)
continue
}
}
if selected {
if len(constraint.Values) > 0 && !isWildcardOptionConstraint(constraint) {
values := []any{}
for _, value := range constraint.Values {
if p.Accepts(imageParameterValue(p, value)) {
values = append(values, imageParameterValue(p, value))
}
}
if len(values) == 0 {
continue
}
p.Values = values
}
if constraint.Min != nil && (p.Min == nil || *constraint.Min > *p.Min) {
p.Min = constraint.Min
}
if constraint.Max != nil && (p.Max == nil || *constraint.Max < *p.Max) {
p.Max = constraint.Max
}
if constraint.Step != nil && (p.Step == nil || *constraint.Step >= *p.Step) {
p.Step = constraint.Step
}
if p.Min != nil && p.Max != nil && *p.Min > *p.Max {
continue
}
}
if p.Default != nil && !p.Accepts(p.Default) {
p.Default = nil
if len(p.Values) > 0 {
p.Default = p.Values[0]
}
}
p.Binding, p.Models, p.Encoding = "", nil, ""
result.ImageParameters = append(result.ImageParameters, p)
}
result.Options = imageParameterConstraints(result.ImageParameters)
result.ImageSize = mergeCapabilityImageSize(routes)
if _, ok := result.Options["size"]; !ok {
result.ImageSize = nil
}
return result
}
@@ -0,0 +1,327 @@
package app
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"time"
"yingce/backend/internal/model"
"yingce/backend/internal/protocol"
)
func imageParameterTestAdapter(t *testing.T, packageID, providerID string) protocol.Adapter {
t.Helper()
data, err := os.ReadFile(filepath.Join("..", "..", "..", "plugin-packages", packageID+".yingce-plugin"))
if err != nil {
t.Fatal(err)
}
pkg, err := protocol.ParsePluginPackage(data)
if err != nil {
t.Fatal(err)
}
adapters, err := protocol.LoadInstalledProviders(pkg.ManifestRaw, nil)
if err != nil {
t.Fatal(err)
}
for _, a := range adapters {
if a.Metadata().ID == providerID {
return a
}
}
t.Fatal("provider missing")
return nil
}
func TestImageParametersResolutionOnlyAndLogicalReconciliation(t *testing.T) {
a := imageParameterTestAdapter(t, "google-gemini-image", "gemini-image")
registry, err := protocol.NewRegistry(a)
if err != nil {
t.Fatal(err)
}
config := DefaultModelCapabilityConfigForModel("gemini-image", "arbitrary-model")
config.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"2k"}, Default: "2k"}
config.Image.Size.Presets = nil
resolved, err := NormalizeModelCapabilityConfigForModel("image", "gemini-image", "arbitrary-model", config, registry)
if err != nil {
t.Fatal(err)
}
if resolved.Image.Quality.Supported || !resolved.Image.Resolution.Supported || resolved.Image.Resolution.Default != "2k" {
t.Fatalf("resolution contract = %#v", resolved.Image)
}
route, err := CapabilitySpecFromModelCapabilityConfig(resolved, "image")
if err != nil {
t.Fatal(err)
}
old := CapabilitySpec{Version: 1, Capability: "image", Options: map[string]OptionConstraint{"quality": {Values: []any{"2k"}}}}
current := capabilitySpecWithRoutePresets(old, []CapabilitySpec{route})
if _, exists := current.Options["quality"]; exists {
t.Fatal("stale quality leaked into public model")
}
if _, exists := current.Options["imageResolution"]; !exists {
t.Fatal("resolution lost")
}
defaults, err := decodeLogicalDefaults(`{"quality":"2k"}`, current)
if err != nil || defaults["imageResolution"] != "2k" || defaults["quality"] != nil {
t.Fatalf("defaults = %#v, err=%v", defaults, err)
}
}
func TestImageParametersAdmissionPricingAndProviderUseSameValues(t *testing.T) {
minimum, maximum := 0.0, 100.0
parameters := []protocol.ImageParameter{
{Name: "imageResolution", Label: "Resolution", Type: "string", Values: []any{"small", "large"}, Default: "small", Pricing: true, Binding: "resolution"},
{Name: "novelAmount", Label: "Novel amount", Type: "number", Min: &minimum, Max: &maximum, Default: 0, Binding: "providerOptions.example.amount"},
{Name: "rawMode", Label: "Raw mode", Type: "boolean", Default: false, Binding: "providerOptions.example.raw"},
}
profile := DefaultModelCapabilityConfigForModel("example", "model")
profile.Image.Parameters = parameters
profile.Image.Size = ImageSizeConfig{Parameter: "none", Default: "auto"}
if err := projectImageParameters(profile.Image); err != nil {
t.Fatal(err)
}
spec, err := CapabilitySpecFromModelCapabilityConfig(profile, "image")
if err != nil {
t.Fatal(err)
}
intent := ModelRequestIntent{Capability: "image", Options: map[string]any{"imageResolution": "large", "novelAmount": float64(0), "rawMode": false}}
if match := MatchCapability(spec, intent); !match.Matched {
t.Fatal(match.Reasons)
}
for _, invalid := range []map[string]any{{"novelAmount": 101}, {"quality": "4k"}, {"rawMode": 0}} {
if _, err := resolveImageParameterValues(parameters, invalid); err == nil {
t.Fatalf("invalid values accepted: %#v", invalid)
}
}
if err := validateImageParameterPriceSelector(parameters, map[string]string{"novelAmount": "1"}); err == nil {
t.Fatal("nonpricing parameter accepted for billing")
}
if err := validateImageParameterPriceSelector(parameters, map[string]string{"imageResolution": "large"}); err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(profile)
cm := model.ChannelModel{Capability: "image", Protocol: "example", CapabilityConfigJSON: string(raw), PriceTiers: []model.ChannelModelPriceTier{newSelectionPriceTier("large", `{"imageResolution":"large"}`, "model", "fixed_request")}}
if tier := channelModelPriceTierForIntent(cm, intent); tier == nil || tier.ID != "large" {
t.Fatal("typed intent failed price matching")
}
request := protocolRequestFromInput(canvasGenerationInput{Mode: "image", Config: providerConfig{Model: "model", InterfaceType: "example", ImageParameters: intent.Options}, Metadata: map[string]any{"providerOptions": map[string]any{"example": map[string]any{"amount": 999}}}})
request, err = protocol.ApplyImageParameters(request, parameters)
if err != nil {
t.Fatal(err)
}
if request.Resolution != "large" || request.ProviderOptions["example"]["amount"] != float64(0) || request.ProviderOptions["example"]["raw"] != false {
t.Fatalf("provider request drifted: %#v", request)
}
}
func TestImageParametersPublicIntentDoesNotOverwriteEncodedPixelSize(t *testing.T) {
adapter := imageParameterTestAdapter(t, "openai-images", "openai-image")
request := protocolRequestFromInput(canvasGenerationInput{Mode: "image", Config: providerConfig{
Model: "arbitrary-model", InterfaceType: "openai-image", Size: "2496x1664", ImageResolution: "2k", Quality: "max",
ImageParameters: map[string]any{"size": "3:2", "imageResolution": "2k", "quality": "max"},
}})
spec, err := adapter.BuildCreate(context.Background(), protocol.RequestContext{Request: request})
if err != nil {
t.Fatal(err)
}
body, ok := spec.Body.(map[string]any)
if !ok {
encoded, _ := json.Marshal(spec.Body)
_ = json.Unmarshal(encoded, &body)
}
if body["size"] != "2496x1664" || body["quality"] != "max" || body["resolution"] != "2k" {
t.Fatalf("encoded request = %#v", body)
}
}
func TestImageParametersLegacyChannelUsesLiveContractForRouteAndBilling(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("gemini-image", "opaque-model")
profile.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"2k"}, Default: "2k"}
profile.Image.Resolution = ImageResolutionConfig{}
svc, db, _, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceGeminiImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("resolution", `{"imageResolution":"2k"}`, "opaque-model", "fixed_request"),
})
if err := db.AutoMigrate(&model.SystemSetting{}); err != nil {
t.Fatal(err)
}
stored, err := svc.repo.ChannelModel(channelModel.ID)
if err != nil {
t.Fatal(err)
}
spec, err := channelModelCapabilitySpec(*stored, svc.protocolRegistry())
if err != nil {
t.Fatal(err)
}
if imagePriceParametersForChannel(*stored) != nil {
t.Fatal("fixture must retain legacy persisted config")
}
svc.routeCatalogTTL = time.Hour
svc.routeCatalog = &routeCatalogSnapshot{LoadedAt: time.Now(), Models: map[string]cachedLogicalModel{
"logical": {Model: model.LogicalModel{ID: "logical", Capability: "image", PricePolicy: "channel"}, ProductSpec: spec, Defaults: imageParameterDefaults(spec.ImageParameters), Routes: []cachedLogicalRoute{
{Route: model.LogicalModelRoute{ID: "route", Enabled: true, Weight: 1}, CapabilitySpec: spec, ChannelModel: *stored},
}},
}}
routed, err := svc.ResolveLogicalModel("logical", ModelRequestIntent{Capability: "image", Options: map[string]any{"imageResolution": "2k"}})
if err != nil {
t.Fatal(err)
}
input := applyRoutedProviderSelection(map[string]any{"mode": "image", "config": map[string]any{"quality": "stale", "transparentBackground": "true"}}, routed)
if err := svc.ValidateTaskCapability(input); err != nil {
t.Fatal(err)
}
config := input["config"].(map[string]any)
parameters := config["imageParameters"].(map[string]any)
if parameters["imageResolution"] != "2k" || parameters["quality"] != nil || config["quality"] != "" {
t.Fatalf("execution projection = %#v", config)
}
tier, err := svc.channelModelPriceTierForBilling(*stored, "resolution", "image", routed.Intent)
if err != nil || tier == nil || tier.ID != routed.PriceTier.ID {
t.Fatalf("billing projection = %#v, %v", tier, err)
}
quote, err := svc.QuoteLogicalModel("logical", ModelRequestIntent{Capability: "image", Options: map[string]any{"imageResolution": "2k"}})
if err != nil || quote == nil || quote.AmountMicrocredits != tier.UnitPriceMicrocredits {
t.Fatalf("quote drift: %#v, %v", quote, err)
}
if _, err := svc.channelModelPriceTierForBilling(*stored, "resolution", "image", ModelRequestIntent{Capability: "image", Options: map[string]any{"imageResolution": "4k"}}); err == nil {
t.Fatal("mismatched billing parameters accepted")
}
}
func TestImageParametersCustomChannelRejectsForgedOrOutOfRangeValues(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("gemini-image", "opaque-model")
enabled, minimum, maximum := true, 0.0, 2.0
profile.Image.Parameters = []protocol.ImageParameter{{Name: "temperature", Enabled: &enabled, Min: &minimum, Max: &maximum}}
svc := &Service{}
for _, values := range []map[string]any{{"temperature": 3}, {"providerSecret": "value"}, {"temperature": []any{1}}} {
input := map[string]any{"mode": "image", "config": map[string]any{"interfaceType": "gemini-image", "model": "opaque-model", "capabilityConfig": profile, "imageParameters": values}}
if err := svc.ValidateTaskCapability(input); err == nil {
t.Fatalf("invalid values accepted: %#v", values)
}
}
}
func TestImageParametersDeclaredResolutionNamesAndPixelsAreNotFixedTiers(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("opaque-provider", "opaque-model")
profile.Image.Parameters = []protocol.ImageParameter{
{Name: "size", Label: "Frame", Type: "string", Values: []any{"2:1"}, Default: "2:1", Binding: "aspectRatio", Encoding: "pixels"},
{Name: "imageResolution", Label: "Resolution", Type: "string", Values: []any{"panorama"}, Default: "panorama", Binding: "resolution"},
}
profile.Image.Size.Presets = []ImageSizePreset{{Tier: "panorama", Ratio: "2:1", Width: 8192, Height: 4096, Size: "8192x4096"}}
if err := projectImageParameters(profile.Image); err != nil {
t.Fatal(err)
}
if err := validateImageCapabilityConfig(profile.Image); err != nil {
t.Fatal(err)
}
config := providerConfig{InterfaceType: "opaque-provider", ImageParameters: map[string]any{"size": "2:1", "imageResolution": "panorama"}}
if err := applyImageParameterValues(&config, profile.Image); err != nil {
t.Fatal(err)
}
if config.Size != "8192x4096" || config.ImageParameters["size"] != "2:1" {
t.Fatalf("pixel mapping = %#v", config)
}
}
func TestImageParametersSaveDifferentRatiosPerResolution(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("opaque-provider", "opaque-model")
profile.Image.Parameters = []protocol.ImageParameter{
{Name: "size", Label: "Frame", Type: "string", Values: []any{"1:1", "16:9"}, Default: "1:1", Binding: "aspectRatio", Encoding: "pixels"},
{Name: "imageResolution", Label: "Resolution", Type: "string", Values: []any{"1k", "2k"}, Default: "1k", Binding: "resolution"},
}
profile.Image.Size.Presets = []ImageSizePreset{
{Tier: "1k", Ratio: "1:1", Width: 1024, Height: 1024, Size: "1024x1024"},
{Tier: "2k", Ratio: "16:9", Width: 2560, Height: 1440, Size: "2560x1440"},
}
if err := projectImageParameters(profile.Image); err != nil {
t.Fatal(err)
}
if err := validateImageSizePresetRequirement("image", "opaque-provider", profile); err != nil {
t.Fatal(err)
}
if err := validateImagePresetSelection(profile.Image, "2k", "1:1"); err == nil {
t.Fatal("unsupported combination accepted")
}
if got := resolveImageTaskSize(profile.Image, "opaque-provider", "16:9", "2k"); got != "2560x1440" {
t.Fatal(got)
}
profile.Image.Size.Presets = profile.Image.Size.Presets[:1]
if err := validateImageSizePresetRequirement("image", "opaque-provider", profile); err == nil {
t.Fatal("unmapped ratio accepted")
}
}
func TestImageParametersPixelSelectionKeepsExactSizeWithoutResolution(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("opaque-provider", "opaque-model")
profile.Image.Parameters = []protocol.ImageParameter{{Name: "size", Label: "Size", Type: "string", Values: []any{"1024x1024", "2048x2048"}, Default: "1024x1024", Binding: "aspectRatio", Encoding: "pixels"}}
profile.Image.Size.Presets = []ImageSizePreset{{Tier: "1k", Ratio: "1:1", Width: 1024, Height: 1024, Size: "1024x1024"}, {Tier: "2k", Ratio: "1:1", Width: 2048, Height: 2048, Size: "2048x2048"}}
if err := projectImageParameters(profile.Image); err != nil {
t.Fatal(err)
}
config := providerConfig{InterfaceType: "opaque-provider", Size: "2048x2048", ImageParameters: map[string]any{"size": "2048x2048"}}
if err := applyImageParameterValues(&config, profile.Image); err != nil {
t.Fatal(err)
}
if config.Size != "2048x2048" || config.ImageResolution != "" || config.Quality != "" {
t.Fatalf("unexpected encoding: %#v", config)
}
}
func TestImageParametersDisabledResolutionUsesDefaultAndPreservesGroups(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("opaque-provider", "opaque-model")
disabled := false
profile.Image.Parameters = []protocol.ImageParameter{
{Name: "size", Label: "Frame", Type: "string", Values: []any{"1:1"}, Default: "1:1", Binding: "aspectRatio", Encoding: "pixels"},
{Name: "imageResolution", Label: "Resolution", Type: "string", Values: []any{"1k", "2k"}, Default: "2k", Binding: "resolution", Enabled: &disabled},
}
profile.Image.Size.DefaultTier = "2k"
profile.Image.Size.Presets = []ImageSizePreset{{Tier: "1k", Ratio: "1:1", Width: 1024, Height: 1024, Size: "1024x1024"}, {Tier: "2k", Ratio: "1:1", Width: 2048, Height: 2048, Size: "2048x2048"}}
encoded, err := json.Marshal(profile)
if err != nil {
t.Fatal(err)
}
var reopened ModelCapabilityConfig
if err := json.Unmarshal(encoded, &reopened); err != nil {
t.Fatal(err)
}
if err := projectImageParameters(reopened.Image); err != nil {
t.Fatal(err)
}
if err := validateImageSizePresetRequirement("image", "opaque-provider", &reopened); err != nil {
t.Fatal(err)
}
config := providerConfig{InterfaceType: "opaque-provider", Size: "1:1"}
if err := applyImageParameterValues(&config, reopened.Image); err != nil {
t.Fatal(err)
}
if config.Size != "2048x2048" || config.ImageResolution != "" {
t.Fatalf("disabled resolution changed output: %#v", config)
}
if len(reopened.Image.Size.Presets) != 2 || len(activeImageSizePresets(reopened.Image)) != 1 {
t.Fatal("stored and active presets not separated")
}
reopened.Image.Parameters[1].Enabled = nil
if err := projectImageParameters(reopened.Image); err != nil {
t.Fatal(err)
}
if len(activeImageSizePresets(reopened.Image)) != 2 {
t.Fatal("enabling lost presets")
}
}
func TestImageParametersDisabledResolutionRejectsAmbiguousPixels(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel("opaque-provider", "opaque-model")
profile.Image.Parameters = []protocol.ImageParameter{{Name: "size", Label: "Frame", Type: "string", Values: []any{"1:1"}, Default: "1:1", Binding: "aspectRatio", Encoding: "pixels"}}
profile.Image.Size.Presets = []ImageSizePreset{{Tier: "1k", Ratio: "1:1", Width: 1024, Height: 1024, Size: "1024x1024"}, {Tier: "2k", Ratio: "1:1", Width: 2048, Height: 2048, Size: "2048x2048"}}
if err := projectImageParameters(profile.Image); err != nil {
t.Fatal(err)
}
if err := validateImageSizePresetRequirement("image", "opaque-provider", profile); err == nil {
t.Fatal("ambiguous pixels accepted")
}
config := providerConfig{InterfaceType: "opaque-provider", Size: "1:1"}
if err := applyImageParameterValues(&config, profile.Image); err == nil {
t.Fatal("runtime selected first preset")
}
}
+231 -4
View File
@@ -4,6 +4,8 @@ import (
"encoding/json"
"strings"
"testing"
"yingce/backend/internal/model"
)
func TestImageSizePresetsValidationAndRoundTrip(t *testing.T) {
@@ -54,9 +56,50 @@ func TestImageSizePresetsValidationAndRoundTrip(t *testing.T) {
}
}
func TestImageQualityDoesNotSelectResolutionPresets(t *testing.T) {
profile := DefaultImageCapabilityConfig("openai-image", "test")
profile.Size = ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"1:1"}, Default: "1:1", Presets: []ImageSizePreset{
{Tier: "1k", Ratio: "1:1", Size: "1024x1024", Width: 1024, Height: 1024},
}}
profile.Resolution = ImageResolutionConfig{Supported: false, Default: "auto"}
profile.Quality = ImageQualityConfig{Supported: true, Values: []string{"medium", "high", "max"}, Default: "medium"}
if err := validateImageCapabilityConfig(profile); err != nil {
t.Fatalf("quality-only capability rejected: %v", err)
}
for _, quality := range profile.Quality.Values {
input := canvasGenerationInput{Mode: "image", Prompt: "local test", Config: providerConfig{InterfaceType: "openai-image", Model: "test", Size: "1:1", Quality: quality, Count: "1"}}
raw := map[string]any{"config": map[string]any{"size": "1:1", "quality": quality}}
if err := validateImageTaskWithResolvedSize(raw, &input, profile); err != nil {
t.Fatalf("quality %q rejected: %v", quality, err)
}
if input.Config.Size != "1024x1024" || input.Config.Quality != quality {
t.Fatalf("quality changed preset or value: %+v", input.Config)
}
}
profile.Resolution.Supported = true
if err := validateImagePresetSelection(profile, "2k", "1:1"); err == nil {
t.Fatal("independent resolution must still reject an undeclared combination")
}
}
func TestResolveImageTaskSizeUsesRouteEncodingForDeclaredAlias(t *testing.T) {
profile := &ImageCapabilityConfig{
Size: ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"16:9"}, Default: "16:9", Presets: []ImageSizePreset{
{Tier: "1k", Ratio: "16:9", Size: "1824x1024"},
}},
Quality: ImageQualityConfig{Supported: true, Values: []string{"1k"}, Default: "1k"},
}
if got := resolveImageTaskSize(profile, string(model.ChannelInterfaceGrokImage), "1824x1024", "1k"); got != "16:9" {
t.Fatalf("aspect-ratio route got %q, want canonical ratio 16:9", got)
}
if got := resolveImageTaskSize(profile, string(model.ChannelInterfaceOpenAIImage), "32:18", "1k"); got != "1824x1024" {
t.Fatalf("pixel route got %q, want declared pixel size 1824x1024", got)
}
}
func TestImageSizePresetsEnforceResolutionRatioPair(t *testing.T) {
profile := DefaultImageCapabilityConfig("grok-image", "grok-imagine-image")
profile.Quality.Default = "1k"
profile.Resolution.Default = "1k"
profile.Size = ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"1:1", "16:9"}, Default: "1:1", Presets: []ImageSizePreset{
{Tier: "1k", Ratio: "1:1", Size: "1024x1024", Width: 1024, Height: 1024},
{Tier: "2k", Ratio: "16:9", Size: "2752x1536", Width: 2752, Height: 1536},
@@ -64,12 +107,12 @@ func TestImageSizePresetsEnforceResolutionRatioPair(t *testing.T) {
if err := validateImageCapabilityConfig(profile); err != nil {
t.Fatal(err)
}
profile.Quality.Default = "2k"
profile.Resolution.Default = "2k"
if err := validateImageCapabilityConfig(profile); err == nil || !strings.Contains(err.Error(), "默认图片分辨率") {
t.Fatalf("expected invalid default pair error, got %v", err)
}
profile.Quality.Default = "1k"
input := canvasGenerationInput{Config: providerConfig{Size: "1:1", Quality: "2k"}}
profile.Resolution.Default = "1k"
input := canvasGenerationInput{Config: providerConfig{Size: "1:1", ImageResolution: "2k"}}
if err := validateImageTask(profile, input); err == nil || !strings.Contains(err.Error(), "当前分辨率") {
t.Fatalf("expected pair validation error, got %v", err)
}
@@ -83,3 +126,187 @@ func TestImageSizePresetsEnforceResolutionRatioPair(t *testing.T) {
t.Fatal(err)
}
}
func pixelSizeTestProfile() *ImageCapabilityConfig {
profile := DefaultImageCapabilityConfig("openai-image", "gpt-image-2.5-4k")
profile.Size = ImageSizeConfig{Parameter: "size", Values: []string{"2048x2048", "2752x1536", "2880x2880", "3840x2160"}, Default: "2752x1536", Presets: []ImageSizePreset{
{Tier: "2k", Ratio: "1:1", Size: "2048x2048", Width: 2048, Height: 2048},
{Tier: "2k", Ratio: "16:9", Size: "2752x1536", Width: 2752, Height: 1536},
{Tier: "4k", Ratio: "1:1", Size: "2880x2880", Width: 2880, Height: 2880},
{Tier: "4k", Ratio: "16:9", Size: "3840x2160", Width: 3840, Height: 2160},
}}
profile.Quality = ImageQualityConfig{Supported: true, Values: []string{"2k", "4k"}, Default: "2k"}
return profile
}
func TestResolveImageTaskSizeUsesTierRatioPreset(t *testing.T) {
profile := pixelSizeTestProfile()
for _, tc := range []struct {
name, size, quality, want string
}{
{"2k ratio preset", "16:9", "2k", "2752x1536"},
{"4k ratio preset", "1:1", "4k", "2880x2880"},
{"quality alias", "16:9", "medium", "2752x1536"},
{"fallback to default tier", "1:1", "", "2048x2048"},
{"pixel passthrough", "2048x2048", "2k", "2048x2048"},
{"auto passthrough", "auto", "2k", "auto"},
{"undeclared ratio stays for validation", "3:2", "2k", "3:2"},
} {
t.Run(tc.name, func(t *testing.T) {
if got := resolveImageTaskSize(profile, "openai-image", tc.size, tc.quality); got != tc.want {
t.Fatalf("resolveImageTaskSize(%q, %q) = %q; want %q", tc.size, tc.quality, got, tc.want)
}
})
}
aspectProfile := DefaultImageCapabilityConfig("grok-image", "grok-imagine-image")
aspectProfile.Size = ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"1:1", "16:9"}, Default: "1:1"}
if got := resolveImageTaskSize(aspectProfile, "grok-image", "16:9", "2k"); got != "16:9" {
t.Fatalf("aspect_ratio profile size changed: %q", got)
}
if got := resolveImageTaskSize(nil, "openai-image", "16:9", "2k"); got != "16:9" {
t.Fatalf("nil profile size changed: %q", got)
}
}
func TestValidateTaskCapabilityRewritesRatioSizeToPixelPreset(t *testing.T) {
config := DefaultModelCapabilityConfigForModel("openai-image", "gpt-image-2.5-4k")
config.Image = pixelSizeTestProfile()
config.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"2k", "4k"}, Default: "2k"}
config.Image.Quality = ImageQualityConfig{Supported: false}
for _, tc := range []struct {
name, size, resolution, wantSize string
}{
{"2k preset", "16:9", "2k", "2752x1536"},
{"4k preset", "1:1", "4k", "2880x2880"},
} {
t.Run(tc.name, func(t *testing.T) {
input := map[string]any{
"mode": "image", "prompt": "A simple gray circle on a white background.",
"config": map[string]any{"interfaceType": "openai-image", "model": "gpt-image-2.5-4k", "size": tc.size, "imageResolution": tc.resolution, "count": "1", "capabilityConfig": config},
}
data, err := json.Marshal(input)
if err != nil {
t.Fatal(err)
}
var normalized map[string]any
if err := json.Unmarshal(data, &normalized); err != nil {
t.Fatal(err)
}
if err := (&Service{}).ValidateTaskCapability(normalized); err != nil {
t.Fatalf("ValidateTaskCapability() error = %v", err)
}
rewritten := normalized["config"].(map[string]any)["size"]
if rewritten != tc.wantSize {
t.Fatalf("config.size = %v; want %q", rewritten, tc.wantSize)
}
})
}
t.Run("undeclared ratio fails validation locally", func(t *testing.T) {
input := map[string]any{
"mode": "image", "prompt": "A simple gray circle on a white background.",
"config": map[string]any{"interfaceType": "openai-image", "model": "gpt-image-2.5-4k", "size": "3:2", "imageResolution": "2k", "count": "1", "capabilityConfig": config},
}
data, err := json.Marshal(input)
if err != nil {
t.Fatal(err)
}
var normalized map[string]any
if err := json.Unmarshal(data, &normalized); err != nil {
t.Fatal(err)
}
err = (&Service{}).ValidateTaskCapability(normalized)
if err == nil || !strings.Contains(err.Error(), "支持范围") {
t.Fatalf("expected local size validation error, got %v", err)
}
})
}
func TestValidateTaskCapabilityRewritesOpenAIAspectPresetToPixelSize(t *testing.T) {
config := DefaultModelCapabilityConfigForModel("openai-image", "gpt-image-2.5-4k")
config.Image.Size = ImageSizeConfig{
Parameter: "aspect_ratio",
Values: []string{"9:16"},
Default: "9:16",
Presets: []ImageSizePreset{
{Tier: "2k", Ratio: "9:16", Size: "1536x2752", Width: 1536, Height: 2752},
{Tier: "4k", Ratio: "9:16", Size: "2160x3840", Width: 2160, Height: 3840},
},
}
config.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"2k", "4k"}, Default: "2k"}
config.Image.Quality = ImageQualityConfig{Supported: false}
input := map[string]any{
"mode": "image",
"prompt": "A simple gray circle on a white background.",
"config": map[string]any{
"interfaceType": "openai-image",
"model": "gpt-image-2.5-4k",
"size": "9:16",
"imageResolution": "2k",
"count": "1",
"capabilityConfig": config,
},
}
data, err := json.Marshal(input)
if err != nil {
t.Fatal(err)
}
var normalized map[string]any
if err := json.Unmarshal(data, &normalized); err != nil {
t.Fatal(err)
}
if err := (&Service{}).ValidateTaskCapability(normalized); err != nil {
t.Fatalf("ValidateTaskCapability() error = %v", err)
}
if got := normalized["config"].(map[string]any)["size"]; got != "1536x2752" {
t.Fatalf("config.size = %v; want 1536x2752", got)
}
}
// 比例型线路在任务输入边界把画布比例换算成 preset 像素值后,执行前的 provider 预检会用
// 同一份能力画像再校验一次;换算结果必须继续被认成合法尺寸,否则任务会在发请求前被本地
// 拒绝(线上表现为「图片尺寸不在当前模型支持范围内」,出站记录为 provider-preflight)。
func TestValidateImageTaskAcceptsResolvedPresetPixelSize(t *testing.T) {
profile := DefaultImageCapabilityConfig("openai-image", "gpt-image-2.5")
profile.Size = ImageSizeConfig{
Parameter: "aspect_ratio",
Values: []string{"1:1", "4:3"},
Default: "1:1",
Presets: []ImageSizePreset{
{Tier: "1k", Ratio: "1:1", Size: "1024x1024", Width: 1024, Height: 1024},
{Tier: "1k", Ratio: "4:3", Size: "1360x1024", Width: 1360, Height: 1024},
{Tier: "2k", Ratio: "4:3", Size: "2304x1728", Width: 2304, Height: 1728},
},
}
profile.Quality = ImageQualityConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "1k"}
raw := map[string]any{"config": map[string]any{"size": "4:3", "quality": "1k"}}
taskInput := canvasGenerationInput{Mode: "image", Prompt: "a simple circle", Config: providerConfig{InterfaceType: "openai-image", Model: "gpt-image-2.5", Size: "4:3", Quality: "1k", Count: "1"}}
if err := validateImageTaskWithResolvedSize(raw, &taskInput, profile); err != nil {
t.Fatalf("resolve step error = %v", err)
}
if taskInput.Config.Size != "1360x1024" {
t.Fatalf("resolved size = %q; want 1360x1024", taskInput.Config.Size)
}
if got := raw["config"].(map[string]any)["size"]; got != "1360x1024" {
t.Fatalf("persisted config.size = %v; want 1360x1024", got)
}
// 执行前预检用同一份画像再校验已换算的像素值,必须通过。
if err := validateImageTask(profile, taskInput); err != nil {
t.Fatalf("provider preflight rejected the resolved pixel size: %v", err)
}
// 未声明的像素值仍然拒绝。
undeclared := taskInput
undeclared.Config.Size = "2000x2000"
if err := validateImageTask(profile, undeclared); err == nil || !strings.Contains(err.Error(), "图片尺寸") {
t.Fatalf("undeclared pixel size should stay rejected, got %v", err)
}
// 其他档位的 preset 像素值不能借低档质量通过。
wrongTier := taskInput
wrongTier.Config.Size = "2304x1728"
if err := validateImageTask(profile, wrongTier); err == nil || !strings.Contains(err.Error(), "图片尺寸") {
t.Fatalf("other-tier pixel size should stay rejected, got %v", err)
}
}
+1 -1
View File
@@ -101,7 +101,7 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
if routed.PriceTier != nil {
priceTierID = routed.PriceTier.ID
}
order, billingErr := s.newBillingOrderWithPriceTier("", "", "quote", routed.ChannelModel.ChannelID, routed.ChannelModel.ModelKey, capability, "model_quote", quantity, tokenEstimate, priceTierID)
order, billingErr := s.newBillingOrderWithPriceTier("", "", "quote", routed.ChannelModel.ChannelID, routed.ChannelModel.ModelKey, capability, "model_quote", quantity, tokenEstimate, priceTierID, resolvedIntent)
if billingErr != nil {
return nil, billingErr
}
+44 -12
View File
@@ -10,6 +10,7 @@ import (
"gorm.io/gorm"
"yingce/backend/internal/model"
"yingce/backend/internal/protocol"
"yingce/backend/internal/repository"
)
@@ -182,17 +183,21 @@ func (s *Service) buildAdminLogicalModel(item model.LogicalModel, graph *reposit
channelModelByID[channelModel.ID] = channelModel
}
admin := AdminLogicalModel{PublicLogicalModel: publicLogicalModel(cachedLogicalModel{Model: item, ProductSpec: productSpec, Defaults: map[string]any{}}, false), Enabled: item.Enabled, ActiveRevisionID: graph.Revision.ID, RevisionVersion: graph.Revision.Version, Routes: []AdminLogicalRoute{}}
projectionRoutes := make([]cachedLogicalRoute, 0, len(graph.Routes))
for _, route := range graph.Routes {
channelModel, channelOK := channelModelByID[route.ChannelModelID]
if !channelOK {
return nil, errors.New("供应线路引用的渠道模型不存在")
}
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel)
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel, s.protocolRegistry())
if specErr != nil {
return nil, specErr
}
_, channelOK = systemChannelByID[channelModel.ChannelID]
structurallyAvailable := route.Enabled && route.Weight > 0 && channelModel.Enabled && channelOK
if structurallyAvailable {
projectionRoutes = append(projectionRoutes, cachedLogicalRoute{Route: route, CapabilitySpec: capabilitySpec, ChannelModel: channelModel})
}
billingAvailable := item.PricePolicy != "unified" || item.BillingMode != "token" || supportsTokenBilling(item.Capability, channelModel.Protocol)
available := structurallyAvailable && billingAvailable && (item.PricePolicy != "channel" || channelModel.PriceConfigured)
admin.Routes = append(admin.Routes, AdminLogicalRoute{ID: route.ID, ChannelModelID: channelModel.ID, ChannelID: channelModel.ChannelID, ChannelModelKey: channelModel.ModelKey, ChannelModelName: channelModel.DisplayName, Enabled: route.Enabled, Priority: route.Priority, Weight: route.Weight, Available: available, structurallyAvailable: structurallyAvailable, CapabilitySpec: capabilitySpec})
@@ -206,9 +211,8 @@ func (s *Service) buildAdminLogicalModel(item model.LogicalModel, graph *reposit
if err != nil {
return nil, err
}
admin.PublicLogicalModel = publicLogicalModel(cachedLogicalModel{Model: item, ProductSpec: productSpec, Defaults: defaults}, false)
// publicLogicalModel above has no route list; admin routes are already attached
// and the enriched product spec is the source used by the editor.
admin.PublicLogicalModel = publicLogicalModel(cachedLogicalModel{Model: item, ProductSpec: productSpec, Defaults: defaults, Routes: projectionRoutes}, false)
// Admin and creator share the sanitized price projection of active routes.
admin.CapabilitySpec = productSpec
admin.DefaultOptions = defaults
structuralRouteSpecs := structuralAdminRouteSpecs(admin.Routes)
@@ -381,11 +385,11 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
return nil, nil, nil, false, BadAuthRequest("前台模型只能同步系统渠道模型")
}
capability = normalizeCapability(source.Capability)
derivedSpec, specErr := channelModelCapabilitySpec(*source)
derivedSpec, specErr := channelModelCapabilitySpec(*source, s.protocolRegistry())
if specErr != nil {
return nil, nil, nil, false, specErr
}
derivedDefaults, defaultsErr := channelModelDefaultOptions(*source, derivedSpec)
derivedDefaults, defaultsErr := channelModelDefaultOptions(*source, derivedSpec, s.protocolRegistry())
if defaultsErr != nil {
return nil, nil, nil, false, defaultsErr
}
@@ -496,7 +500,7 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
if modelErr != nil {
return nil, nil, nil, false, BadAuthRequest("供应线路引用的渠道模型不存在")
}
capabilitySpec, specErr := channelModelCapabilitySpec(*channelModel)
capabilitySpec, specErr := channelModelCapabilitySpec(*channelModel, s.protocolRegistry())
if specErr != nil {
return nil, nil, nil, false, specErr
}
@@ -532,6 +536,22 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
return nil, nil, nil, false, BadAuthRequest("Token 计费仅支持文本和视频前台模型")
}
}
if capability == "image" && len(structuralRouteSpecs) > 0 {
// Rebuild labels, types and pricing eligibility from current routes. The
// frontend may restrict values, but cannot invent provider capabilities.
reconciled := effectiveImageParameterSpec(req.CapabilitySpec, structuralRouteSpecs)
if reconciled.ImageParameters != nil {
if err := validateProductSpecWithinRoutes(req.CapabilitySpec, structuralRouteSpecs); err != nil {
return nil, nil, nil, false, err
}
req.CapabilitySpec = reconciled
encodedSpec, encodeErr := json.Marshal(reconciled)
if encodeErr != nil {
return nil, nil, nil, false, encodeErr
}
revision.CapabilitySpecJSON = string(encodedSpec)
}
}
// 停用必须始终可执行,便于管理员立即阻止失效线路继续对外服务;重新启用时再强校验结构能力和计费可用性。
if req.Enabled {
if len(structuralRouteSpecs) == 0 {
@@ -563,9 +583,18 @@ func supportsLogicalModelTokenBilling(capability string, enabledRouteProtocols [
}
func normalizeLogicalDefaults(spec CapabilitySpec, defaults map[string]any) (map[string]any, error) {
if spec.Capability == "image" && spec.ImageParameters != nil {
parameters := append([]protocol.ImageParameter(nil), spec.ImageParameters...)
for index := range parameters {
parameters[index].Required = false
}
if _, err := resolveImageParameterValues(parameters, defaults); err != nil {
return nil, err
}
}
result := make(map[string]any, len(defaults))
for rawName, value := range defaults {
name := canonicalCapabilityOptionName(rawName)
name := canonicalModelOptionName(spec.Capability, rawName)
if _, exists := result[name]; exists {
return nil, BadAuthRequest("默认参数存在重复别名:" + name)
}
@@ -594,13 +623,13 @@ func defaultMap(value map[string]any) map[string]any {
return value
}
func channelModelCapabilitySpec(channelModel model.ChannelModel) (CapabilitySpec, error) {
func channelModelCapabilitySpec(channelModel model.ChannelModel, registries ...*protocol.Registry) (CapabilitySpec, error) {
config, err := DecodeModelCapabilityConfig(channelModel.CapabilityConfigJSON)
if err != nil {
return CapabilitySpec{}, BadAuthRequest("渠道模型能力配置无效,请先修复渠道模型")
}
if config != nil {
config, err = NormalizeModelCapabilityConfigForModel(normalizeCapability(channelModel.Capability), string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config)
config, err = NormalizeModelCapabilityConfigForModel(normalizeCapability(channelModel.Capability), string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config, registries...)
if err != nil {
return CapabilitySpec{}, err
}
@@ -673,18 +702,21 @@ func capabilitySpecWithPriceTiers(spec CapabilitySpec, channelModel model.Channe
return result
}
func channelModelDefaultOptions(channelModel model.ChannelModel, spec CapabilitySpec) (map[string]any, error) {
func channelModelDefaultOptions(channelModel model.ChannelModel, spec CapabilitySpec, registries ...*protocol.Registry) (map[string]any, error) {
config, err := DecodeModelCapabilityConfig(channelModel.CapabilityConfigJSON)
if err != nil {
return nil, BadAuthRequest("渠道模型能力配置无效,请先修复渠道模型")
}
if config != nil {
config, err = NormalizeModelCapabilityConfigForModel(normalizeCapability(channelModel.Capability), string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config)
config, err = NormalizeModelCapabilityConfigForModel(normalizeCapability(channelModel.Capability), string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config, registries...)
if err != nil {
return nil, err
}
}
defaults := make(map[string]any)
if spec.Capability == "image" && spec.ImageParameters != nil {
return normalizeLogicalDefaults(spec, imageParameterDefaults(spec.ImageParameters))
}
if config != nil {
switch normalizeCapability(channelModel.Capability) {
case "image":
+15 -1
View File
@@ -32,7 +32,8 @@ func (s *Service) PublicLogicalModels(intent *ModelRequestIntent) ([]PublicLogic
available = false
if coverageValid {
for _, route := range cached.Routes {
if route.Route.Enabled && route.Route.Weight > 0 && !s.logicalRouteBlocked(route) && MatchCapability(route.CapabilitySpec, resolvedIntent).Matched && (cached.Model.PricePolicy != "channel" || channelModelPriceTierForIntent(route.ChannelModel, resolvedIntent) != nil) {
priceCompatible := cached.Model.PricePolicy != "channel" || channelModelHasCompatiblePriceTier(route.ChannelModel, resolvedIntent, route.CapabilitySpec)
if route.Route.Enabled && route.Route.Weight > 0 && !s.logicalRouteBlocked(route) && MatchCapability(route.CapabilitySpec, resolvedIntent).Matched && priceCompatible {
available = true
break
}
@@ -93,6 +94,12 @@ func publicLogicalModelPriceTiers(cached cachedLogicalModel) []PublicLogicalMode
continue
}
selector := skuSelectorForTier(tier)
if parameters := route.CapabilitySpec.ImageParameters; parameters != nil {
selector = model.DecodeSKUSelector(tier.SelectorJSON)
if validateImageParameterPriceSelector(parameters, selector) != nil {
continue
}
}
_, selectorKey, selectorErr := model.CanonicalSKUSelector(selector)
if selectorErr != nil {
continue
@@ -147,6 +154,13 @@ func enabledLogicalRouteSpecs(routes []cachedLogicalRoute) []CapabilitySpec {
// Callers must pass only currently enabled routes; disabled or zero-weight
// routes would otherwise advertise size tiers the public catalog cannot route.
func capabilitySpecWithRoutePresets(spec CapabilitySpec, routes []CapabilitySpec) CapabilitySpec {
if spec.Capability == "image" {
for _, route := range routes {
if route.ImageParameters != nil {
return effectiveImageParameterSpec(spec, routes)
}
}
}
result := spec
result.Options = make(map[string]OptionConstraint, len(spec.Options))
for name, constraint := range spec.Options {
+122 -11
View File
@@ -7,6 +7,7 @@ import (
"strings"
"yingce/backend/internal/model"
protocolcontract "yingce/backend/internal/protocol"
)
// ModelCapabilityConfig 是模型能力声明,不包含供应商字段名;协议适配器负责把统一参数映射到上游请求。
@@ -38,13 +39,18 @@ type TextReferenceConfig struct {
}
type ImageCapabilityConfig struct {
References ImageReferenceConfig `json:"references"`
Size ImageSizeConfig `json:"size"`
Quality ImageQualityConfig `json:"quality"`
TransparentBackground VideoBooleanConfig `json:"transparentBackground"`
ResponseFormat ParameterSupport `json:"responseFormat"`
OutputFormat ParameterSupport `json:"outputFormat"`
MaxOutputs int `json:"maxOutputs"`
Parameters []protocolcontract.ImageParameter `json:"parameters"`
References ImageReferenceConfig `json:"references"`
Size ImageSizeConfig `json:"size"`
Resolution ImageResolutionConfig `json:"resolution"`
Quality ImageQualityConfig `json:"quality"`
// ResolutionUsesQuality is reserved for protocols whose documented quality
// values are actually resolution tiers (for example Gemini imageSize).
ResolutionUsesQuality bool `json:"resolutionUsesQuality,omitempty"`
TransparentBackground VideoBooleanConfig `json:"transparentBackground"`
ResponseFormat ParameterSupport `json:"responseFormat"`
OutputFormat ParameterSupport `json:"outputFormat"`
MaxOutputs int `json:"maxOutputs"`
}
type ImageReferenceConfig struct {
@@ -60,6 +66,7 @@ type ImageSizeConfig struct {
Default string `json:"default"`
AllowCustom bool `json:"allowCustom"`
Presets []ImageSizePreset `json:"presets,omitempty"`
DefaultTier string `json:"defaultTier,omitempty"`
}
type ImageSizePreset struct {
@@ -76,6 +83,12 @@ type ImageQualityConfig struct {
Default string `json:"default"`
}
type ImageResolutionConfig struct {
Supported bool `json:"supported"`
Values []string `json:"values"`
Default string `json:"default"`
}
type ParameterSupport struct {
Supported bool `json:"supported"`
}
@@ -147,7 +160,7 @@ func DecodeModelCapabilityConfig(raw string) (*ModelCapabilityConfig, error) {
// normalizedChannelModelCapability 从持久化记录恢复渠道模型的权威能力合同。
// 目录读取可以选择隔离损坏记录;任务创建等写路径必须把错误向上返回并失败关闭。
func normalizedChannelModelCapability(channelModel *model.ChannelModel) (*ModelCapabilityConfig, error) {
func normalizedChannelModelCapability(channelModel *model.ChannelModel, registries ...*protocolcontract.Registry) (*ModelCapabilityConfig, error) {
if channelModel == nil {
return nil, errors.New("渠道模型为空")
}
@@ -162,7 +175,7 @@ func normalizedChannelModelCapability(channelModel *model.ChannelModel) (*ModelC
if err != nil {
return nil, fmt.Errorf("解析渠道模型能力配置失败:%w", err)
}
normalized, err := NormalizeModelCapabilityConfigForModel(capability, string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config)
normalized, err := NormalizeModelCapabilityConfigForModel(capability, string(channelModel.Protocol), firstNonEmpty(channelModel.ProviderModelKey, channelModel.ModelKey), config, registries...)
if err != nil {
return nil, err
}
@@ -173,7 +186,7 @@ func NormalizeModelCapabilityConfig(capability string, protocol string, input *M
return NormalizeModelCapabilityConfigForModel(capability, protocol, "", input)
}
func NormalizeModelCapabilityConfigForModel(capability string, protocol string, modelName string, input *ModelCapabilityConfig) (*ModelCapabilityConfig, error) {
func NormalizeModelCapabilityConfigForModel(capability string, protocol string, modelName string, input *ModelCapabilityConfig, registries ...*protocolcontract.Registry) (*ModelCapabilityConfig, error) {
if capability != "text" && capability != "image" && capability != "video" {
return nil, nil
}
@@ -202,6 +215,27 @@ func NormalizeModelCapabilityConfigForModel(capability string, protocol string,
if input == nil || input.Image == nil {
return nil, BadAuthRequest("请配置图片模型能力参数")
}
if len(registries) > 0 && registries[0] != nil {
if adapter, ok := registries[0].Resolve(protocol); ok && adapter.Metadata().ImageParameters != nil {
if err := resolveImageCapabilityParameters(input.Image, adapter.Metadata().ImageParameters, modelName); err != nil {
return nil, err
}
} else if input.Image.Parameters != nil {
return nil, BadAuthRequest("当前插件未声明图片参数合同,请先更新插件")
}
}
if input.Image.Parameters != nil {
if err := projectImageParameters(input.Image); err != nil {
return nil, err
}
} else {
normalizeLegacyImageResolutionConfig(protocol, input.Image)
input.Image.ResolutionUsesQuality = strings.TrimSpace(protocol) == string(model.ChannelInterfaceGeminiImage)
}
// 旧配置缺换算表时按声明的档位与比例补齐后再校验,保存即把旧线路归一化成当前形态。
if input.Image.Parameters == nil {
fillMissingImageSizePresets(input.Image, protocol)
}
value := &ModelCapabilityConfig{Version: 1, Image: input.Image}
if err := validateImageCapabilityConfig(value.Image); err != nil {
return nil, err
@@ -226,6 +260,71 @@ func NormalizeModelCapabilityConfigForModel(capability string, protocol string,
return value, nil
}
// normalizeLegacyImageResolutionConfig projects legacy values only for protocols whose
// shipped contracts prove that these exact quality values represented resolution tiers.
// The projection is in-memory; persisted capabilities and historical task inputs are untouched.
func normalizeLegacyImageResolutionConfig(protocol string, image *ImageCapabilityConfig) {
if image == nil || image.Resolution.Supported || !image.Quality.Supported {
return
}
allowed := legacyImageResolutionTiers(protocol)
if len(allowed) == 0 {
return
}
values := make([]string, 0, len(image.Quality.Values))
for _, value := range image.Quality.Values {
value = strings.ToLower(strings.TrimSpace(value))
if !allowed[value] {
return
}
values = append(values, value)
}
defaultValue := strings.ToLower(strings.TrimSpace(image.Quality.Default))
if len(values) == 0 || !allowed[defaultValue] || !containsCapabilityString(values, defaultValue) {
return
}
image.Resolution = ImageResolutionConfig{Supported: true, Values: values, Default: defaultValue}
image.Quality = ImageQualityConfig{Supported: false, Values: []string{}, Default: "auto"}
}
func legacyImageResolutionProtocol(protocol string) bool {
return len(legacyImageResolutionTiers(protocol)) > 0
}
func legacyImageResolutionTiers(protocol string) map[string]bool {
switch strings.TrimSpace(protocol) {
case string(model.ChannelInterfaceGrokImage):
return map[string]bool{"1k": true, "2k": true}
case "agnes-image":
return map[string]bool{"1k": true, "2k": true, "4k": true}
default:
return nil
}
}
// normalizeLegacyImageResolutionRequest adapts only old request fields for the same
// proven protocols. Other plugins retain their own quality semantics.
func normalizeLegacyImageResolutionRequest(protocol string, capability *ModelCapabilityConfig, config map[string]any) string {
if capability == nil || capability.Image == nil || !capability.Image.Resolution.Supported || capability.Image.Quality.Supported {
return ""
}
imageResolutionProtocol := strings.TrimSpace(protocol) == string(model.ChannelInterfaceGrokImage) || strings.TrimSpace(protocol) == "agnes-image"
if !imageResolutionProtocol {
return ""
}
legacy := strings.TrimSpace(metadataString(config, "quality"))
if !containsCapabilityString(capability.Image.Resolution.Values, legacy) {
return ""
}
if strings.TrimSpace(metadataString(config, "imageResolution")) != "" {
delete(config, "quality")
return ""
}
config["imageResolution"] = legacy
delete(config, "quality")
return legacy
}
func applyModelSpecificVideoCapability(profile *VideoCapabilityConfig, protocol string, modelName string) *VideoCapabilityConfig {
if profile == nil || model.ChannelInterfaceType(strings.TrimSpace(protocol)) != model.ChannelInterfaceAgnesVideo {
return profile
@@ -304,6 +403,14 @@ func CapabilitySpecFromModelCapabilityConfig(config *ModelCapabilityConfig, capa
if image.Size.Parameter != "none" {
spec.Options["size"] = imageSizeOptionConstraint(image.Size)
spec.ImageSize = capabilityImageSizeFromConfig(image.Size)
if image.Parameters != nil && !image.Resolution.Supported {
size := image.Size
size.Presets = activeImageSizePresets(image)
spec.ImageSize = capabilityImageSizeFromConfig(size)
}
}
if image.Resolution.Supported {
spec.Options["imageResolution"] = anyValues(image.Resolution.Values)
}
if image.Quality.Supported {
spec.Options["quality"] = anyValues(image.Quality.Values)
@@ -314,6 +421,10 @@ func CapabilitySpecFromModelCapabilityConfig(config *ModelCapabilityConfig, capa
spec.Options["transparentBackground"] = boolValues(false)
}
spec.Options["count"] = numericRange(1, float64(image.MaxOutputs), 1)
if image.Parameters != nil {
spec.Options = imageParameterConstraints(image.Parameters)
spec.ImageParameters = publicImageParameters(image.Parameters)
}
case "video":
if config.Video == nil {
return spec, BadAuthRequest("渠道视频模型尚未配置能力参数")
@@ -391,7 +502,7 @@ func capabilityImageSizeFromConfig(size ImageSizeConfig) *CapabilityImageSize {
tier := strings.ToLower(strings.TrimSpace(preset.Tier))
ratio := strings.TrimSpace(preset.Ratio)
value := strings.TrimSpace(preset.Size)
if tier == "" || ratio == "" || value == "" {
if ratio == "" || value == "" {
continue
}
result.Presets = append(result.Presets, CapabilityImageSizePreset{
@@ -3,6 +3,7 @@
package app
import (
"strconv"
"strings"
"yingce/backend/internal/model"
@@ -27,6 +28,10 @@ func DefaultImageCapabilityConfig(protocol string, modelName string) *ImageCapab
MaxOutputs: 15,
}
switch model.ChannelInterfaceType(protocol) {
case model.ChannelInterfaceOpenAIImage:
// OpenAI Images 只收 WIDTHxHEIGHT:默认配置声明了 1K/2K/4K,就必须自带档位换算表,
// 否则运行时换算会被静默跳过(见 imageSizePresetMissing),实际出图档位与所选档位不一致。
image.Size.Presets = openAIImageDefaultSizePresets()
case "km-kemei-seedream":
image.References.MaxImages = 10
image.References.MaskSupported = false
@@ -45,7 +50,8 @@ func DefaultImageCapabilityConfig(protocol string, modelName string) *ImageCapab
image.References.MaskSupported = false
// grok2api / xAI Imagine:size→aspect_ratio,quality→resolution(1k/2k)。
image.Size = ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"1:1", "3:4", "4:3", "9:16", "16:9", "2:3", "3:2"}, Default: "1:1", AllowCustom: false}
image.Quality = ImageQualityConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "2k"}
image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "2k"}
image.Quality = ImageQualityConfig{Supported: false, Default: "auto"}
image.TransparentBackground = VideoBooleanConfig{Supported: false, Default: false}
image.ResponseFormat = ParameterSupport{Supported: true}
image.OutputFormat = ParameterSupport{Supported: false}
@@ -71,12 +77,14 @@ func DefaultImageCapabilityConfig(protocol string, modelName string) *ImageCapab
image.ResponseFormat.Supported = false
image.OutputFormat.Supported = false
image.MaxOutputs = 4
image.ResolutionUsesQuality = true
}
if model.ChannelInterfaceType(protocol) != model.ChannelInterfaceGrokImage && strings.HasPrefix(strings.ToLower(strings.TrimSpace(modelName)), "grok-imagine-image") {
image.References.MaxImages = 0
image.References.MaskSupported = false
image.Size = ImageSizeConfig{Parameter: "aspect_ratio", Values: []string{"1:1", "3:4", "4:3", "9:16", "16:9", "2:3", "3:2"}, Default: "1:1", AllowCustom: false}
image.Quality = ImageQualityConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "2k"}
image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "2k"}
image.Quality = ImageQualityConfig{Supported: false, Default: "auto"}
image.TransparentBackground = VideoBooleanConfig{Supported: false, Default: false}
image.ResponseFormat = ParameterSupport{Supported: true}
image.OutputFormat = ParameterSupport{Supported: false}
@@ -94,6 +102,45 @@ func defaultImageSizeValues() []string {
}
}
// openAIImageDefaultSizeTable 是 openai-image 默认能力配置的档位换算表(比例 × 1K/2K/4K)。
// 像素值与库内 openai-image 线路实际使用的预设逐项一致(gpt-image-2 / 2.5 / 4k 的 1K/2K/4K 全部命中),
// 且都在 defaultImageSizeValues() 里,不引入未声明的尺寸。
var openAIImageDefaultSizeTable = []struct {
ratio string
tierSizes [3]string
}{
{"1:1", [3]string{"1024x1024", "2048x2048", "2880x2880"}},
{"16:9", [3]string{"1824x1024", "2752x1536", "3840x2160"}},
{"9:16", [3]string{"1024x1824", "1536x2752", "2160x3840"}},
{"4:3", [3]string{"1360x1024", "2304x1728", "3264x2448"}},
{"3:4", [3]string{"1024x1360", "1728x2304", "2448x3264"}},
{"3:2", [3]string{"1536x1024", "2496x1664", "3504x2336"}},
{"2:3", [3]string{"1024x1536", "1664x2496", "2336x3504"}},
{"4:5", [3]string{"1024x1280", "1792x2240", "2560x3200"}},
{"5:4", [3]string{"1280x1024", "2240x1792", "3200x2560"}},
{"21:9", [3]string{"2048x878", "3136x1344", "3808x1632"}},
}
// openAIImageDefaultSizePresets 把上面的表展开成 3 个档位 × 10 个比例的预设。
// 像素值都来自 defaultImageSizeValues(),validateImageCapabilityConfig 会校验与支持值一致。
func openAIImageDefaultSizePresets() []ImageSizePreset {
tiers := []string{"1k", "2k", "4k"}
presets := make([]ImageSizePreset, 0, len(openAIImageDefaultSizeTable)*len(tiers))
for _, entry := range openAIImageDefaultSizeTable {
for index, tier := range tiers {
size := entry.tierSizes[index]
widthText, heightText, found := strings.Cut(size, "x")
width, widthErr := strconv.Atoi(widthText)
height, heightErr := strconv.Atoi(heightText)
if !found || widthErr != nil || heightErr != nil {
continue
}
presets = append(presets, ImageSizePreset{Tier: tier, Ratio: entry.ratio, Size: size, Width: width, Height: height})
}
}
return presets
}
// legacyImageSizeValues 用于修复旧数据中仅保存了 "*" 的图片尺寸能力。
// 这组值是前后台共同展示的基础预设,不能让历史通配符配置继续污染用户生成参数。
func legacyImageSizeValues() []string {
+464 -13
View File
@@ -54,7 +54,7 @@ func validateImageCapabilityConfig(value *ImageCapabilityConfig) error {
value.Size.Default = "auto"
value.Size.AllowCustom = false
case "size", "aspect_ratio":
if strings.TrimSpace(value.Size.Default) == "" {
if value.Parameters == nil && strings.TrimSpace(value.Size.Default) == "" {
return BadAuthRequest("请配置默认图片尺寸或比例")
}
if !value.Size.AllowCustom && !containsCapabilityString(value.Size.Values, value.Size.Default) {
@@ -65,19 +65,25 @@ func validateImageCapabilityConfig(value *ImageCapabilityConfig) error {
}
seenPresets := make(map[string]bool)
for _, preset := range value.Size.Presets {
if preset.Tier != "1k" && preset.Tier != "1.5k" && preset.Tier != "2k" && preset.Tier != "4k" {
if value.Parameters == nil && preset.Tier != "1k" && preset.Tier != "1.5k" && preset.Tier != "2k" && preset.Tier != "4k" {
return BadAuthRequest("图片分辨率档位仅支持 1K、1.5K、2K、4K")
}
if value.Parameters != nil && value.Resolution.Supported && !containsCapabilityString(value.Resolution.Values, preset.Tier) {
return BadAuthRequest("像素映射使用了未启用的分辨率")
}
parts := strings.Split(preset.Ratio, ":")
if len(parts) != 2 {
return BadAuthRequest("图片预设比例格式无效")
}
w, ew := strconv.Atoi(parts[0])
h, eh := strconv.Atoi(parts[1])
if ew != nil || eh != nil || w <= 0 || h <= 0 || w > 100000 || h > 100000 || max(w, h) > min(w, h)*3 {
if ew != nil || eh != nil || w <= 0 || h <= 0 || w > 100000 || h > 100000 || value.Parameters == nil && max(w, h) > min(w, h)*3 {
return BadAuthRequest("图片预设比例无效")
}
if preset.Width <= 0 || preset.Height <= 0 || max(preset.Width, preset.Height) > 3840 || max(preset.Width, preset.Height) > min(preset.Width, preset.Height)*3 || preset.Width*preset.Height < 655360 || preset.Width*preset.Height > 8294400 || preset.Size != fmt.Sprintf("%dx%d", preset.Width, preset.Height) {
if preset.Width <= 0 || preset.Height <= 0 || max(preset.Width, preset.Height) > 100000 || preset.Size != fmt.Sprintf("%dx%d", preset.Width, preset.Height) {
return BadAuthRequest("图片预设像素尺寸无效")
}
if value.Parameters == nil && (max(preset.Width, preset.Height) > 3840 || max(preset.Width, preset.Height) > min(preset.Width, preset.Height)*3 || preset.Width*preset.Height < 655360 || preset.Width*preset.Height > 8294400) {
return BadAuthRequest("图片预设像素尺寸无效")
}
// 容许像素取整误差,但不能将横屏尺寸标记成竖屏或其他比例。
@@ -106,14 +112,26 @@ func validateImageCapabilityConfig(value *ImageCapabilityConfig) error {
}
}
if value.Quality.Supported {
if len(value.Quality.Values) == 0 || strings.TrimSpace(value.Quality.Default) == "" || !containsCapabilityString(value.Quality.Values, value.Quality.Default) {
if value.Parameters == nil && (len(value.Quality.Values) == 0 || strings.TrimSpace(value.Quality.Default) == "" || !containsCapabilityString(value.Quality.Values, value.Quality.Default)) {
return BadAuthRequest("请配置图片质量支持值和默认值")
}
} else {
value.Quality.Values = []string{}
value.Quality.Default = "auto"
}
if err := validateImagePresetSelection(value, value.Quality.Default, value.Size.Default); err != nil {
if value.Resolution.Supported {
if value.Parameters == nil && (len(value.Resolution.Values) == 0 || strings.TrimSpace(value.Resolution.Default) == "" || !containsCapabilityString(value.Resolution.Values, value.Resolution.Default)) {
return BadAuthRequest("请配置图片分辨率支持值和默认值")
}
} else {
value.Resolution.Values = []string{}
value.Resolution.Default = "auto"
}
defaultTier := value.Quality.Default
if value.Resolution.Supported {
defaultTier = value.Resolution.Default
}
if err := validateImagePresetSelection(value, defaultTier, value.Size.Default); err != nil {
return BadAuthRequest("默认图片分辨率与宽高比不在已配置的组合中")
}
if !value.TransparentBackground.Supported {
@@ -215,7 +233,18 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
if taskInput.Config.CapabilityConfig != nil && taskInput.Config.CapabilityConfig.Image != nil {
profile = taskInput.Config.CapabilityConfig.Image
}
return validateImageTask(profile, taskInput)
normalized, err := NormalizeModelCapabilityConfigForModel("image", taskInput.Config.InterfaceType, taskInput.Config.Model, &ModelCapabilityConfig{Version: 1, Image: profile}, s.protocolRegistry())
if err != nil {
return err
}
profile = normalized.Image
if profile.Parameters == nil {
fillMissingImageSizePresets(profile, taskInput.Config.InterfaceType)
}
if presetErr := imageSizePresetReadyError(profile, taskInput.Config.InterfaceType); presetErr != nil {
return presetErr
}
return validateImageTaskWithResolvedSize(input, &taskInput, profile)
}
profile := taskInput.Config.CapabilityConfig
if profile == nil || profile.Video == nil {
@@ -240,6 +269,7 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
}
profile, err := DecodeModelCapabilityConfig(item.CapabilityConfigJSON)
if taskInput.Mode == "image" {
profile, err = normalizedChannelModelCapability(item, s.protocolRegistry())
if err != nil {
return BadAuthRequest("当前图片模型能力参数无效")
}
@@ -247,7 +277,15 @@ func (s *Service) ValidateTaskCapability(input map[string]any) error {
if profile != nil && profile.Image != nil {
imageProfile = profile.Image
}
return validateImageTask(applyModelSpecificImageCapability(imageProfile, string(item.Protocol), firstNonEmpty(item.ProviderModelKey, item.ModelKey), taskInput.Config.APIFormat), taskInput)
imageProfile = applyModelSpecificImageCapability(imageProfile, string(item.Protocol), firstNonEmpty(item.ProviderModelKey, item.ModelKey), taskInput.Config.APIFormat)
// 旧线路没有换算表时按声明的档位补齐;补不齐就失败关闭,不能静默按 1K 出图。
if imageProfile.Parameters == nil {
fillMissingImageSizePresets(imageProfile, string(item.Protocol))
}
if presetErr := imageSizePresetReadyError(imageProfile, string(item.Protocol)); presetErr != nil {
return presetErr
}
return validateImageTaskWithResolvedSize(input, &taskInput, imageProfile)
}
if err != nil || profile == nil || profile.Video == nil {
return BadAuthRequest("当前视频模型尚未配置能力参数")
@@ -348,6 +386,11 @@ func validateImageTask(profile *ImageCapabilityConfig, input canvasGenerationInp
if profile == nil {
return nil
}
if profile.Parameters != nil {
if _, err := resolveImageParameterValues(profile.Parameters, input.Config.ImageParameters); err != nil {
return err
}
}
modelName := strings.TrimPrefix(strings.ToLower(strings.TrimSpace(input.Config.Model)), "models/")
if input.Config.InterfaceType == string(model.ChannelInterfaceGrokImage) && modelName == "grok-imagine-image-quality" {
const maxPromptBytes = 8000
@@ -367,19 +410,32 @@ func validateImageTask(profile *ImageCapabilityConfig, input canvasGenerationInp
if input.Mask != nil && !profile.References.MaskSupported {
return BadAuthRequest("当前图片模型不支持蒙版编辑")
}
if profile.Size.Parameter != "none" && !profile.Size.AllowCustom && strings.TrimSpace(input.Config.Size) != "" && !containsCapabilityString(profile.Size.Values, input.Config.Size) {
quality := strings.TrimSpace(input.Config.Quality)
resolution := strings.TrimSpace(input.Config.ImageResolution)
if profile.Resolution.Supported && resolution != "" && !strings.EqualFold(resolution, "auto") && !strings.EqualFold(resolution, "any") && !containsCapabilityString(profile.Resolution.Values, resolution) {
return BadAuthRequest("图片分辨率不在当前模型支持范围内")
}
selectionTier := quality
if profile.Resolution.Supported {
selectionTier = resolution
}
// 比例型线路会在任务输入边界把画布比例换算成 preset 像素值(OpenAI Images 只收
// WIDTHxHEIGHT)。换算结果必须继续通过同一套尺寸与分辨率校验:先把已声明的 preset
// 像素值还原成对应比例,否则执行前的 provider 预检会把刚换算好的值判成不支持的尺寸。
resolvedRatio := imageSizeRatioForDeclaredPreset(profile, input.Config.Size, qualityForImageValidation(selectionTier, profile.Resolution.Default))
if profile.Size.Parameter != "none" && !profile.Size.AllowCustom && strings.TrimSpace(input.Config.Size) != "" &&
!containsCapabilityString(profile.Size.Values, input.Config.Size) && resolvedRatio == "" {
return BadAuthRequest("图片尺寸不在当前模型支持范围内")
}
if profile.Size.Parameter == "size" && profile.Size.AllowCustom && strings.HasPrefix(modelName, "gpt-image-2") && !containsCapabilityString(profile.Size.Values, input.Config.Size) {
if profile.Parameters == nil && profile.Size.Parameter == "size" && profile.Size.AllowCustom && strings.HasPrefix(modelName, "gpt-image-2") && !containsCapabilityString(profile.Size.Values, input.Config.Size) {
if err := validateGPTImage2CustomSize(input.Config.Size); err != nil {
return BadAuthRequest(err.Error())
}
}
quality := strings.TrimSpace(input.Config.Quality)
if profile.Quality.Supported && quality != "" && !strings.EqualFold(quality, "auto") && !strings.EqualFold(quality, "any") && !containsCapabilityString(profile.Quality.Values, quality) {
return BadAuthRequest("图片质量不在当前模型支持范围内")
}
if err := validateImagePresetSelection(profile, qualityForImageValidation(quality, profile.Quality.Default), firstNonEmpty(input.Config.Size, profile.Size.Default)); err != nil {
if err := validateImagePresetSelection(profile, qualityForImageValidation(selectionTier, firstNonEmpty(profile.Resolution.Default, profile.Quality.Default)), firstNonEmpty(resolvedRatio, input.Config.Size, profile.Size.Default)); err != nil {
return err
}
count, err := strconv.Atoi(strings.TrimSpace(input.Config.Count))
@@ -389,6 +445,29 @@ func validateImageTask(profile *ImageCapabilityConfig, input canvasGenerationInp
return nil
}
func validateImageTaskWithResolvedSize(input map[string]any, taskInput *canvasGenerationInput, profile *ImageCapabilityConfig) error {
if profile.Parameters != nil {
if err := applyImageParameterValues(&taskInput.Config, profile); err != nil {
return err
}
if config, ok := input["config"].(map[string]any); ok {
config["imageParameters"] = taskInput.Config.ImageParameters
config["size"], config["quality"], config["imageResolution"] = taskInput.Config.Size, taskInput.Config.Quality, taskInput.Config.ImageResolution
config["count"], config["transparentBackground"] = taskInput.Config.Count, taskInput.Config.TransparentBackground
}
return validateImageTask(profile, *taskInput)
}
if imageSizeResolutionAfterValidation(profile, taskInput.Config.InterfaceType) {
if err := validateImageTask(profile, *taskInput); err != nil {
return err
}
applyImageSizeResolution(input, taskInput, profile)
return nil
}
applyImageSizeResolution(input, taskInput, profile)
return validateImageTask(profile, *taskInput)
}
func qualityForImageValidation(quality string, fallback string) string {
if strings.EqualFold(quality, "auto") || strings.EqualFold(quality, "any") {
return fallback
@@ -400,7 +479,7 @@ func validateImagePresetSelection(profile *ImageCapabilityConfig, quality, ratio
if profile.Size.Parameter != "aspect_ratio" || profile.Size.AllowCustom || len(profile.Size.Presets) == 0 || ratio == "auto" {
return nil
}
tier := imageResolutionTier(quality)
tier := imagePresetSelectionTier(profile, quality)
if tier == "" {
return nil
}
@@ -412,6 +491,62 @@ func validateImagePresetSelection(profile *ImageCapabilityConfig, quality, ratio
return BadAuthRequest("当前分辨率不支持所选图片宽高比")
}
// imageSizeRatioForDeclaredPreset 把已声明的 preset 像素值还原成它对应的比例。比例型线路
// 会把画布比例换算成 preset 像素值(OpenAI Images 只收 WIDTHxHEIGHT),换算结果必须继续
// 通过同一套尺寸与分辨率校验。只认当前档位的 preset,避免用低档价格取到高档像素。
func imageSizeRatioForDeclaredPreset(profile *ImageCapabilityConfig, size string, quality string) string {
if profile == nil {
return ""
}
value := strings.TrimSpace(size)
if value == "" || !strings.ContainsAny(value, "xX") {
return ""
}
if preset, ok := declaredImageSizePreset(profile.Size.Presets, value, imagePresetSelectionTier(profile, quality), imagePresetDefaultTier(profile)); ok {
return normalizeDeclaredImageRatio(preset.Ratio)
}
return ""
}
func declaredImageSizePreset(presets []ImageSizePreset, value string, quality string, fallbackQuality string) (ImageSizePreset, bool) {
value = strings.TrimSpace(value)
if value == "" || strings.EqualFold(value, "auto") {
return ImageSizePreset{}, false
}
tier := strings.TrimSpace(quality)
if tier == "" {
tier = strings.TrimSpace(fallbackQuality)
}
ratio := ""
if strings.Contains(value, ":") {
ratio = normalizeDeclaredImageRatio(value)
}
for _, preset := range presets {
if tier != "" && !strings.EqualFold(strings.TrimSpace(preset.Tier), tier) {
continue
}
if (ratio != "" && normalizeDeclaredImageRatio(preset.Ratio) == ratio) || strings.EqualFold(strings.TrimSpace(preset.Size), value) {
return preset, true
}
}
return ImageSizePreset{}, false
}
func normalizeDeclaredImageRatio(value string) string {
ratio := normalizeImageAspectRatio(value)
left, right, found := strings.Cut(ratio, ":")
if !found {
return ratio
}
width, widthErr := strconv.Atoi(left)
height, heightErr := strconv.Atoi(right)
if widthErr != nil || heightErr != nil || width <= 0 || height <= 0 {
return ratio
}
divisor := imageDimensionGCD(width, height)
return strconv.Itoa(width/divisor) + ":" + strconv.Itoa(height/divisor)
}
func imageResolutionTier(quality string) string {
switch strings.ToLower(strings.TrimSpace(quality)) {
case "1k", "low":
@@ -427,6 +562,322 @@ func imageResolutionTier(quality string) string {
}
}
func declaredImageResolutionTier(value string) string {
switch strings.ToLower(strings.TrimSpace(value)) {
case "1k", "1.5k", "2k", "4k":
return strings.ToLower(strings.TrimSpace(value))
default:
return ""
}
}
// Legacy aliases are meaningful only when the model explicitly declares resolution tiers.
// Ordinary image quality never selects a pixel preset.
func imagePresetSelectionTier(profile *ImageCapabilityConfig, value string) string {
if profile.Parameters != nil {
if profile.Resolution.Supported && containsCapabilityString(profile.Resolution.Values, value) {
return value
}
if !profile.Resolution.Supported {
if tier, ok := singleImageSizeTier(profile); ok {
return tier
}
}
return ""
}
if tier := declaredImageResolutionTier(value); tier != "" {
return tier
}
if profile.Resolution.Supported || (profile.Quality.Supported && profile.ResolutionUsesQuality) {
return imageResolutionTier(value)
}
for _, quality := range profile.Quality.Values {
if declaredImageResolutionTier(quality) != "" {
return imageResolutionTier(value)
}
}
return ""
}
func imagePresetDefaultTier(profile *ImageCapabilityConfig) string {
if profile.Resolution.Supported {
return imagePresetSelectionTier(profile, profile.Resolution.Default)
}
return imagePresetSelectionTier(profile, profile.Quality.Default)
}
// resolveImageTaskSize 把画布按比例保存的 size(如 16:9)换算成图片模型
// 声明的 preset 像素尺寸。声明式 OpenAI Images 协议把统一请求的 aspectRatio
// 原样映射到上游 size 字段,只认 WIDTHxHEIGHT 的上游会拒绝比例字符串,所以
// 换算必须在任务输入边界完成。未命中 preset 的组合不做猜测,交给能力校验给
// 出明确错误。
func resolveImageTaskSize(profile *ImageCapabilityConfig, interfaceType string, size string, quality string) string {
if profile == nil {
return size
}
value := strings.TrimSpace(size)
if value == "" || strings.EqualFold(value, "auto") {
return size
}
preset, ok := declaredImageSizePreset(activeImageSizePresets(profile), value, imagePresetSelectionTier(profile, quality), imagePresetDefaultTier(profile))
if !ok {
return size
}
if imageSizePixelOutbound(profile, interfaceType) {
return preset.Size
}
if profile.Size.Parameter == "aspect_ratio" {
return normalizeDeclaredImageRatio(preset.Ratio)
}
return size
}
// imageSizePixelOutbound 表示该线路出网需要像素尺寸,决定“比例 → 像素”换算是否发生。
// parameter=size 由字段本身要求像素;aspect_ratio 只在声明式 OpenAI Images 上被翻成像素。
func imageSizePixelOutbound(profile *ImageCapabilityConfig, protocol string) bool {
if profile == nil {
return false
}
if profile.Parameters != nil {
for _, p := range profile.Parameters {
if p.Name == "size" && p.IsEnabled() {
return p.Encoding == "pixels"
}
}
return false
}
if profile.Size.Parameter == "size" {
return true
}
return profile.Size.Parameter == "aspect_ratio" && strings.TrimSpace(protocol) == string(model.ChannelInterfaceOpenAIImage)
}
// imageSizeClientSubmitsRatio 表示画布会按比例提交尺寸。size 字段里出现比例值属于历史
// 遗留形态:字段名说“发送像素”,值却是比例,同样需要换算表。
func imageSizeClientSubmitsRatio(profile *ImageCapabilityConfig) bool {
if profile.Size.Parameter == "aspect_ratio" || profile.Size.AllowCustom {
return true
}
if strings.Contains(profile.Size.Default, ":") {
return true
}
for _, value := range profile.Size.Values {
if strings.Contains(value, ":") {
return true
}
}
return false
}
// imageSizePresetMissingExact 是规则本体:出网需要像素、客户端按比例提交、没有换算表、
// 且确实有档位要被编码进尺寸。与 imageSizeResolutionEnabled 共用 imageSizePixelOutbound,
// 保证“需要换算”只有一个判断来源。size + 像素值 + 无预设表 的线路不需要换算,不能误伤。
func imageSizePresetMissingExact(profile *ImageCapabilityConfig, protocol string) bool {
return imageSizePixelOutbound(profile, protocol) && len(profile.Size.Presets) == 0 && imageSizeClientSubmitsRatio(profile)
}
// imageSizePresetMissing 在规则本体上再要求“有可解析的档位”:没有档位声明的线路(如 ark、
// 即梦图片)档位不参与请求,用不着换算表,不能因为缺表就判为配置不完整。
func imageSizePresetMissing(profile *ImageCapabilityConfig, protocol string) bool {
if !imageSizePresetMissingExact(profile, protocol) {
return false
}
if profile.Parameters != nil {
return true
}
return len(imageSizeDeclaredTiers(profile)) > 0
}
// imageSizeDeclaredTiers 取出该线路声明里可解析的分辨率档位。只有"档位要被编码进尺寸"的
// 线路才需要换算表:没有质量档位声明(例如 ark / 即梦图片)时,档位不参与请求,用不着表。
func imageSizeDeclaredTiers(profile *ImageCapabilityConfig) []string {
tiers := make([]string, 0, 3)
seen := make(map[string]bool, 3)
add := func(value string) {
tier := imageResolutionTier(value)
if tier == "" || seen[tier] {
return
}
seen[tier] = true
tiers = append(tiers, tier)
}
if profile.Quality.Supported {
for _, value := range profile.Quality.Values {
add(value)
}
}
add(profile.Quality.Default)
return tiers
}
// imageSizeDeclaredRatios 取出该线路声明里按比例形式的支持值与默认值,归一化后去重。
func imageSizeDeclaredRatios(profile *ImageCapabilityConfig) []string {
ratios := make([]string, 0, len(profile.Size.Values))
seen := make(map[string]bool, len(profile.Size.Values)+1)
add := func(value string) {
if !strings.Contains(value, ":") {
return
}
ratio := normalizeImageAspectRatio(value)
if ratio == "" || seen[ratio] {
return
}
seen[ratio] = true
ratios = append(ratios, ratio)
}
add(profile.Size.Default)
for _, value := range profile.Size.Values {
add(value)
}
return ratios
}
// openAIImageDefaultPixelSize 从默认换算表取「比例 + 档位」对应的像素尺寸。
func openAIImageDefaultPixelSize(ratio string, tier string) (ImageSizePreset, bool) {
index := -1
switch tier {
case "1k":
index = 0
case "2k":
index = 1
case "4k":
index = 2
}
if index < 0 {
return ImageSizePreset{}, false
}
for _, entry := range openAIImageDefaultSizeTable {
if entry.ratio != ratio {
continue
}
size := entry.tierSizes[index]
widthText, heightText, found := strings.Cut(size, "x")
width, widthErr := strconv.Atoi(widthText)
height, heightErr := strconv.Atoi(heightText)
if !found || widthErr != nil || heightErr != nil {
return ImageSizePreset{}, false
}
return ImageSizePreset{Tier: tier, Ratio: ratio, Size: size, Width: width, Height: height}, true
}
return ImageSizePreset{}, false
}
// fillMissingImageSizePresets 为「出网需要像素、按比例提交、却没有换算表」的旧线路补齐
// 换算表:按线路自己声明的档位与比例,从 openAIImageDefaultSizeTable 取值。这与
// legacyImageSizeValues 修复旧通配符尺寸是同一套做法 —— 旧数据在读取边界补成当前形态,
// 而不是要求人工逐条重配。补不齐(声明了表里没有的比例)时保持原样,交给调用方拒绝。
// 返回是否发生了补齐。
func fillMissingImageSizePresets(profile *ImageCapabilityConfig, protocol string) bool {
if !imageSizePresetMissingExact(profile, protocol) {
return false
}
tiers := imageSizeDeclaredTiers(profile)
ratios := imageSizeDeclaredRatios(profile)
if len(tiers) == 0 || len(ratios) == 0 {
return false
}
presets := make([]ImageSizePreset, 0, len(tiers)*len(ratios))
for _, tier := range tiers {
for _, ratio := range ratios {
if preset, ok := openAIImageDefaultPixelSize(ratio, tier); ok {
presets = append(presets, preset)
}
}
}
if len(presets) == 0 {
return false
}
profile.Size.Presets = presets
if profile.Size.Parameter == "size" {
// parameter=size 的线路要求预设像素值同时出现在支持值里(validateImageCapabilityConfig),
// 与前端 imageSizeConfigWithPresets 的做法一致。
for _, preset := range presets {
if !containsCapabilityString(profile.Size.Values, preset.Size) {
profile.Size.Values = append(profile.Size.Values, preset.Size)
}
}
}
return true
}
// imageSizePresetReadyError 是运行时的失败关闭点:需要把档位换算成像素、又确实没有可用的
// 换算表(含补不齐的情况)时,宁可报错,也不要静默按 1K 出图。
func imageSizePresetReadyError(profile *ImageCapabilityConfig, protocol string) error {
if !imageSizePresetMissing(profile, protocol) {
return nil
}
return BadAuthRequest("当前线路缺少像素尺寸换算表,无法把所选比例与档位换算成上游要求的像素尺寸;请在管理端为该线路的每个档位配置像素预设")
}
// validateImageSizePresetRequirement 是写路径(保存渠道模型)使用的完整性校验:
// 出网需要像素、客户端又按比例提交时必须有换算表。读路径不做这个拦截。
func validateImageSizePresetRequirement(capability string, protocol string, profile *ModelCapabilityConfig) error {
if normalizeCapability(capability) != "image" || profile == nil {
return nil
}
if image := profile.Image; image != nil && image.Parameters != nil && imageSizePixelOutbound(image, protocol) {
if !image.Resolution.Supported && len(image.Size.Presets) > 0 {
if _, ok := singleImageSizeTier(image); !ok || len(activeImageSizePresets(image)) == 0 {
return BadAuthRequest("关闭分辨率前请设置默认尺寸档位")
}
}
hasRatios := false
for _, ratio := range image.Size.Values {
if !strings.Contains(ratio, ":") {
continue
}
hasRatios = true
if _, ok := declaredImageSizePreset(image.Size.Presets, ratio, "", ""); !ok {
return BadAuthRequest(fmt.Sprintf("请配置比例 %s 对应的像素尺寸", ratio))
}
}
// Each tier owns its available ratios; the cartesian product is not required.
if hasRatios && image.Resolution.Supported {
for _, tier := range image.Resolution.Values {
found := false
for _, preset := range image.Size.Presets {
if preset.Tier == tier {
found = true
break
}
}
if !found {
return BadAuthRequest(fmt.Sprintf("请为分辨率 %s 至少配置一个比例", tier))
}
}
}
}
if !imageSizePresetMissing(profile.Image, protocol) {
return nil
}
return BadAuthRequest("该线路按像素尺寸出网但未配置像素预设:请为每个分辨率档位填写对应的像素尺寸,否则实际出图尺寸会与所选档位不一致")
}
func imageSizeResolutionEnabled(profile *ImageCapabilityConfig, interfaceType string) bool {
return imageSizePixelOutbound(profile, interfaceType) && len(profile.Size.Presets) > 0
}
func imageSizeResolutionAfterValidation(profile *ImageCapabilityConfig, interfaceType string) bool {
return profile != nil && profile.Size.Parameter != "size" && imageSizeResolutionEnabled(profile, interfaceType)
}
// applyImageSizeResolution 把换算结果写回任务输入,与视频的 applyVideoResolution
// 写回 config.vquality 同一机制,保证持久化的任务输入已是可执行值。
func applyImageSizeResolution(input map[string]any, taskInput *canvasGenerationInput, profile *ImageCapabilityConfig) {
tier := taskInput.Config.Quality
if profile.Resolution.Supported {
tier = taskInput.Config.ImageResolution
}
resolved := resolveImageTaskSize(profile, taskInput.Config.InterfaceType, taskInput.Config.Size, tier)
if resolved == taskInput.Config.Size {
return
}
taskInput.Config.Size = resolved
if config, ok := input["config"].(map[string]any); ok {
config["size"] = resolved
}
}
func validateWorkflowProviderPromptLength(input canvasGenerationInput) error {
profile := input.Config.CapabilityConfig
if input.Mode != "video" || profile == nil || profile.Video == nil {
+11 -6
View File
@@ -190,6 +190,10 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) (PublicChannelMod
if cm == nil {
return PublicChannelModel{}, fmt.Errorf("渠道模型为空")
}
normalized, err := normalizedChannelModelCapability(cm, s.protocolRegistry())
if err != nil {
return PublicChannelModel{}, err
}
// 仓储层已预加载价格档;这里只发布当前启用且价格字段自洽的活动档位。
priceTiers := cm.PriceTiers
@@ -198,6 +202,11 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) (PublicChannelMod
if !tier.Enabled || !tier.PriceConfigured || !ValidatePriceTierPrice(&tier, cm.Capability, cm.Protocol) {
continue
}
if normalized != nil && normalized.Image != nil && normalized.Image.Parameters != nil {
if validateImageParameterPriceSelector(normalized.Image.Parameters, model.DecodeSKUSelector(tier.SelectorJSON)) != nil {
continue
}
}
publicTiers = append(publicTiers, PublicChannelModelPriceTier{
ID: tier.ID,
Selector: model.DecodeSKUSelector(tier.SelectorJSON),
@@ -215,10 +224,6 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) (PublicChannelMod
pricingMode, displayPrice, priceLabel := computeChannelModelPriceDisplay(cm, publicTiers)
var capabilityConfig map[string]any
normalized, err := normalizedChannelModelCapability(cm)
if err != nil {
return PublicChannelModel{}, err
}
if normalized != nil {
capabilityConfig, err = modelCapabilityConfigToMap(normalized)
if err != nil {
@@ -231,7 +236,7 @@ func (s *Service) sanitizeChannelModel(cm *model.ChannelModel) (PublicChannelMod
if specErr != nil {
return PublicChannelModel{}, fmt.Errorf("投影渠道模型默认参数失败:%w", specErr)
}
defaultOptions, err = channelModelDefaultOptions(*cm, spec)
defaultOptions, err = channelModelDefaultOptions(*cm, spec, s.protocolRegistry())
if err != nil {
return PublicChannelModel{}, err
}
@@ -303,7 +308,7 @@ func (s *Service) channelModelMatchesIntent(cm *model.ChannelModel, intent *Mode
if normalizeCapability(cm.Capability) == "audio" {
return true, nil
}
config, err := normalizedChannelModelCapability(cm)
config, err := normalizedChannelModelCapability(cm, s.protocolRegistry())
if err != nil {
return false, err
}
+66 -7
View File
@@ -167,7 +167,7 @@ func (s *Service) loadRouteCatalog() (*routeCatalogSnapshot, error) {
if item.PricePolicy == "channel" && !channelModelHasActivePriceTier(channelModel) {
continue
}
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel)
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel, s.protocolRegistry())
if specErr != nil {
log.Printf("logical route omitted from catalog route_id=%s channel_model_id=%s: invalid capability: %v", route.ID, channelModel.ID, specErr)
continue
@@ -200,7 +200,12 @@ func (s *Service) ResolveLogicalModel(logicalModelID string, intent ModelRequest
if !ok {
return nil, BadAuthRequest("所选模型不可用")
}
intent.Options = mergeIntentDefaults(intent.Options, cached.Defaults)
intent = resolveModelRequestIntent(cached.ProductSpec, intent, cached.Defaults)
if parameters := cached.ProductSpec.ImageParameters; parameters != nil {
if _, err := resolveImageParameterValues(parameters, intent.Options); err != nil {
return nil, err
}
}
if match := MatchCapability(cached.ProductSpec, intent); !match.Matched {
return nil, BadAuthRequest("所选模型不支持当前请求:" + strings.Join(match.Reasons, ";"))
}
@@ -211,12 +216,12 @@ func (s *Service) ResolveLogicalModel(logicalModelID string, intent ModelRequest
selected := weightedRoute(eligible)
var priceTier *model.ChannelModelPriceTier
if cached.Model.PricePolicy == "channel" {
priceTier = channelModelPriceTierForIntent(selected.ChannelModel, intent)
priceTier = channelModelPriceTierForIntent(selected.ChannelModel, intent, selected.CapabilitySpec)
if priceTier == nil {
return nil, BadAuthRequest("当前模型尚未配置所选规格的价格")
}
}
return &RoutedModel{LogicalModel: cached.Model, Revision: cached.Revision, Route: selected.Route, ChannelModel: selected.ChannelModel, PriceTier: priceTier, Defaults: cached.Defaults}, nil
return &RoutedModel{LogicalModel: cached.Model, Revision: cached.Revision, Route: selected.Route, ChannelModel: selected.ChannelModel, CapabilitySpec: selected.CapabilitySpec, PriceTier: priceTier, Defaults: cached.Defaults, Intent: intent}, nil
}
func (s *Service) eligibleLogicalRoutes(routes []cachedLogicalRoute, intent ModelRequestIntent, tried map[string]bool, requirePriceTier bool) []cachedLogicalRoute {
@@ -229,7 +234,7 @@ func (s *Service) eligibleLogicalRoutes(routes []cachedLogicalRoute, intent Mode
if match := MatchCapability(route.CapabilitySpec, intent); !match.Matched {
continue
}
if requirePriceTier && channelModelPriceTierForIntent(route.ChannelModel, intent) == nil {
if requirePriceTier && channelModelPriceTierForIntent(route.ChannelModel, intent, route.CapabilitySpec) == nil {
continue
}
if route.Route.Priority > maxPriority {
@@ -254,8 +259,12 @@ func channelModelHasActivePriceTier(channelModel model.ChannelModel) bool {
// channelModelPriceTierForIntent 使用“精确规格优先、通配规格兜底”的规则。SKU 选择器与
// 运行意图使用同一组规范键,因而图片质量/画幅、视频分辨率/时长和生成操作都能独立定价。
func channelModelPriceTierForIntent(channelModel model.ChannelModel, intent ModelRequestIntent) *model.ChannelModelPriceTier {
func channelModelPriceTierForIntent(channelModel model.ChannelModel, intent ModelRequestIntent, specs ...CapabilitySpec) *model.ChannelModelPriceTier {
selector := skuSelectorForIntent(intent)
parameters := imagePriceParametersForChannel(channelModel, specs...)
if parameters != nil {
selector = imagePriceSelectorForParameters(parameters, intent)
}
bestScore := -1
var best *model.ChannelModelPriceTier
for index := range channelModel.PriceTiers {
@@ -263,7 +272,14 @@ func channelModelPriceTierForIntent(channelModel model.ChannelModel, intent Mode
if !tier.Enabled || !tier.PriceConfigured {
continue
}
matched, score := matchSKUSelector(skuSelectorForTier(*tier), selector)
tierSelector := skuSelectorForTier(*tier)
if parameters != nil {
tierSelector = model.DecodeSKUSelector(tier.SelectorJSON)
if validateImageParameterPriceSelector(parameters, tierSelector) != nil {
continue
}
}
matched, score := matchSKUSelector(tierSelector, selector)
if !matched {
continue
}
@@ -274,6 +290,44 @@ func channelModelPriceTierForIntent(channelModel model.ChannelModel, intent Mode
return best
}
// channelModelHasCompatiblePriceTier is only for catalog discovery: an option
// omitted from the intent is still a choice, while every supplied selector
// value must be compatible with at least one active, configured tier.
func channelModelHasCompatiblePriceTier(channelModel model.ChannelModel, intent ModelRequestIntent, specs ...CapabilitySpec) bool {
requested := skuSelectorForIntent(intent)
parameters := imagePriceParametersForChannel(channelModel, specs...)
if parameters != nil {
requested = imagePriceSelectorForParameters(parameters, intent)
}
for _, tier := range channelModel.PriceTiers {
if !tier.Enabled || !tier.PriceConfigured {
continue
}
compatible := true
tierSelector := skuSelectorForTier(tier)
if parameters != nil {
tierSelector = model.DecodeSKUSelector(tier.SelectorJSON)
if validateImageParameterPriceSelector(parameters, tierSelector) != nil {
continue
}
}
for key, expected := range tierSelector {
expected = strings.TrimSpace(expected)
if expected == "" || expected == "*" {
continue
}
if actual, provided := requested[key]; provided && actual != expected {
compatible = false
break
}
}
if compatible {
return true
}
}
return false
}
func skuSelectorForIntent(intent ModelRequestIntent) map[string]string {
selector := map[string]string{}
if operation := strings.ToLower(strings.TrimSpace(intent.Operation)); operation != "" {
@@ -302,6 +356,11 @@ func skuSelectorForIntent(intent ModelRequestIntent) map[string]string {
selector["videoGenerateAudio"] = audio
}
case "image":
for name, value := range intent.Options {
if value != nil {
selector[name] = fmt.Sprint(value)
}
}
if intent.Inputs["image"] > 0 {
selector["operation"] = "image_to_image"
} else {
+27 -22
View File
@@ -148,21 +148,22 @@ func (s *Service) routedModelForTaskSelection(task *model.Task) (*RoutedModel, e
if err != nil {
return nil, err
}
capabilitySpec, err := channelModelCapabilitySpec(*channelModel, s.protocolRegistry())
if err != nil || s.logicalRouteBlocked(cachedLogicalRoute{Route: *route, CapabilitySpec: capabilitySpec, ChannelModel: *channelModel}) {
return nil, errors.New("当前模型服务暂不可用")
}
productSpec = capabilitySpecWithRoutePresets(productSpec, []CapabilitySpec{capabilitySpec})
defaults, err := decodeLogicalDefaults(revision.DefaultOptionsJSON, productSpec)
if err != nil {
return nil, err
}
capabilitySpec, err := channelModelCapabilitySpec(*channelModel)
if err != nil || s.logicalRouteBlocked(cachedLogicalRoute{Route: *route, CapabilitySpec: capabilitySpec, ChannelModel: *channelModel}) {
return nil, errors.New("当前模型服务暂不可用")
}
if logicalModel.PricePolicy == "channel" && !channelModel.PriceConfigured {
return nil, errors.New("任务使用的模型服务价格配置已失效")
}
if logicalModel.PricePolicy == "unified" && logicalModel.BillingMode == "token" && !supportsTokenBilling(logicalModel.Capability, channelModel.Protocol) {
return nil, errors.New("任务使用的模型服务不再支持当前 Token 计费配置")
}
routed := &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: *route, ChannelModel: *channelModel, Defaults: defaults}
routed := &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: *route, ChannelModel: *channelModel, CapabilitySpec: capabilitySpec, Defaults: defaults}
return routed, nil
}
@@ -187,15 +188,6 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
if err != nil {
return nil, err
}
defaults, err := decodeLogicalDefaults(revision.DefaultOptionsJSON, productSpec)
if err != nil {
return nil, err
}
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
intent.Options = mergeIntentDefaults(intent.Options, defaults)
if match := MatchCapability(productSpec, intent); !match.Matched {
return nil, BadAuthRequest("任务参数不再符合前台模型能力:" + strings.Join(match.Reasons, ";"))
}
routes, err := s.repo.LogicalModelRoutes(revision.ID, false)
if err != nil {
return nil, err
@@ -232,12 +224,21 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
if !channelOK {
continue
}
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel)
capabilitySpec, specErr := channelModelCapabilitySpec(channelModel, s.protocolRegistry())
if specErr != nil {
continue
}
candidates = append(candidates, cachedLogicalRoute{Route: route, CapabilitySpec: capabilitySpec, ChannelModel: channelModel})
}
productSpec = capabilitySpecWithRoutePresets(productSpec, enabledLogicalRouteSpecs(candidates))
defaults, err := decodeLogicalDefaults(revision.DefaultOptionsJSON, productSpec)
if err != nil {
return nil, err
}
intent := resolveModelRequestIntent(productSpec, ModelRequestIntentFromTaskInput(input, task.Type, task.Operation), defaults)
if match := MatchCapability(productSpec, intent); !match.Matched {
return nil, BadAuthRequest("任务参数不再符合前台模型能力:" + strings.Join(match.Reasons, ";"))
}
tried := make(map[string]bool, len(attempts))
for _, attempt := range attempts {
tried[attempt.RouteID] = true
@@ -249,12 +250,12 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
selected := weightedRoute(eligible)
var priceTier *model.ChannelModelPriceTier
if logicalModel.PricePolicy == "channel" {
priceTier = channelModelPriceTierForIntent(selected.ChannelModel, intent)
priceTier = channelModelPriceTierForIntent(selected.ChannelModel, intent, selected.CapabilitySpec)
if priceTier == nil {
return nil, BadAuthRequest("当前模型尚未配置所选规格的价格")
}
}
routed := &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: selected.Route, ChannelModel: selected.ChannelModel, PriceTier: priceTier, Defaults: defaults}
routed := &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: selected.Route, ChannelModel: selected.ChannelModel, CapabilitySpec: selected.CapabilitySpec, PriceTier: priceTier, Defaults: defaults, Intent: intent}
nextInput := applyRoutedProviderSelection(input, routed)
if err := s.ValidateTaskCapability(nextInput); err != nil {
return nil, err
@@ -287,7 +288,7 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
} else if task.BillingOrderID != "" {
config, _ := nextInput["config"].(map[string]any)
capability := selected.ChannelModel.Capability
snapshotCreditCost(&costOrder, channelModelPriceTierForIntent(selected.ChannelModel, intent), requestedBillingQuantity(capability, config), estimateTaskBillingTokens(nextInput, capability))
snapshotCreditCost(&costOrder, channelModelPriceTierForIntent(selected.ChannelModel, intent, selected.CapabilitySpec), requestedBillingQuantity(capability, config), estimateTaskBillingTokens(nextInput, capability))
}
if err := s.repo.SwitchTaskLogicalRoute(task.ID, previousRouteID, selected.Route.ID, string(encoded), task.BillingOrderID, selected.ChannelModel.ChannelID, selected.ChannelModel.ID, replacement, costOrder.BillingCostSnapshot); err != nil {
if errors.Is(err, repository.ErrInsufficientCredits) {
@@ -425,6 +426,11 @@ func (s *Service) resolveArchivedTaskRoute(task *model.Task, intent ModelRequest
if err != nil {
return nil, err
}
capabilitySpec, err := channelModelCapabilitySpec(*channelModel, s.protocolRegistry())
if err != nil || s.logicalRouteBlocked(cachedLogicalRoute{Route: *route, CapabilitySpec: capabilitySpec, ChannelModel: *channelModel}) {
return nil, BadAuthRequest("历史任务原模型供应线路暂不可用,无法重试")
}
productSpec = capabilitySpecWithRoutePresets(productSpec, []CapabilitySpec{capabilitySpec})
defaults, err := decodeLogicalDefaults(revision.DefaultOptionsJSON, productSpec)
if err != nil {
return nil, err
@@ -433,14 +439,13 @@ func (s *Service) resolveArchivedTaskRoute(task *model.Task, intent ModelRequest
if match := MatchCapability(productSpec, intent); !match.Matched {
return nil, BadAuthRequest("历史任务不再符合前台模型能力:" + strings.Join(match.Reasons, ";"))
}
capabilitySpec, err := channelModelCapabilitySpec(*channelModel)
if err != nil || s.logicalRouteBlocked(cachedLogicalRoute{Route: *route, CapabilitySpec: capabilitySpec, ChannelModel: *channelModel}) {
return nil, BadAuthRequest("历史任务原模型供应线路暂不可用,无法重试")
if match := MatchCapability(capabilitySpec, intent); !match.Matched {
return nil, BadAuthRequest("历史任务原供应线路不再支持这些参数:" + strings.Join(match.Reasons, ";"))
}
if logicalModel.PricePolicy == "channel" && !channelModel.PriceConfigured {
return nil, BadAuthRequest("历史任务原模型价格配置已失效,无法重试")
}
return &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: *route, ChannelModel: *channelModel, Defaults: defaults}, nil
return &RoutedModel{LogicalModel: *logicalModel, Revision: *revision, Route: *route, ChannelModel: *channelModel, CapabilitySpec: capabilitySpec, Defaults: defaults, Intent: intent}, nil
}
func (s *Service) finishTaskRouteAttempt(attempt *model.RouteAttempt, task *model.Task, taskErr error) {
+188 -27
View File
@@ -15,15 +15,10 @@ import (
"time"
"yingce/backend/internal/model"
"yingce/backend/internal/protocol"
)
type CapabilityImageSizePreset struct {
Size string `json:"size"`
Tier string `json:"tier"`
Ratio string `json:"ratio"`
Width int `json:"width"`
Height int `json:"height"`
}
type CapabilityImageSizePreset = ImageSizePreset
type CapabilityImageSize struct {
Parameter string `json:"parameter,omitempty"`
@@ -32,12 +27,13 @@ type CapabilityImageSize struct {
}
type CapabilitySpec struct {
Version int `json:"version"`
Capability string `json:"capability"`
Operations []string `json:"operations,omitempty"`
Inputs map[string]InputConstraint `json:"inputs,omitempty"`
Options map[string]OptionConstraint `json:"options,omitempty"`
ImageSize *CapabilityImageSize `json:"imageSize,omitempty"`
ImageParameters []protocol.ImageParameter `json:"imageParameters"`
Version int `json:"version"`
Capability string `json:"capability"`
Operations []string `json:"operations,omitempty"`
Inputs map[string]InputConstraint `json:"inputs,omitempty"`
Options map[string]OptionConstraint `json:"options,omitempty"`
ImageSize *CapabilityImageSize `json:"imageSize,omitempty"`
}
type InputConstraint struct {
@@ -78,18 +74,30 @@ func ModelRequestIntentFromTaskInput(input map[string]any, taskType string, oper
if options, ok := input["capabilityOptions"].(map[string]any); ok {
explicitOptions = true
for key, value := range options {
name := canonicalCapabilityOptionName(key)
// auto/any 表示调用方不指定质量;不能把它当作模型必须声明的
name := canonicalModelOptionName(capability, key)
// auto/any 表示调用方不指定质量或图片分辨率;不能把它当作模型必须声明的
// 枚举值,否则未列出 auto 的模型会被错误判定为参数不支持。
if name == "quality" {
if name == "quality" || name == "imageResolution" {
if normalized, ok := value.(string); ok && (strings.EqualFold(strings.TrimSpace(normalized), "auto") || strings.EqualFold(strings.TrimSpace(normalized), "any")) {
continue
}
}
intent.Options[name] = normalizeModelRequestOption(name, value)
if capability == "image" {
intent.Options[name] = value
} else {
intent.Options[name] = normalizeModelRequestOption(name, value)
}
}
}
if config, ok := input["config"].(map[string]any); ok && !explicitOptions {
if capability == "image" {
if parameters, ok := config["imageParameters"].(map[string]any); ok {
for name, value := range parameters {
intent.Options[name] = value
}
return intent
}
}
for key, value := range config {
switch key {
case "channelId", "apiFormat", "interfaceType", "baseUrl", "apiKey", "secretKey", "headers", "model", "capabilityConfig":
@@ -107,7 +115,7 @@ func ModelRequestIntentFromTaskInput(input map[string]any, taskType string, oper
func normalizeModelRequestOption(name string, value any) any {
canonicalName := canonicalCapabilityOptionName(name)
if canonicalName == "quality" || canonicalName == "size" {
if canonicalName == "quality" || canonicalName == "size" || canonicalName == "imageResolution" {
if text, ok := value.(string); ok {
return strings.ToLower(strings.TrimSpace(text))
}
@@ -170,12 +178,15 @@ type routeCatalogSnapshot struct {
}
type RoutedModel struct {
LogicalModel model.LogicalModel
Revision model.LogicalModelRevision
Route model.LogicalModelRoute
ChannelModel model.ChannelModel
PriceTier *model.ChannelModelPriceTier
Defaults map[string]any
LogicalModel model.LogicalModel
Revision model.LogicalModelRevision
Route model.LogicalModelRoute
ChannelModel model.ChannelModel
CapabilitySpec CapabilitySpec
PriceTier *model.ChannelModelPriceTier
Defaults map[string]any
// Intent 是已归一的公开生成意图(比例口径),与线路执行编码分离。
Intent ModelRequestIntent
}
func DecodeCapabilitySpec(raw string) (CapabilitySpec, error) {
@@ -227,7 +238,7 @@ func NormalizeCapabilitySpec(spec CapabilitySpec) (CapabilitySpec, error) {
spec.Inputs = normalizedInputs
normalizedOptions := make(map[string]OptionConstraint, len(spec.Options))
for rawName, constraint := range spec.Options {
name := canonicalCapabilityOptionName(rawName)
name := canonicalModelOptionName(spec.Capability, rawName)
if strings.TrimSpace(name) == "" {
return spec, BadAuthRequest("能力参数名称不能为空")
}
@@ -254,6 +265,11 @@ func NormalizeCapabilitySpec(spec CapabilitySpec) (CapabilitySpec, error) {
normalizedOptions[name] = constraint
}
spec.Options = normalizedOptions
if spec.Capability == "image" && spec.ImageParameters != nil {
if err := protocol.ValidateImageParameters(spec.ImageParameters); err != nil {
return spec, BadAuthRequest(err.Error())
}
}
return spec, nil
}
@@ -262,11 +278,44 @@ func decodeLogicalDefaults(raw string, spec CapabilitySpec) (map[string]any, err
if err := json.Unmarshal([]byte(raw), &defaults); err != nil {
return nil, err
}
if spec.Capability == "image" && spec.ImageParameters != nil {
current := imageParameterDefaults(spec.ImageParameters)
for _, p := range spec.ImageParameters {
if value, ok := defaults[p.Name]; ok && p.IsEnabled() && p.Accepts(imageParameterValue(p, value)) {
current[p.Name] = imageParameterValue(p, value)
}
}
defaults = current
}
return normalizeLogicalDefaults(spec, defaults)
}
func MatchCapability(spec CapabilitySpec, intent ModelRequestIntent) CapabilityMatch {
reasons := make([]string, 0)
if spec.Capability == "image" && spec.ImageParameters != nil {
values := make(map[string]any, len(intent.Options))
for name, value := range intent.Options {
values[name] = value
}
// Size may already be encoded as a pixel preset by an older client.
parameters := append([]protocol.ImageParameter(nil), spec.ImageParameters...)
for index := range parameters {
parameters[index].Required = false
}
if value, ok := values["size"]; ok && capabilityImageSizePresetMatches(spec, value, values) {
delete(values, "size")
parameters = make([]protocol.ImageParameter, 0, len(spec.ImageParameters))
for _, p := range spec.ImageParameters {
if p.Name != "size" {
p.Required = false
parameters = append(parameters, p)
}
}
}
if _, err := resolveImageParameterValues(parameters, values); err != nil {
reasons = append(reasons, err.Error())
}
}
if normalizeCapability(intent.Capability) != normalizeCapability(spec.Capability) {
reasons = append(reasons, "能力类型不匹配")
}
@@ -295,7 +344,11 @@ func MatchCapability(spec CapabilitySpec, intent ModelRequestIntent) CapabilityM
}
}
for name, value := range intent.Options {
constraint, declared := spec.Options[canonicalCapabilityOptionName(name)]
canonicalName := canonicalModelOptionName(spec.Capability, name)
if inactiveCapabilityOptionValue(canonicalName, value) {
continue
}
constraint, declared := spec.Options[canonicalName]
if !declared {
reasons = append(reasons, "不支持参数 "+capabilityOptionLabel(name))
continue
@@ -307,6 +360,105 @@ func MatchCapability(spec CapabilitySpec, intent ModelRequestIntent) CapabilityM
return CapabilityMatch{Matched: len(reasons) == 0, Reasons: reasons}
}
// Image size intent and provider encoding share explicit preset mappings.
// 公开意图按比例口径表达,线路执行编码可能是像素。两者只依据当前规格的显式 presets
// 互为别名,不做宽高数值猜测。
// resolveModelRequestIntent 产出匹配、计价与线路选择共用的唯一公开生成意图。
func resolveModelRequestIntent(spec CapabilitySpec, intent ModelRequestIntent, defaults map[string]any) ModelRequestIntent {
intent.Options = mergeIntentDefaults(intent.Options, defaults)
return normalizeImageSizeIntent(spec, intent)
}
func normalizeImageSizeIntent(spec CapabilitySpec, intent ModelRequestIntent) ModelRequestIntent {
if normalizeCapability(intent.Capability) != "image" || spec.ImageSize == nil || intent.Options == nil {
return intent
}
value, ok := intent.Options["size"].(string)
if !ok || strings.TrimSpace(value) == "" {
return intent
}
tier := stringValue(intent.Options["imageResolution"])
if _, hasIndependentResolution := spec.Options["imageResolution"]; hasIndependentResolution {
if strings.EqualFold(tier, "auto") || strings.EqualFold(tier, "any") {
tier = ""
}
if tier == "" {
return intent
}
} else if spec.ImageParameters == nil {
tier = stringValue(intent.Options["quality"])
}
preset, ok := declaredImageSizePreset(spec.ImageSize.Presets, value, tier, "")
if !ok {
return intent
}
options := make(map[string]any, len(intent.Options))
for key, option := range intent.Options {
options[key] = option
}
if spec.ImageSize.Parameter == "size" {
options["size"] = strings.TrimSpace(preset.Size)
} else {
options["size"] = normalizeDeclaredImageRatio(preset.Ratio)
}
intent.Options = options
return intent
}
// capabilityImageSizePresetMatches lets routing compare the public image-size
// intent with either route encoding. Only an explicit tier + preset mapping is
// an alias; numeric similarity is never inferred.
func capabilityImageSizePresetMatches(spec CapabilitySpec, value any, options map[string]any) bool {
size := spec.ImageSize
if size == nil || len(size.Presets) == 0 {
return false
}
text, ok := value.(string)
if !ok {
return false
}
var tier any
if spec.ImageParameters == nil {
tier = options["quality"]
}
if _, independent := spec.Options["imageResolution"]; independent {
resolution := stringValue(options["imageResolution"])
if resolution == "" || strings.EqualFold(resolution, "auto") || strings.EqualFold(resolution, "any") {
return false
}
tier = resolution
}
_, matched := declaredImageSizePreset(size.Presets, text, stringValue(tier), "")
return matched
}
// inactiveCapabilityOptionValue 判断取值是否表示“未请求该参数”。
// 空值和图片质量/分辨率的 auto/any 不构成请求;其他非空字符串、true、非零数字仍视为真实要求。
func inactiveCapabilityOptionValue(name string, value any) bool {
switch typed := value.(type) {
case nil:
return true
case bool:
return !typed
case string:
normalized := strings.TrimSpace(typed)
if normalized == "" {
return true
}
return (name == "quality" || name == "imageResolution") && (strings.EqualFold(normalized, "auto") || strings.EqualFold(normalized, "any"))
case float64:
return typed == 0
case float32:
return typed == 0
case int:
return typed == 0
case int64:
return typed == 0
}
return false
}
func capabilityInputLabel(name string) string {
switch normalizeCapabilityValue(name) {
case "image":
@@ -328,6 +480,8 @@ func capabilityOptionLabel(name string) string {
return "画面尺寸"
case "quality":
return "生成质量"
case "imageResolution":
return "图片分辨率"
case "transparentBackground":
return "透明背景"
case "count":
@@ -461,10 +615,17 @@ func canonicalCapabilityOptionName(value string) string {
}
}
func canonicalModelOptionName(capability, value string) string {
if capability == "image" {
return strings.TrimSpace(value)
}
return canonicalCapabilityOptionName(value)
}
func isCapabilityOptionFor(capability string, name string) bool {
switch normalizeCapability(capability) {
case "image":
return name == "size" || name == "quality" || name == "transparentBackground" || name == "count"
return name == "size" || name == "quality" || name == "imageResolution" || name == "transparentBackground" || name == "count"
case "video":
return name == "size" || name == "videoSeconds" || name == "vquality" || name == "videoGenerateAudio" || name == "videoWatermark"
case "audio":
@@ -26,6 +26,7 @@ type PluginProviderCatalogItem struct {
Enabled bool `json:"enabled"`
UnavailableReason string `json:"unavailableReason,omitempty"`
Parameters []protocol.Parameter `json:"parameters,omitempty"`
ImageParameters []protocol.ImageParameter `json:"imageParameters,omitempty"`
Workflows []protocol.ManifestWorkflow `json:"workflows,omitempty"`
}
@@ -42,6 +43,7 @@ func (s *Service) PluginProviderCatalog(scope, capability string, includeUnavail
}
item := PluginProviderCatalogItem{ID: provider.ID, Version: plugin.Manifest.Version, Name: provider.Label, Vendor: plugin.Manifest.Author, Categories: provider.Capabilities, Scopes: provider.Scopes, BaseURL: provider.BaseURL, Enabled: plugin.Status == "enabled", UnavailableReason: plugin.Error, Parameters: provider.Parameters, Workflows: workflowsForProvider(plugin.Manifest.Contributes.Workflows, provider.ID)}
item.Create, item.Poll, item.ContentType = operationSummary(provider.Create), operationSummaryPtr(provider.Poll), provider.Create.ContentType
item.ImageParameters = provider.ImageParameters
// The registry metadata is the canonical provider projection. This keeps
// host-backed dispatch paths out of every user-facing catalog consumer.
if adapter, ok := canonicalProviderAdapter(s.protocolRegistry(), provider.ID); ok {
@@ -180,6 +182,7 @@ func (s *Service) InstallPlugin(data []byte, fileName string) (PluginView, error
}
plugin, err := s.pluginRuntime.install(data, fileName)
if err == nil {
s.invalidateRouteCatalog()
s.refreshPaymentRegistry()
}
return plugin, err
@@ -241,6 +244,7 @@ func (s *Service) SetPluginEnabled(id string, enabled bool) (PluginView, error)
}
plugin, err := s.pluginRuntime.setEnabled(id, enabled)
if err == nil {
s.invalidateRouteCatalog()
s.refreshPaymentRegistry()
}
return plugin, err
@@ -255,6 +259,7 @@ func (s *Service) UninstallPlugin(id string) error {
}
err := s.pluginRuntime.uninstall(id)
if err == nil {
s.invalidateRouteCatalog()
s.refreshPaymentRegistry()
}
return err
+2
View File
@@ -75,6 +75,8 @@ type providerConfig struct {
Model string `json:"model"`
Size string `json:"size"`
Quality string `json:"quality"`
ImageResolution string `json:"imageResolution"`
ImageParameters map[string]any `json:"imageParameters,omitempty"`
TransparentBackground string `json:"transparentBackground"`
Count string `json:"count"`
VideoSeconds string `json:"videoSeconds"`
+1 -1
View File
@@ -306,7 +306,7 @@ func grokImageRequestBody(input canvasGenerationInput) (grokImageRequest, string
ResponseFormat: grokImageResponseFormat(input.ImageCapability),
// Grok 图片协议用 aspect_ratio 表达画布比例;同时发送 size 会被上游按 OpenAI 枚举校验并拒绝。
AspectRatio: normalizeGrokImageAspectRatio(input.Config.Size),
Resolution: normalizeGrokImageResolution(input.Config.Quality),
Resolution: normalizeGrokImageResolution(firstNonEmpty(input.Config.ImageResolution, input.Config.Quality)),
}
if len(input.ReferenceImages) == 0 {
return body, "/images/generations", nil
@@ -22,6 +22,9 @@ import (
func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRequest {
resolution := strings.TrimSpace(input.Config.VQuality)
if input.Mode == "image" {
resolution = strings.TrimSpace(input.Config.ImageResolution)
}
if input.Mode == "video" {
if declared := videoResolutionNameRequest(input.VideoCapability, resolution); declared != "" {
resolution = declared
@@ -32,19 +35,20 @@ func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRe
aspectRatio = normalizePixelSize(aspectRatio)
}
request := protocol.GenerationRequest{
Capability: protocol.Capability(input.Mode),
Model: input.Config.Model,
Prompt: input.Prompt,
Instructions: strings.TrimSpace(input.Config.SystemPrompt),
Images: protocolImageReferences(input),
Videos: protocolMediaReferences(input.ReferenceVideos, "video"),
Audios: protocolMediaReferences(input.ReferenceAudios, "audio"),
AspectRatio: aspectRatio,
Resolution: resolution,
Quality: input.Config.Quality,
GenerateAudio: parseBool(input.Config.VideoGenerateAudio, false),
Watermark: parseBool(input.Config.VideoWatermark, false),
Operation: firstNonEmpty(metadataString(input.Metadata, "videoEditOperation"), metadataString(input.Metadata, "videoOperation")),
ImageParameters: protocolImageParameterValues(input.Config.ImageParameters),
Capability: protocol.Capability(input.Mode),
Model: input.Config.Model,
Prompt: input.Prompt,
Instructions: strings.TrimSpace(input.Config.SystemPrompt),
Images: protocolImageReferences(input),
Videos: protocolMediaReferences(input.ReferenceVideos, "video"),
Audios: protocolMediaReferences(input.ReferenceAudios, "audio"),
AspectRatio: aspectRatio,
Resolution: resolution,
Quality: input.Config.Quality,
GenerateAudio: parseBool(input.Config.VideoGenerateAudio, false),
Watermark: parseBool(input.Config.VideoWatermark, false),
Operation: firstNonEmpty(metadataString(input.Metadata, "videoEditOperation"), metadataString(input.Metadata, "videoOperation")),
Extra: map[string]any{
"videoSeconds": input.Config.VideoSeconds,
"audioVoice": input.Config.AudioVoice,
@@ -84,7 +88,7 @@ func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRe
Watermark: request.Watermark, Format: input.Config.AudioFormat,
}
request.ProviderOptions = make(map[string]map[string]any)
if configured, ok := input.Metadata["providerOptions"].(map[string]any); ok {
if configured, ok := input.Metadata["providerOptions"].(map[string]any); ok && input.Config.ImageParameters == nil {
for namespace, raw := range configured {
if options, ok := raw.(map[string]any); ok {
request.ProviderOptions[strings.TrimSpace(namespace)] = options
@@ -102,6 +106,22 @@ func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRe
return request
}
func protocolImageParameterValues(values map[string]any) map[string]any {
if values == nil {
return nil
}
result := make(map[string]any, len(values))
for name, value := range values {
// These fields are already encoded from the same validated intent. In
// particular size must retain the route's explicit pixel conversion.
if name == "size" {
continue
}
result[name] = value
}
return result
}
func protocolImageReferences(input canvasGenerationInput) []protocol.MediaReference {
if input.Mode == "video" {
return protocolVideoImageReferences(input)
+22 -5
View File
@@ -205,10 +205,17 @@ func (s *Service) validateResolvedImageCapability(input *canvasGenerationInput)
fallback := DefaultImageCapabilityConfig(input.Config.InterfaceType, input.Config.Model)
channelID := strings.TrimSpace(input.Config.ChannelID)
if channelID == "" {
if input.Config.CapabilityConfig != nil && input.Config.CapabilityConfig.Image != nil {
input.ImageCapability = input.Config.CapabilityConfig.Image
} else {
input.ImageCapability = fallback
profile := input.Config.CapabilityConfig
if profile == nil || profile.Image == nil {
profile = &ModelCapabilityConfig{Version: 1, Image: fallback}
}
normalized, err := NormalizeModelCapabilityConfigForModel("image", input.Config.InterfaceType, input.Config.Model, profile, s.protocolRegistry())
if err != nil {
return err
}
input.ImageCapability = normalized.Image
if err := applyImageParameterValues(&input.Config, input.ImageCapability); err != nil {
return err
}
return validateImageTask(input.ImageCapability, *input)
}
@@ -216,7 +223,7 @@ func (s *Service) validateResolvedImageCapability(input *canvasGenerationInput)
if err != nil {
return errors.New("当前系统渠道模型未配置或已停用")
}
profile, err := DecodeModelCapabilityConfig(item.CapabilityConfigJSON)
profile, err := normalizedChannelModelCapability(item, s.protocolRegistry())
if err != nil {
return errors.New("当前图片模型能力参数无效")
}
@@ -225,6 +232,16 @@ func (s *Service) validateResolvedImageCapability(input *canvasGenerationInput)
} else {
input.ImageCapability = fallback
}
// 与任务输入边界同一套补齐/失败关闭规则:旧线路没有换算表时先按声明补齐,补不齐再报错。
if input.ImageCapability.Parameters == nil {
fillMissingImageSizePresets(input.ImageCapability, input.Config.InterfaceType)
}
if presetErr := imageSizePresetReadyError(input.ImageCapability, input.Config.InterfaceType); presetErr != nil {
return presetErr
}
if err := applyImageParameterValues(&input.Config, input.ImageCapability); err != nil {
return err
}
return validateImageTask(input.ImageCapability, *input)
}
+112 -11
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"strings"
"yingce/backend/internal/model"
@@ -245,6 +246,9 @@ func (s *Service) resolveTaskModelSelection(input map[string]any, logicalModelID
if err != nil {
return nil, input, err
}
if normalizeCapability(routed.Intent.Capability) == "image" && routed.Intent.Options != nil {
input["capabilityOptions"] = maps.Clone(routed.Intent.Options)
}
return routed, applyRoutedProviderSelection(input, routed), nil
}
@@ -275,7 +279,10 @@ func applyRoutedProviderSelection(input map[string]any, routed *RoutedModel) map
}
}
for key, value := range routed.Defaults {
canonical := canonicalCapabilityOptionName(key)
canonical := canonicalModelOptionName(routed.Intent.Capability, key)
if !isProviderCapabilityOption(canonical) {
continue
}
if existing, exists := nextConfig[canonical]; !exists || existing == nil || strings.TrimSpace(fmt.Sprint(existing)) == "" {
nextConfig[canonical] = providerConfigOptionValue(value)
}
@@ -283,7 +290,7 @@ func applyRoutedProviderSelection(input map[string]any, routed *RoutedModel) map
// 路由匹配和真实请求必须使用同一组参数;逻辑能力参数覆盖空的页面配置,但不携带供应链字段。
if options, ok := input["capabilityOptions"].(map[string]any); ok {
for key, value := range options {
canonical := canonicalCapabilityOptionName(key)
canonical := canonicalModelOptionName(routed.Intent.Capability, key)
if isProviderCapabilityOption(canonical) {
nextConfig[canonical] = providerConfigOptionValue(value)
}
@@ -292,12 +299,25 @@ func applyRoutedProviderSelection(input map[string]any, routed *RoutedModel) map
nextConfig["channelId"] = routed.ChannelModel.ChannelID
nextConfig["model"] = routed.ChannelModel.ModelKey
nextConfig["channelModelKey"] = routed.ChannelModel.ModelKey
// 协议必须以服务端记录为唯一权威:受管逻辑模型流程的客户端只表达创作参数,不携带
// interfaceType;缺失会让依赖协议的尺寸换算(比例 → 像素)静默跳过,把 16:9 这类比例
// 原样发给只认 WIDTHxHEIGHT 的上游(OpenAI Images 直接拒绝)。
nextConfig["interfaceType"] = string(routed.ChannelModel.Protocol)
providerModelKey := routed.ChannelModel.ProviderModelKey
if routed.PriceTier != nil {
nextConfig["priceTierId"] = routed.PriceTier.ID
providerModelKey = firstNonEmpty(routed.PriceTier.ProviderModelKey, providerModelKey)
}
nextConfig["providerModelKey"] = firstNonEmpty(providerModelKey, routed.ChannelModel.ModelKey)
if routed.Intent.Capability == "image" && routed.CapabilitySpec.ImageParameters != nil {
nextConfig["imageParameters"] = maps.Clone(routed.Intent.Options)
for _, key := range []string{"size", "quality", "imageResolution", "transparentBackground", "count"} {
delete(nextConfig, key)
if value, exists := routed.Intent.Options[key]; exists {
nextConfig[key] = providerConfigOptionValue(value)
}
}
}
input["config"] = nextConfig
return input
}
@@ -326,6 +346,15 @@ func normalizeTaskInput(input map[string]any) (map[string]any, error) {
if err := json.Unmarshal(encoded, &normalized); err != nil {
return nil, BadAuthRequest("任务输入格式无效")
}
if config, ok := normalized["config"].(map[string]any); ok {
if encoded, ok := config["imageParameters"].(string); ok {
var parameters map[string]any
if err := json.Unmarshal([]byte(encoded), &parameters); err != nil || parameters == nil {
return nil, BadAuthRequest("图片扩展参数必须为有效对象")
}
config["imageParameters"] = parameters
}
}
if snapshot, ok := normalized["canvasSnapshot"]; ok {
normalized["canvasSnapshot"] = compactPersistedValue(snapshot)
}
@@ -460,17 +489,24 @@ func (s *Service) resolveSystemChannelModelSelection(input map[string]any, taskT
// 不能让两份客户端数据分别驱动计费与真实上游请求。
if options, ok := input["capabilityOptions"].(map[string]any); ok {
for key, value := range options {
canonical := canonicalCapabilityOptionName(key)
canonical := canonicalModelOptionName(channelModel.Capability, key)
if isCapabilityOptionFor(channelModel.Capability, canonical) {
nextConfig[canonical] = value
}
}
}
capabilityConfig, err := normalizedChannelModelCapability(channelModel)
capabilityConfig, err := normalizedChannelModelCapability(channelModel, s.protocolRegistry())
if err != nil {
return input, InvalidModelSelection("指定的模型能力配置无效,请联系管理员")
}
if legacyImageResolutionProtocol(string(channelModel.Protocol)) && capabilityConfig != nil && capabilityConfig.Image != nil && capabilityConfig.Image.Resolution.Supported {
legacyQuality := strings.ToLower(strings.TrimSpace(metadataString(nextConfig, "quality")))
if legacyQuality != "" && legacyQuality != "<nil>" && legacyQuality != "auto" && legacyQuality != "any" && !containsCapabilityString(capabilityConfig.Image.Resolution.Values, legacyQuality) {
return input, ModelCapabilityNotSupported("所选模型不支持当前图片分辨率:" + legacyQuality)
}
}
legacyImageResolutionTier := normalizeLegacyImageResolutionRequest(string(channelModel.Protocol), capabilityConfig, nextConfig)
if capabilityConfig != nil && capabilityConfig.Video != nil && capabilityConfig.Video.FixedScreenSpec != nil {
videoInput := canvasGenerationInput{Config: providerConfig{
Size: metadataString(nextConfig, "size"), VQuality: metadataString(nextConfig, "vquality"),
@@ -489,6 +525,34 @@ func (s *Service) resolveSystemChannelModelSelection(input map[string]any, taskT
capabilitySpec = &spec
}
applyChannelCapabilityDefaults(nextConfig, channelModel.Capability, capabilityConfig)
if capabilityConfig != nil && capabilityConfig.Image != nil && capabilityConfig.Image.Parameters != nil {
parameters := capabilityConfig.Image.Parameters
values := declaredImageParameterValues(nextConfig, parameters)
if explicit, ok := input["capabilityOptions"].(map[string]any); ok {
values = explicit
}
if value, ok := values["size"]; ok && capabilitySpec != nil && capabilityImageSizePresetMatches(*capabilitySpec, value, values) {
values = maps.Clone(values)
if ratio := imageSizeRatioForDeclaredPreset(capabilityConfig.Image, fmt.Sprint(value), fmt.Sprint(values["imageResolution"])); ratio != "" {
values["size"] = ratio
}
}
resolved, parameterErr := resolveImageParameterValues(parameters, values)
if parameterErr != nil {
return input, parameterErr
}
nextConfig["imageParameters"] = resolved
for _, p := range parameters {
if value, ok := resolved[p.Name]; ok && isCapabilityOptionFor("image", p.Name) {
nextConfig[p.Name] = providerConfigOptionValue(value)
}
}
for _, name := range []string{"size", "quality", "imageResolution", "transparentBackground"} {
if _, ok := resolved[name]; !ok {
delete(nextConfig, name)
}
}
}
input["config"] = nextConfig
var declaredOptions map[string]OptionConstraint
if capabilitySpec != nil {
@@ -497,6 +561,15 @@ func (s *Service) resolveSystemChannelModelSelection(input map[string]any, taskT
input["capabilityOptions"] = capabilityOptionsFromConfig(channelModel.Capability, nextConfig, declaredOptions)
intent := ModelRequestIntentFromTaskInput(input, taskType, operation)
if capabilitySpec != nil && normalizeCapability(intent.Capability) == "image" {
intent = normalizeImageSizeIntent(*capabilitySpec, intent)
input["capabilityOptions"] = maps.Clone(intent.Options)
for key, value := range intent.Options {
if isProviderCapabilityOption(key) {
nextConfig[key] = providerConfigOptionValue(value)
}
}
}
if normalizeCapability(intent.Capability) != normalizeCapability(channelModel.Capability) {
return input, ModelCapabilityNotSupported("所选模型与任务能力不匹配")
}
@@ -510,16 +583,24 @@ func (s *Service) resolveSystemChannelModelSelection(input map[string]any, taskT
}
pricingIntent := intent
if normalizeCapability(channelModel.Capability) == "image" {
if normalizeCapability(channelModel.Capability) == "image" && (capabilityConfig == nil || capabilityConfig.Image == nil || capabilityConfig.Image.Parameters == nil) {
pricingOptions := make(map[string]any, len(intent.Options)+2)
for k, v := range intent.Options {
pricingOptions[k] = v
}
rawQuality := strings.ToLower(strings.TrimSpace(fmt.Sprint(nextConfig["quality"])))
if rawQuality != "" && rawQuality != "<nil>" && rawQuality != "auto" && rawQuality != "any" {
pricingOptions["quality"] = rawQuality
} else if pricingOptions["quality"] == nil || pricingOptions["quality"] == "" || pricingOptions["quality"] == "auto" {
pricingOptions["quality"] = "1k"
if legacyImageResolutionTier != "" {
// Match pre-split price tiers without forwarding the legacy quality field upstream.
pricingOptions["quality"] = strings.ToLower(legacyImageResolutionTier)
} else if capabilityConfig == nil || capabilityConfig.Image == nil || !capabilityConfig.Image.Resolution.Supported {
if rawQuality != "" && rawQuality != "<nil>" && rawQuality != "auto" && rawQuality != "any" {
pricingOptions["quality"] = rawQuality
} else if pricingOptions["quality"] == nil || pricingOptions["quality"] == "" || pricingOptions["quality"] == "auto" {
pricingOptions["quality"] = "1k"
}
}
if rawResolution := strings.ToLower(strings.TrimSpace(fmt.Sprint(nextConfig["imageResolution"]))); rawResolution != "" && rawResolution != "<nil>" && rawResolution != "auto" {
pricingOptions["imageResolution"] = rawResolution
}
if rawSize := strings.ToLower(strings.TrimSpace(fmt.Sprint(nextConfig["size"]))); rawSize != "" && rawSize != "<nil>" && rawSize != "auto" {
pricingOptions["size"] = rawSize
@@ -527,9 +608,13 @@ func (s *Service) resolveSystemChannelModelSelection(input map[string]any, taskT
pricingIntent.Options = pricingOptions
}
priceTier := channelModelPriceTierForIntent(*channelModel, pricingIntent)
var pricingSpecs []CapabilitySpec
if capabilitySpec != nil {
pricingSpecs = append(pricingSpecs, *capabilitySpec)
}
priceTier := channelModelPriceTierForIntent(*channelModel, pricingIntent, pricingSpecs...)
if priceTier == nil {
priceTier = channelModelPriceTierForIntent(*channelModel, intent)
priceTier = channelModelPriceTierForIntent(*channelModel, intent, pricingSpecs...)
}
if priceTier == nil || !ValidatePriceTierPrice(priceTier, channelModel.Capability, channelModel.Protocol) {
return input, ModelPriceNotConfigured("指定的模型未配置当前规格的有效价格")
@@ -559,9 +644,20 @@ func applyChannelCapabilityDefaults(config map[string]any, capability string, pr
if profile == nil || profile.Image == nil {
return
}
if profile.Image.Parameters != nil {
for _, parameter := range profile.Image.Parameters {
if parameter.IsEnabled() && parameter.Default != nil && isCapabilityOptionFor("image", parameter.Name) {
setDefault(parameter.Name, parameter.Default)
}
}
return
}
if profile.Image.Size.Parameter != "none" {
setDefault("size", profile.Image.Size.Default)
}
if profile.Image.Resolution.Supported {
setDefault("imageResolution", profile.Image.Resolution.Default)
}
if profile.Image.Quality.Supported {
setDefault("quality", profile.Image.Quality.Default)
}
@@ -583,6 +679,11 @@ func applyChannelCapabilityDefaults(config map[string]any, capability string, pr
func capabilityOptionsFromConfig(capability string, config map[string]any, declared map[string]OptionConstraint) map[string]any {
options := map[string]any{}
if capability == "image" {
if parameters, ok := config["imageParameters"].(map[string]any); ok {
return maps.Clone(parameters)
}
}
for key, value := range config {
canonical := canonicalCapabilityOptionName(key)
if !isCapabilityOptionFor(capability, canonical) || value == nil || strings.TrimSpace(fmt.Sprint(value)) == "" {
+153 -17
View File
@@ -134,8 +134,8 @@ func TestResolveTaskModelSelectionStillRequiresLogicalModelWithoutExplicitSystem
func TestResolveSystemChannelModelSelectionRebuildsAuthoritativeExecutionSpec(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceGrokImage), "grok-image")
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceGrokImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("tier-1k", `{"operation":"text_to_image","quality":"1k"}`, "provider-image-1k", "fixed_request"),
newSelectionPriceTier("tier-2k", `{"operation":"text_to_image","quality":"2k"}`, "provider-image-2k", "fixed_request"),
newSelectionPriceTier("tier-1k", `{"operation":"text_to_image","imageResolution":"1k"}`, "provider-image-1k", "fixed_request"),
newSelectionPriceTier("tier-2k", `{"operation":"text_to_image","imageResolution":"2k"}`, "provider-image-2k", "fixed_request"),
})
input := map[string]any{
@@ -155,7 +155,7 @@ func TestResolveSystemChannelModelSelectionRebuildsAuthoritativeExecutionSpec(t
"capabilityConfig": map[string]any{"image": map[string]any{"maxOutputs": 99}},
},
// capabilityOptions 是创作端表达的最终规格,必须覆盖旧页面缓存到 config 的同名值。
"capabilityOptions": map[string]any{"quality": "1k", "size": "1:1"},
"capabilityOptions": map[string]any{"imageResolution": "1k", "size": "1:1"},
}
resolved, err := svc.resolveSystemChannelModelSelection(input, "canvas_image", "")
@@ -168,8 +168,8 @@ func TestResolveSystemChannelModelSelectionRebuildsAuthoritativeExecutionSpec(t
t.Fatalf("config[%q] must be removed from a system-channel request: %#v", forbidden, config[forbidden])
}
}
if got := config["quality"]; got != "1k" {
t.Fatalf("quality = %#v, want capabilityOptions value 1k", got)
if got := config["imageResolution"]; got != "1k" {
t.Fatalf("imageResolution = %#v, want capabilityOptions value 1k", got)
}
if got := config["priceTierId"]; got != "tier-1k" {
t.Fatalf("priceTierId = %#v, want server-selected tier-1k", got)
@@ -184,11 +184,60 @@ func TestResolveSystemChannelModelSelectionRebuildsAuthoritativeExecutionSpec(t
t.Fatalf("apiFormat = %#v, want openai", got)
}
options := resolved["capabilityOptions"].(map[string]any)
if options["quality"] != config["quality"] || options["size"] != config["size"] || options["count"] != config["count"] {
if options["imageResolution"] != config["imageResolution"] || options["size"] != config["size"] || providerConfigOptionValue(options["count"]) != config["count"] {
t.Fatalf("capabilityOptions and provider config diverged: options=%#v config=%#v", options, config)
}
}
func TestResolveSystemChannelModelSelectionPricesImageResolutionAndQualityIndependently(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceOpenAIImage), "gpt-image-2")
profile.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "1k"}
profile.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"high", "max"}, Default: "high"}
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceOpenAIImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("2k-max", `{"operation":"text_to_image","imageResolution":"2k","quality":"max"}`, "provider-2k-max", "fixed_request"),
})
resolved, err := svc.resolveSystemChannelModelSelection(map[string]any{
"mode": "image",
"config": map[string]any{"channelId": channel.ID, "model": channelModel.ModelKey, "imageResolution": "2k", "quality": "max", "size": "1:1"},
}, "canvas_image", "")
if err != nil {
t.Fatalf("resolveSystemChannelModelSelection() error = %v", err)
}
config := resolved["config"].(map[string]any)
if config["priceTierId"] != "2k-max" || config["imageResolution"] != "2k" || config["quality"] != "max" {
t.Fatalf("resolved request = %#v, want exact 2k-max tier and independent options", config)
}
options := resolved["capabilityOptions"].(map[string]any)
if options["imageResolution"] != "2k" || options["quality"] != "max" {
t.Fatalf("capabilityOptions = %#v, want independent imageResolution/quality", options)
}
}
func TestResolveSystemChannelModelSelectionImportsLegacyGrokResolutionWithCanonicalPrice(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceGrokImage), "grok-image")
profile.Image.Resolution = ImageResolutionConfig{}
profile.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"1k", "2k"}, Default: "2k"}
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceGrokImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("legacy-2k", `{"imageResolution":"2k"}`, "provider-2k", "fixed_request"),
})
resolved, err := svc.resolveSystemChannelModelSelection(map[string]any{
"mode": "image",
"config": map[string]any{"channelId": channel.ID, "model": channelModel.ModelKey, "quality": "2k", "size": "16:9"},
}, "canvas_image", "")
if err != nil {
t.Fatalf("legacy request was rejected: %v", err)
}
config := resolved["config"].(map[string]any)
if config["imageResolution"] != "2k" || config["quality"] != nil || config["priceTierId"] != "legacy-2k" || config["providerModelKey"] != "provider-2k" {
t.Fatalf("legacy request did not preserve its execution and pricing semantics: %#v", config)
}
if channelModel.CapabilityConfigJSON == "" || !strings.Contains(channelModel.CapabilityConfigJSON, `"quality":{"supported":true`) {
t.Fatal("fixture did not retain the persisted legacy capability JSON")
}
}
func TestResolveSystemChannelModelSelectionMatchesMiniMax768PTier(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceMiniMaxVideo), "MiniMax-H3")
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "video", model.ChannelInterfaceMiniMaxVideo, profile, []model.ChannelModelPriceTier{
@@ -221,7 +270,7 @@ func TestResolveSystemChannelModelSelectionMatchesMiniMax768PTier(t *testing.T)
func TestResolveSystemChannelModelSelectionAppliesServerDefaults(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceGrokImage), "grok-image")
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceGrokImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("tier-default", `{"operation":"text_to_image","quality":"2k"}`, "provider-image-default", "fixed_request"),
newSelectionPriceTier("tier-default", `{"operation":"text_to_image","imageResolution":"2k"}`, "provider-image-default", "fixed_request"),
})
resolved, err := svc.resolveSystemChannelModelSelection(map[string]any{
@@ -232,7 +281,7 @@ func TestResolveSystemChannelModelSelectionAppliesServerDefaults(t *testing.T) {
t.Fatalf("resolveSystemChannelModelSelection() error = %v", err)
}
config := resolved["config"].(map[string]any)
if config["size"] != "1:1" || config["quality"] != "2k" || config["count"] != "1" || config["transparentBackground"] != "false" {
if config["size"] != "1:1" || config["imageResolution"] != "2k" || config["quality"] != nil || config["count"] != "1" || config["transparentBackground"] != nil {
t.Fatalf("server defaults were not applied: %#v", config)
}
encoded, err := json.Marshal(resolved)
@@ -376,10 +425,11 @@ func newSelectionPriceTier(id string, selector string, providerModelKey string,
func TestImageResolutionPricingOnSystemChannel(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceGeminiImage), "gemini-image-model")
profile.Image.Quality = ImageQualityConfig{Supported: false, Default: "auto"}
profile.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"1k", "2k", "4k"}, Default: "1k"}
profile.Image.Size = ImageSizeConfig{
Parameter: "aspect_ratio",
Values: []string{"1:1", "16:9"},
Default: "1:1",
Default: "16:9",
Presets: []ImageSizePreset{
{Tier: "1k", Ratio: "16:9", Size: "1824x1024", Width: 1824, Height: 1024},
{Tier: "2k", Ratio: "16:9", Size: "2752x1536", Width: 2752, Height: 1536},
@@ -387,9 +437,9 @@ func TestImageResolutionPricingOnSystemChannel(t *testing.T) {
},
}
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceGeminiImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("tier-1k", `{"quality":"1k"}`, "provider-1k", "fixed_request"),
newSelectionPriceTier("tier-2k", `{"quality":"2k"}`, "provider-2k", "fixed_request"),
newSelectionPriceTier("tier-4k", `{"quality":"4k"}`, "provider-4k", "fixed_request"),
newSelectionPriceTier("tier-1k", `{"imageResolution":"1k"}`, "provider-1k", "fixed_request"),
newSelectionPriceTier("tier-2k", `{"imageResolution":"2k"}`, "provider-2k", "fixed_request"),
newSelectionPriceTier("tier-4k", `{"imageResolution":"4k"}`, "provider-4k", "fixed_request"),
})
for _, tc := range []struct {
@@ -401,17 +451,16 @@ func TestImageResolutionPricingOnSystemChannel(t *testing.T) {
{"1k specified", "1k", "16:9", "tier-1k"},
{"2k specified", "2k", "16:9", "tier-2k"},
{"4k specified", "4k", "16:9", "tier-4k"},
{"auto specified", "auto", "16:9", "tier-1k"},
{"empty specified", "", "16:9", "tier-1k"},
} {
t.Run(tc.name, func(t *testing.T) {
input := map[string]any{
"mode": "image",
"config": map[string]any{
"channelId": channel.ID,
"model": channelModel.ModelKey,
"size": tc.size,
"quality": tc.quality,
"channelId": channel.ID,
"model": channelModel.ModelKey,
"size": tc.size,
"imageResolution": tc.quality,
},
}
resolved, err := svc.resolveSystemChannelModelSelection(input, "canvas_image", "")
@@ -425,3 +474,90 @@ func TestImageResolutionPricingOnSystemChannel(t *testing.T) {
})
}
}
func TestOpenAIAspectPresetSystemChannelPersistsPixelExecutionSize(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceOpenAIImage), "gpt-image-2.5-4k")
profile.Image.Size = ImageSizeConfig{
Parameter: "aspect_ratio",
Values: []string{"1:1", "9:16"},
Default: "1:1",
Presets: []ImageSizePreset{
{Tier: "2k", Ratio: "1:1", Size: "2048x2048", Width: 2048, Height: 2048},
{Tier: "2k", Ratio: "9:16", Size: "1536x2752", Width: 1536, Height: 2752},
{Tier: "4k", Ratio: "1:1", Size: "2880x2880", Width: 2880, Height: 2880},
{Tier: "4k", Ratio: "9:16", Size: "2160x3840", Width: 2160, Height: 3840},
},
}
profile.Image.Resolution = ImageResolutionConfig{Supported: true, Values: []string{"2k", "4k"}, Default: "2k"}
profile.Image.Quality = ImageQualityConfig{Supported: false}
svc, _, channel, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceOpenAIImage, profile, []model.ChannelModelPriceTier{
newSelectionPriceTier("tier-2k", `{"imageResolution":"2k"}`, "provider-2k", "fixed_request"),
newSelectionPriceTier("tier-4k", `{"imageResolution":"4k"}`, "provider-4k", "fixed_request"),
})
input := map[string]any{
"mode": "image",
"config": map[string]any{
"channelId": channel.ID,
"model": channelModel.ModelKey,
"size": "9:16",
"imageResolution": "2k",
},
}
resolved, err := svc.resolveSystemChannelModelSelection(input, "canvas_image", "")
if err != nil {
t.Fatalf("resolve error: %v", err)
}
if err := svc.ValidateTaskCapability(resolved); err != nil {
t.Fatalf("ValidateTaskCapability() error = %v", err)
}
cfg := resolved["config"].(map[string]any)
if cfg["priceTierId"] != "tier-2k" {
t.Fatalf("priceTierId = %#v, want tier-2k", cfg["priceTierId"])
}
if cfg["size"] != "1536x2752" {
t.Fatalf("config.size = %#v, want 1536x2752", cfg["size"])
}
}
// 受管逻辑模型流程的客户端只表达创作参数:config 里没有 interfaceType。协议必须由
// 服务端路由记录回填,否则比例型 size 不会换算成像素,只认 WIDTHxHEIGHT 的上游会
// 直接拒绝(线上表现为创建成功但生成 400 失败)。
func TestRoutedLogicalImageTaskWithoutClientInterfaceTypePersistsPixelSize(t *testing.T) {
profile := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceOpenAIImage), "gpt-image-2.5-4k")
profile.Image.Size = ImageSizeConfig{
Parameter: "aspect_ratio",
Values: []string{"1:1", "9:16"},
Default: "1:1",
Presets: []ImageSizePreset{
{Tier: "2k", Ratio: "1:1", Size: "2048x2048", Width: 2048, Height: 2048},
{Tier: "2k", Ratio: "9:16", Size: "1536x2752", Width: 1536, Height: 2752},
},
}
profile.Image.Quality = ImageQualityConfig{Supported: true, Values: []string{"2k"}, Default: "2k"}
svc, _, _, channelModel := createSystemChannelSelectionFixture(t, "image", model.ChannelInterfaceOpenAIImage, profile, nil)
tier := newSelectionPriceTier("tier-2k", `{"quality":"2k"}`, "provider-2k", "fixed_request")
tier.ChannelModelID = channelModel.ID
routed := &RoutedModel{ChannelModel: channelModel, PriceTier: &tier}
input := map[string]any{
"mode": "image",
"prompt": "A simple gray circle on a white background.",
"config": map[string]any{
"channelId": channelModel.ChannelID,
"model": channelModel.ModelKey,
"size": "9:16",
"quality": "2k",
},
}
resolved := applyRoutedProviderSelection(input, routed)
cfg := resolved["config"].(map[string]any)
if cfg["interfaceType"] != string(model.ChannelInterfaceOpenAIImage) {
t.Fatalf("config.interfaceType = %#v, want %s", cfg["interfaceType"], model.ChannelInterfaceOpenAIImage)
}
if err := svc.ValidateTaskCapability(resolved); err != nil {
t.Fatalf("ValidateTaskCapability() error = %v", err)
}
if cfg["size"] != "1536x2752" {
t.Fatalf("config.size = %#v, want 1536x2752", cfg["size"])
}
}
@@ -33,6 +33,8 @@ type ModelSelection struct {
// node/task tags are the only mapping between the persisted canvas and task wire names.
type Options struct {
Size *string `json:"size,omitempty" node:"size" task:"size" modes:"image,video"`
ImageResolution *string `json:"imageResolution,omitempty" node:"imageResolution" task:"imageResolution" modes:"image"`
ImageParameters *string `json:"imageParameters,omitempty" node:"imageParameters" task:"imageParameters" modes:"image"`
Quality *string `json:"quality,omitempty" node:"quality" task:"quality" modes:"image"`
Count *int `json:"count,omitempty" node:"count" task:"count" modes:"image"`
TransparentBackground *bool `json:"transparentBackground,omitempty" node:"transparentBackground" task:"transparentBackground" modes:"image"`
@@ -124,6 +126,19 @@ func (s GenerationSpec) Validate() error {
if s.Options.Count != nil && *s.Options.Count < 1 {
return invalid("options.count", "数量必须为正整数")
}
if s.Options.ImageParameters != nil {
var parameters map[string]any
if err := json.Unmarshal([]byte(*s.Options.ImageParameters), &parameters); err != nil || parameters == nil {
return invalid("options.imageParameters", "图片参数必须为有效对象")
}
for _, value := range parameters {
switch value.(type) {
case string, bool, float64:
default:
return invalid("options.imageParameters", "图片参数仅支持文本、数字或布尔值")
}
}
}
ids := map[string]bool{}
orders := map[int]bool{}
for i, binding := range s.ReferenceBindings {
@@ -189,6 +204,15 @@ func OptionsFromTaskConfig(mode string, config map[string]any) (Options, error)
switch field.Type.Elem().Kind() {
case reflect.String:
text, ok := raw.(string)
if !ok && field.Tag.Get("task") == "imageParameters" {
if parameters, object := raw.(map[string]any); object {
encoded, err := json.Marshal(parameters)
if err != nil {
return options, invalid("options.imageParameters", "参数无法序列化")
}
text, ok = string(encoded), true
}
}
if !ok {
return options, invalid("options."+field.Tag.Get("task"), "必须是字符串")
}
@@ -219,6 +243,12 @@ func (o Options) TaskConfig() map[string]any {
result[typ.Field(i).Tag.Get("task")] = fmt.Sprint(value.Field(i).Elem().Interface())
}
}
if o.ImageParameters != nil {
var parameters map[string]any
if json.Unmarshal([]byte(*o.ImageParameters), &parameters) == nil && parameters != nil {
result["imageParameters"] = parameters
}
}
return result
}
@@ -0,0 +1,292 @@
package protocol
import (
"encoding/json"
"fmt"
"math"
"regexp"
"slices"
"strings"
)
// ImageParameter is the image input contract shared by plugins, model
// configuration and generation. Binding is interpreted only at the provider
// boundary; names and values are never inferred from a model's display name.
type ImageParameter struct {
Name string `json:"name"`
Label string `json:"label"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
Values []any `json:"values,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Step *float64 `json:"step,omitempty"`
MaxLength int `json:"maxLength,omitempty"`
Default any `json:"default,omitempty"`
Required bool `json:"required,omitempty"`
Pricing bool `json:"pricing,omitempty"`
Binding string `json:"binding,omitempty"`
Encoding string `json:"encoding,omitempty"`
Models []string `json:"models,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
}
func (p ImageParameter) IsEnabled() bool { return p.Enabled == nil || *p.Enabled }
func (p ImageParameter) AppliesTo(model string) bool {
return len(p.Models) == 0 || slices.Contains(p.Models, strings.TrimPrefix(strings.TrimSpace(model), "models/"))
}
var imageParameterName = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9_]{0,63}$`)
func ValidateImageParameters(parameters []ImageParameter) error {
seen := map[string]bool{}
bindings := map[string]bool{}
for _, p := range parameters {
if !imageParameterName.MatchString(p.Name) || seen[p.Name] || strings.TrimSpace(p.Label) == "" {
return fmt.Errorf("invalid or duplicate image parameter %q", p.Name)
}
seen[p.Name] = true
if p.Encoding != "" && (p.Binding != "aspectRatio" || p.Encoding != "pixels" && p.Encoding != "ratio") {
return fmt.Errorf("image parameter %s has invalid encoding", p.Name)
}
switch p.Type {
case "string", "number", "integer", "boolean":
default:
return fmt.Errorf("image parameter %s has unsupported type %s", p.Name, p.Type)
}
if p.Min != nil && (!finite(*p.Min) || p.Max != nil && *p.Min > *p.Max) || p.Max != nil && !finite(*p.Max) || p.Step != nil && (!finite(*p.Step) || *p.Step <= 0) || p.MaxLength < 0 {
return fmt.Errorf("image parameter %s has invalid bounds", p.Name)
}
if p.Binding != "" {
if !validImageParameterBinding(p.Binding) || bindings[p.Binding] {
return fmt.Errorf("image parameter %s has invalid or duplicate binding", p.Name)
}
bindings[p.Binding] = true
}
for _, value := range p.Values {
constraint := p
constraint.Values = nil
if !constraint.Accepts(value) {
return fmt.Errorf("image parameter %s has invalid enum value", p.Name)
}
}
if p.Default != nil && !p.Accepts(p.Default) {
return fmt.Errorf("image parameter %s default is outside its constraints", p.Name)
}
}
return nil
}
func finite(value float64) bool { return !math.IsNaN(value) && !math.IsInf(value, 0) }
func (p ImageParameter) Accepts(value any) bool {
if value == nil {
return !p.Required
}
switch p.Type {
case "string":
text, ok := value.(string)
if !ok || p.MaxLength > 0 && len([]rune(text)) > p.MaxLength {
return false
}
case "boolean":
if _, ok := value.(bool); !ok {
return false
}
case "number", "integer":
number, ok := imageParameterNumber(value)
if !ok || !finite(number) || p.Type == "integer" && math.Trunc(number) != number {
return false
}
if p.Min != nil && number < *p.Min || p.Max != nil && number > *p.Max {
return false
}
if p.Step != nil {
base := 0.0
if p.Min != nil {
base = *p.Min
}
steps := (number - base) / *p.Step
if math.Abs(steps-math.Round(steps)) > 1e-8 {
return false
}
}
default:
return false
}
if len(p.Values) == 0 {
return true
}
for _, candidate := range p.Values {
if ImageParameterValuesEqual(candidate, value) {
return true
}
}
return false
}
func imageParameterNumber(value any) (float64, bool) {
switch v := value.(type) {
case float64:
return v, true
case float32:
return float64(v), true
case int:
return float64(v), true
case int64:
return float64(v), true
case json.Number:
n, err := v.Float64()
return n, err == nil
default:
return 0, false
}
}
func ImageParameterValuesEqual(left, right any) bool {
l, lok := imageParameterNumber(left)
r, rok := imageParameterNumber(right)
if lok || rok {
return lok && rok && l == r
}
lb, _ := json.Marshal(left)
rb, _ := json.Marshal(right)
return string(lb) == string(rb)
}
func validImageParameterBinding(binding string) bool {
switch binding {
case "aspectRatio", "resolution", "quality", "imageCount", "transparentBackground":
return true
}
parts := strings.Split(binding, ".")
return len(parts) == 3 && parts[0] == "providerOptions" && validManifestIdentifier(parts[1]) && imageParameterName.MatchString(parts[2])
}
// ResolveImageParameters takes only channel-editable restrictions. Labels,
// types, pricing eligibility and bindings always come from the plugin.
func ResolveImageParameters(definitions, configured []ImageParameter, model string) ([]ImageParameter, error) {
if err := ValidateImageParameters(definitions); err != nil {
return nil, err
}
settings := map[string]ImageParameter{}
for _, p := range configured {
if _, duplicate := settings[p.Name]; duplicate {
return nil, fmt.Errorf("duplicate image parameter %s", p.Name)
}
settings[p.Name] = p
}
result := make([]ImageParameter, 0, len(definitions))
for _, definition := range definitions {
if !definition.AppliesTo(model) {
continue
}
p := definition
if setting, ok := settings[p.Name]; ok {
p.Enabled = setting.Enabled
if !p.IsEnabled() && p.Required {
return nil, fmt.Errorf("%s is required", p.Label)
}
if setting.Values != nil {
for _, value := range setting.Values {
if !definition.Accepts(value) {
return nil, fmt.Errorf("%s value exceeds plugin constraints", p.Label)
}
}
if len(setting.Values) == 0 && len(definition.Values) > 0 && p.IsEnabled() {
return nil, fmt.Errorf("%s requires supported values", p.Label)
}
p.Values = setting.Values
}
if setting.Min != nil {
if definition.Min != nil && *setting.Min < *definition.Min {
return nil, fmt.Errorf("%s minimum exceeds plugin constraints", p.Label)
}
p.Min = setting.Min
}
if setting.Max != nil {
if definition.Max != nil && *setting.Max > *definition.Max {
return nil, fmt.Errorf("%s maximum exceeds plugin constraints", p.Label)
}
p.Max = setting.Max
}
if setting.Step != nil {
if definition.Step != nil && (math.Abs(*setting.Step / *definition.Step - math.Round(*setting.Step / *definition.Step)) > 1e-8 || *setting.Step < *definition.Step) {
return nil, fmt.Errorf("%s step exceeds plugin constraints", p.Label)
}
p.Step = setting.Step
}
if definition.Step != nil && p.Min != nil {
base := 0.0
if definition.Min != nil {
base = *definition.Min
}
steps := (*p.Min - base) / *definition.Step
if math.Abs(steps-math.Round(steps)) > 1e-8 {
return nil, fmt.Errorf("%s minimum does not align with plugin step", p.Label)
}
}
p.Default = setting.Default
delete(settings, p.Name)
}
result = append(result, p)
}
for name, p := range settings {
if p.IsEnabled() {
return nil, fmt.Errorf("plugin does not declare image parameter %s for this model", name)
}
}
return result, ValidateImageParameters(result)
}
// ApplyImageParameters runs before building a request. It preserves false and
// zero, rejects undeclared values, and maps only plugin-declared destinations.
func ApplyImageParameters(request GenerationRequest, definitions []ImageParameter) (GenerationRequest, error) {
if request.Capability != CapabilityImage || request.ImageParameters == nil {
return request, nil
}
allowed := map[string]ImageParameter{}
for _, p := range definitions {
if p.AppliesTo(request.Model) {
allowed[p.Name] = p
}
}
if request.ProviderOptions == nil {
request.ProviderOptions = map[string]map[string]any{}
}
if request.Extra == nil {
request.Extra = map[string]any{}
}
for name, value := range request.ImageParameters {
p, ok := allowed[name]
if !ok || !p.Accepts(value) {
return request, fmt.Errorf("unsupported image parameter %s", name)
}
if value == nil {
continue
}
switch p.Binding {
case "aspectRatio":
request.AspectRatio = fmt.Sprint(value)
case "resolution":
request.Resolution = fmt.Sprint(value)
case "quality":
request.Quality = fmt.Sprint(value)
case "imageCount":
n, _ := imageParameterNumber(value)
request.ImageCount = int(n)
case "transparentBackground":
request.Extra["transparentBackground"] = fmt.Sprint(value)
default:
parts := strings.Split(p.Binding, ".")
if len(parts) != 3 || parts[0] != "providerOptions" {
return request, fmt.Errorf("image parameter %s has no request binding", name)
}
if request.ProviderOptions[parts[1]] == nil {
request.ProviderOptions[parts[1]] = map[string]any{}
}
request.ProviderOptions[parts[1]][parts[2]] = value
}
}
return request, nil
}
@@ -0,0 +1,67 @@
package protocol
import (
"context"
"testing"
)
func TestImageParametersPluginRequestPreservesValuesAndModelScope(t *testing.T) {
adapter := officialPackageAdapter(t, "kacang-midjourney.yingce-plugin", "kacang-midjourney")
if len(adapter.Metadata().ImageParameters) == 0 {
t.Fatal("packaged plugin is missing image parameter declarations")
}
request := GenerationRequest{Capability: CapabilityImage, Model: "mj-v8.2", Prompt: "portrait", ImageParameters: map[string]any{
"size": "1:1", "count": 1, "seed": 0, "raw": false, "chaos": 0, "stylize": 450, "mjQuality": 0.5,
}}
spec, err := adapter.BuildCreate(context.Background(), RequestContext{Request: request})
if err != nil {
t.Fatal(err)
}
body := manifestTestBody(t, spec)
for name, expected := range map[string]any{"size": "1:1", "seed": float64(0), "raw": false, "chaos": float64(0), "stylize": float64(450), "quality": 0.5} {
if body[name] != expected {
t.Fatalf("%s = %#v, want %#v", name, body[name], expected)
}
}
request.Model = "Midjourney v8.2 高速"
if _, err := adapter.BuildCreate(context.Background(), RequestContext{Request: request}); err == nil {
t.Fatal("fast model accepted unsupported stable-only parameters")
}
request.Model = "mj-v8.2"
request.ImageParameters["stylize"] = 1001
if _, err := adapter.BuildCreate(context.Background(), RequestContext{Request: request}); err == nil {
t.Fatal("out of range value accepted")
}
}
func TestImageParametersCannotExpandPluginConstraintsOrBindings(t *testing.T) {
minimum, maximum := 0.0, 100.0
definitions := []ImageParameter{{Name: "amount", Label: "Amount", Type: "number", Min: &minimum, Max: &maximum, Binding: "providerOptions.example.amount"}}
expanded := 101.0
if _, err := ResolveImageParameters(definitions, []ImageParameter{{Name: "amount", Max: &expanded}}, "model"); err == nil {
t.Fatal("channel expanded plugin bounds")
}
resolved, err := ResolveImageParameters(definitions, []ImageParameter{{Name: "amount", Binding: "providerOptions.evil.amount", Pricing: true, Default: 0}}, "model")
if err != nil {
t.Fatal(err)
}
if resolved[0].Binding != definitions[0].Binding || resolved[0].Pricing {
t.Fatalf("channel replaced trusted metadata: %#v", resolved[0])
}
if _, err := ResolveImageParameters(definitions, []ImageParameter{{Name: "invented"}}, "model"); err == nil {
t.Fatal("undeclared field accepted")
}
}
func TestImageParametersGeminiResolutionIsIndependentFromStaleQuality(t *testing.T) {
adapter := officialPackageAdapter(t, "google-gemini-image.yingce-plugin", "gemini-image")
request := GenerationRequest{Capability: CapabilityImage, Model: "image-model", Prompt: "portrait", ImageParameters: map[string]any{"imageResolution": "2k", "seed": 0}}
spec, err := adapter.BuildCreate(context.Background(), RequestContext{Request: request})
if err != nil {
t.Fatal(err)
}
config := manifestTestBody(t, spec)["generationConfig"].(map[string]any)
if config["imageConfig"].(map[string]any)["imageSize"] != "2K" || config["seed"] != float64(0) {
t.Fatalf("mapped request: %#v", config)
}
}
+12
View File
@@ -292,6 +292,17 @@ func ValidateManifest(manifest Manifest) error {
return fmt.Errorf("duplicate provider contribution %q", provider.ID)
}
providerIDs[provider.ID] = struct{}{}
if err := ValidateImageParameters(provider.ImageParameters); err != nil {
return fmt.Errorf("provider %q image parameters: %w", provider.ID, err)
}
for _, parameter := range provider.ImageParameters {
if parameter.Binding == "" {
return fmt.Errorf("provider %q image parameter %s requires a binding", provider.ID, parameter.Name)
}
if strings.HasPrefix(parameter.Binding, "providerOptions.") && !strings.HasPrefix(parameter.Binding, "providerOptions."+provider.ID+".") {
return fmt.Errorf("provider %q image parameter %s must use its own namespace", provider.ID, parameter.Name)
}
}
if len(provider.Capabilities) == 0 || len(provider.Scopes) == 0 {
return fmt.Errorf("provider contribution %q requires capabilities and scopes", provider.ID)
}
@@ -399,6 +410,7 @@ func normalizeManifestForProvider(manifest *Manifest, index int) error {
manifest.Metadata.Categories = provider.Capabilities
manifest.Metadata.Scopes = provider.Scopes
manifest.Metadata.Parameters = provider.Parameters
manifest.Metadata.ImageParameters = provider.ImageParameters
manifest.Metadata.Create = operationSummary(provider.Create)
manifest.Metadata.Poll = operationSummaryPtr(provider.Poll)
manifest.Metadata.Cancel = operationSummaryPtr(provider.Cancel)
@@ -32,10 +32,14 @@ func (a manifestAdapter) BuildCreate(_ context.Context, c RequestContext) (Reque
if len(a.manifest.Contributes.Providers) == 0 {
return RequestSpec{}, fmt.Errorf("plugin %s does not provide a provider", a.manifest.Metadata.ID)
}
if err := validateManifestRequest(a.manifest.Validations, c.Request); err != nil {
request, err := ApplyImageParameters(c.Request, a.manifest.Metadata.ImageParameters)
if err != nil {
return RequestSpec{}, err
}
return buildManifestOperation(a.manifest.Create, a.manifest.Auth, c.Request, "")
if err := validateManifestRequest(a.manifest.Validations, request); err != nil {
return RequestSpec{}, err
}
return buildManifestOperation(a.manifest.Create, a.manifest.Auth, request, "")
}
func (a manifestAdapter) BuildAgent(_ context.Context, c AgentRequestContext) (RequestSpec, error) {
+22 -19
View File
@@ -95,6 +95,7 @@ type GenerationRequest struct {
Operation string `json:"operation,omitempty"`
Output OutputOptions `json:"output,omitempty"`
ProviderOptions map[string]map[string]any `json:"providerOptions,omitempty"`
ImageParameters map[string]any `json:"imageParameters,omitempty"`
Extra map[string]any `json:"extra,omitempty"`
}
@@ -163,25 +164,26 @@ type Parameter struct {
}
type Metadata struct {
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
Vendor string `json:"vendor"`
Description string `json:"description,omitempty"`
Categories []Capability `json:"categories"`
Scopes []Surface `json:"scopes"`
Parameters []Parameter `json:"parameters,omitempty"`
Create string `json:"-"`
Poll string `json:"-"`
Cancel string `json:"-"`
ContentType string `json:"-"`
Documentation string `json:"documentation,omitempty"`
LegacyAliases []string `json:"-"`
Enabled bool `json:"enabled"`
Installable bool `json:"installable"`
Execution string `json:"-"`
RequiresPublicMediaURLs bool `json:"-"`
UnavailableReason string `json:"-"`
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
Vendor string `json:"vendor"`
Description string `json:"description,omitempty"`
Categories []Capability `json:"categories"`
Scopes []Surface `json:"scopes"`
Parameters []Parameter `json:"parameters,omitempty"`
ImageParameters []ImageParameter `json:"imageParameters,omitempty"`
Create string `json:"-"`
Poll string `json:"-"`
Cancel string `json:"-"`
ContentType string `json:"-"`
Documentation string `json:"documentation,omitempty"`
LegacyAliases []string `json:"-"`
Enabled bool `json:"enabled"`
Installable bool `json:"installable"`
Execution string `json:"-"`
RequiresPublicMediaURLs bool `json:"-"`
UnavailableReason string `json:"-"`
}
// Manifest is the single plugin contract. A plugin may contribute providers,
@@ -338,6 +340,7 @@ type ManifestProvider struct {
RequiresPublicMediaURLs bool `json:"requiresPublicMediaUrls,omitempty"`
Auth ManifestAuth `json:"auth,omitempty"`
Parameters []Parameter `json:"parameters,omitempty"`
ImageParameters []ImageParameter `json:"imageParameters,omitempty"`
Validations []ManifestValidation `json:"validations,omitempty"`
Create ManifestOperation `json:"create"`
Agent *ManifestOperation `json:"agent,omitempty"`