🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"
TypeScript
feat: 全面扩展 AI Provider 配置 + 新增 audio/lipsync 服务类型
Connor483316ce638f
diff --git a/api/handlers/ai_config.go b/api/handlers/ai_config.goindex f1207df..88b4b1c 100644--- a/api/handlers/ai_config.go+++ b/api/handlers/ai_config.go@@ -134,3 +134,15 @@ func (h *AIConfigHandler) TestConnection(c *gin.Context) {response.Success(c, gin.H{"message": "连接测试成功"})}++func (h *AIConfigHandler) ListProviders(c *gin.Context) {+ serviceType := c.Query("service_type")++ providers, err := h.aiService.ListProviders(serviceType)+ if err != nil {+ response.InternalError(c, "获取厂商列表失败")+ return+ }++ response.Success(c, providers)+}diff --git a/api/routes/routes.go b/api/routes/routes.goindex a6294e4..0910dd6 100644--- a/api/routes/routes.go+++ b/api/routes/routes.go@@ -90,6 +90,9 @@ func SetupRouter(cfg *config.Config, db *gorm.DB, log *logger.Logger, localStoraaiConfigs.DELETE("/:id", aiConfigHandler.DeleteConfig)}+ // AI 厂商列表+ api.GET("/ai-providers", aiConfigHandler.ListProviders)+generation := api.Group("/generation"){generation.POST("/characters", scriptGenHandler.GenerateCharacters)diff --git a/application/services/ai_service.go b/application/services/ai_service.goindex 832c1d5..bbad675 100644--- a/application/services/ai_service.go+++ b/application/services/ai_service.go@@ -23,7 +23,7 @@ func NewAIService(db *gorm.DB, log *logger.Logger) *AIService {}type CreateAIConfigRequest struct {- ServiceType string `json:"service_type" binding:"required,oneof=text image video"`+ ServiceType string `json:"service_type" binding:"required,oneof=text image video audio lipsync"`Name string `json:"name" binding:"required,min=1,max=100"`Provider string `json:"provider" binding:"required"`BaseURL string `json:"base_url" binding:"required,url"`@@ -45,8 +45,8 @@ type UpdateAIConfigRequest struct {Endpoint string `json:"endpoint"`QueryEndpoint string `json:"query_endpoint"`Priority *int `json:"priority"`- IsDefault bool `json:"is_default"`- IsActive bool `json:"is_active"`+ IsDefault *bool `json:"is_default"`+ IsActive *bool `json:"is_active"`Settings string `json:"settings"`}@@ -100,6 +100,20 @@ func (s *AIService) CreateConfig(req *CreateAIConfigRequest) (*models.AIServiceCqueryEndpoint = "/generations/tasks/{taskId}"}}+ case "minimax":+ if req.ServiceType == "video" {+ endpoint = "/video_generation"+ if queryEndpoint == "" {+ queryEndpoint = "/query/video_generation"+ }+ }+ case "vidu":+ if req.ServiceType == "video" {+ endpoint = "/ent/v2/video/generation"+ if queryEndpoint == "" {+ queryEndpoint = "/ent/v2/video/generation/{taskId}"+ }+ }default:// 默认使用 OpenAI 格式if req.ServiceType == "text" {@@ -224,6 +238,21 @@ func (s *AIService) UpdateConfig(configID uint, req *UpdateAIConfigRequest) (*moupdates["endpoint"] = "/video/generations"updates["query_endpoint"] = "/video/task/{taskId}"}+ case "doubao", "volcengine", "volces":+ if serviceType == "video" {+ updates["endpoint"] = "/contents/generations/tasks"+ updates["query_endpoint"] = "/generations/tasks/{taskId}"+ }+ case "minimax":+ if serviceType == "video" {+ updates["endpoint"] = "/video_generation"+ updates["query_endpoint"] = "/query/video_generation"+ }+ case "vidu":+ if serviceType == "video" {+ updates["endpoint"] = "/ent/v2/video/generation"+ updates["query_endpoint"] = "/ent/v2/video/generation/{taskId}"+ }}} else if req.Endpoint != "" {updates["endpoint"] = req.Endpoint@@ -234,8 +263,12 @@ func (s *AIService) UpdateConfig(configID uint, req *UpdateAIConfigRequest) (*moif req.Settings != "" {updates["settings"] = req.Settings}- updates["is_default"] = req.IsDefault- updates["is_active"] = req.IsActive+ if req.IsDefault != nil {+ updates["is_default"] = *req.IsDefault+ }+ if req.IsActive != nil {+ updates["is_active"] = *req.IsActive+ }if err := tx.Model(&config).Updates(updates).Error; err != nil {tx.Rollback()@@ -433,3 +466,21 @@ func (s *AIService) GenerateImage(prompt string, size string, n int) ([]string,return client.GenerateImage(prompt, size, n)}++// ListProviders 获取 AI 厂商列表,可按 service_type 过滤+func (s *AIService) ListProviders(serviceType string) ([]models.AIServiceProvider, error) {+ var providers []models.AIServiceProvider+ query := s.db.Where("is_active = ?", true)++ if serviceType != "" {+ query = query.Where("service_type = ?", serviceType)+ }++ err := query.Order("service_type, display_name").Find(&providers).Error+ if err != nil {+ s.log.Errorw("Failed to list AI providers", "error", err)+ return nil, err+ }++ return providers, nil+}diff --git a/application/services/ai_service_test.go b/application/services/ai_service_test.gonew file mode 100644index 0000000..c22c655--- /dev/null+++ b/application/services/ai_service_test.go@@ -0,0 +1,92 @@+package services++import (+ "testing"++ "github.com/stretchr/testify/assert"+)++// TestValidServiceTypes 测试所有支持的服务类型+func TestValidServiceTypes(t *testing.T) {+ validTypes := []string{"text", "image", "video", "audio", "lipsync"}++ for _, serviceType := range validTypes {+ t.Run(serviceType, func(t *testing.T) {+ req := CreateAIConfigRequest{+ ServiceType: serviceType,+ Name: "test-config",+ Provider: "test-provider",+ BaseURL: "https://api.example.com",+ APIKey: "test-key",+ Model: []string{"test-model"},+ }++ // 验证 service type 是有效的+ assert.Contains(t, validTypes, req.ServiceType)+ })+ }+}++// TestInvalidServiceType 测试无效的服务类型+func TestInvalidServiceType(t *testing.T) {+ invalidTypes := []string{"invalid", "unknown", ""}++ for _, serviceType := range invalidTypes {+ t.Run(serviceType, func(t *testing.T) {+ req := CreateAIConfigRequest{+ ServiceType: serviceType,+ Name: "test-config",+ Provider: "test-provider",+ BaseURL: "https://api.example.com",+ APIKey: "test-key",+ Model: []string{"test-model"},+ }++ // 这些类型不应该在有效列表中+ validTypes := []string{"text", "image", "video", "audio", "lipsync"}+ assert.NotContains(t, validTypes, req.ServiceType)+ })+ }+}++// TestUpdateAIConfigRequest_BoolPointers 测试 bool 指针字段+func TestUpdateAIConfigRequest_BoolPointers(t *testing.T) {+ t.Run("nil pointers should not update", func(t *testing.T) {+ req := UpdateAIConfigRequest{+ Name: "updated-name",+ IsDefault: nil,+ IsActive: nil,+ }++ assert.Nil(t, req.IsDefault)+ assert.Nil(t, req.IsActive)+ })++ t.Run("false pointer should update to false", func(t *testing.T) {+ falseVal := false+ req := UpdateAIConfigRequest{+ Name: "updated-name",+ IsDefault: &falseVal,+ IsActive: &falseVal,+ }++ assert.NotNil(t, req.IsDefault)+ assert.NotNil(t, req.IsActive)+ assert.False(t, *req.IsDefault)+ assert.False(t, *req.IsActive)+ })++ t.Run("true pointer should update to true", func(t *testing.T) {+ trueVal := true+ req := UpdateAIConfigRequest{+ Name: "updated-name",+ IsDefault: &trueVal,+ IsActive: &trueVal,+ }++ assert.NotNil(t, req.IsDefault)+ assert.NotNil(t, req.IsActive)+ assert.True(t, *req.IsDefault)+ assert.True(t, *req.IsActive)+ })+}diff --git a/application/services/prompt_i18n.go b/application/services/prompt_i18n.goindex 3daeb26..dc0e513 100644--- a/application/services/prompt_i18n.go+++ b/application/services/prompt_i18n.go@@ -305,7 +305,7 @@ Each frame **must** follow these specific rules:- **Frame 8:** Deceleration/Follow-through- **Frame 9:** Complete conclusion/Return to stillness-**Aspect Ratio:** * %s+**Aspect Ratio:** %s**Output Specification:**@@ -321,7 +321,7 @@ You must return a **JSON object** with the following structure:"description": "Complete action sequence of a swordsman in black from drawing a blade to striking."}-`, style, imageRatio)+`, imageRatio)}return fmt.Sprintf(`**Role:** 你是一位精通视觉叙事与图像生成提示词的专家。你需要生成一个描述 3x3 九宫格动作序列的提示词。@@ -346,8 +346,8 @@ You must return a **JSON object** with the following structure:- **第8格**:动作缓冲/逐渐收势- **第9格**:完全收尾/回归静止-**Aspect Ratio:**-* %s+**Aspect Ratio:**+%s**Output Specification:**必须返回一个 **JSON 对象**,其结构如下:diff --git a/application/services/storyboard_service.go b/application/services/storyboard_service.goindex 7fdda3d..14d1e3b 100644--- a/application/services/storyboard_service.go+++ b/application/services/storyboard_service.go@@ -148,8 +148,6 @@ func (s *StoryboardService) GenerateStoryboard(episodeID string, model string) (%s%s-%s-【剧本原文】%s@@ -212,7 +210,7 @@ func (s *StoryboardService) GenerateStoryboard(episodeID string, model string) ("action": "陈峥缓缓转身,目光与身后的李芳对视,李芳手握手电筒,光束在两人之间晃动,眼神中透露疑惑和警惕","dialogue": "陈峥:\"我们被耍了,这里根本没有我们要找的东西。\" 李芳:\"现在怎么办?我们的时间不多了。\"","result": "两人站在昏暗中陷入沉思,手电筒光束照在地面形成圆形光斑,背景传来微弱的金属摩擦声,气氛紧张凝重",- "atmosphere": "低调光线·暗部占画面70%,侧面硬光勾勒人物轮廓,冷暖光对比强烈,海风吹过产生呼啸声,营造紧迫感",+ "atmosphere": "低调光线·暗部占画面70%%,侧面硬光勾勒人物轮廓,冷暖光对比强烈,海风吹过产生呼啸声,营造紧迫感","emotion": "紧张感↑↑·警惕↑↑(悬置)","duration": 7,"bgm_prompt": "紧张感逐渐升级的音效,低频持续音",diff --git a/application/services/video_merge_service.go b/application/services/video_merge_service.goindex 4fcdea6..fe5400c 100644--- a/application/services/video_merge_service.go+++ b/application/services/video_merge_service.go@@ -319,7 +319,7 @@ func (s *VideoMergeService) getVideoClient(provider string) (video.VideoClient,endpoint = "/video/generations"queryEndpoint = "/video/task/{taskId}"return video.NewChatfireClient(config.BaseURL, config.APIKey, model, endpoint, queryEndpoint), nil- case "doubao", "volces", "ark":+ case "doubao", "volces", "volcengine", "ark":endpoint = "/contents/generations/tasks"queryEndpoint = "/generations/tasks/{taskId}"return video.NewVolcesArkClient(config.BaseURL, config.APIKey, model, endpoint, queryEndpoint), nildiff --git a/domain/models/ai_config.go b/domain/models/ai_config.goindex 3236b6a..6a02831 100644--- a/domain/models/ai_config.go+++ b/domain/models/ai_config.go@@ -9,7 +9,7 @@ import (type AIServiceConfig struct {ID uint `gorm:"primaryKey;autoIncrement" json:"id"`- ServiceType string `gorm:"type:varchar(50);not null" json:"service_type"` // text, image, video+ ServiceType string `gorm:"type:varchar(50);not null" json:"service_type"` // text, image, video, audio, lipsyncProvider string `gorm:"type:varchar(50)" json:"provider"` // openai, gemini, volcengine, etc.Name string `gorm:"type:varchar(100);not null" json:"name"`BaseURL string `gorm:"type:varchar(255);not null" json:"base_url"`@@ -30,15 +30,17 @@ func (c *AIServiceConfig) TableName() string {}type AIServiceProvider struct {- ID uint `gorm:"primaryKey;autoIncrement" json:"id"`- Name string `gorm:"type:varchar(100);not null;uniqueIndex" json:"name"`- DisplayName string `gorm:"type:varchar(100);not null" json:"display_name"`- ServiceType string `gorm:"type:varchar(50);not null" json:"service_type"`- DefaultURL string `gorm:"type:varchar(255)" json:"default_url"`- Description string `gorm:"type:text" json:"description"`- IsActive bool `gorm:"default:true" json:"is_active"`- CreatedAt time.Time `gorm:"not null;autoCreateTime" json:"created_at"`- UpdatedAt time.Time `gorm:"not null;autoUpdateTime" json:"updated_at"`+ ID uint `gorm:"primaryKey;autoIncrement" json:"id"`+ Name string `gorm:"type:varchar(100);not null;uniqueIndex" json:"name"`+ DisplayName string `gorm:"type:varchar(100);not null" json:"display_name"`+ ServiceType string `gorm:"type:varchar(50);not null" json:"service_type"`+ Provider string `gorm:"type:varchar(50)" json:"provider"` // 实际 provider id(如 chatfire, gemini, volces)+ DefaultURL string `gorm:"type:varchar(255)" json:"default_url"`+ PresetModels ModelField `gorm:"type:text" json:"preset_models"` // 预设模型列表+ Description string `gorm:"type:text" json:"description"`+ IsActive bool `gorm:"default:true" json:"is_active"`+ CreatedAt time.Time `gorm:"not null;autoCreateTime" json:"created_at"`+ UpdatedAt time.Time `gorm:"not null;autoUpdateTime" json:"updated_at"`}func (p *AIServiceProvider) TableName() string {diff --git a/go.mod b/go.modindex e5826f1..4dc94f4 100644--- a/go.mod+++ b/go.mod@@ -7,12 +7,11 @@ replace github.com/drama-generator/backend => ./require (github.com/gin-gonic/gin v1.9.1github.com/google/uuid v1.6.0- github.com/robfig/cron/v3 v3.0.1github.com/spf13/viper v1.17.0+ github.com/stretchr/testify v1.9.0go.uber.org/zap v1.26.0gorm.io/datatypes v1.2.0gorm.io/driver/mysql v1.5.2- gorm.io/driver/postgres v1.5.0gorm.io/driver/sqlite v1.6.0gorm.io/gorm v1.30.0modernc.org/sqlite v1.34.4@@ -21,6 +20,7 @@ require (require (github.com/bytedance/sonic v1.9.1 // indirectgithub.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect+ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirectgithub.com/dustin/go-humanize v1.0.1 // indirectgithub.com/fsnotify/fsnotify v1.6.0 // indirectgithub.com/gabriel-vasile/mimetype v1.4.2 // indirect@@ -32,9 +32,6 @@ require (github.com/goccy/go-json v0.10.2 // indirectgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirectgithub.com/hashicorp/hcl v1.0.0 // indirect- github.com/jackc/pgpassfile v1.0.0 // indirect- github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect- github.com/jackc/pgx/v5 v5.3.0 // indirectgithub.com/jinzhu/inflection v1.0.0 // indirectgithub.com/jinzhu/now v1.1.5 // indirectgithub.com/json-iterator/go v1.1.12 // indirect@@ -48,6 +45,7 @@ require (github.com/modern-go/reflect2 v1.0.2 // indirectgithub.com/ncruces/go-strftime v0.1.9 // indirectgithub.com/pelletier/go-toml/v2 v2.1.0 // indirect+ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirectgithub.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirectgithub.com/sagikazarmark/locafero v0.3.0 // indirectgithub.com/sagikazarmark/slog-shim v0.1.0 // indirect@@ -55,7 +53,6 @@ require (github.com/spf13/afero v1.10.0 // indirectgithub.com/spf13/cast v1.5.1 // indirectgithub.com/spf13/pflag v1.0.5 // indirect- github.com/stretchr/testify v1.9.0 // indirectgithub.com/subosito/gotenv v1.6.0 // indirectgithub.com/twitchyliquid64/golang-asm v0.15.1 // indirectgithub.com/ugorji/go/codec v1.2.11 // indirect@@ -68,6 +65,7 @@ require (golang.org/x/sys v0.34.0 // indirectgolang.org/x/text v0.26.0 // indirectgoogle.golang.org/protobuf v1.31.0 // indirect+ gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirectgopkg.in/ini.v1 v1.67.0 // indirectgopkg.in/yaml.v3 v3.0.1 // indirectmodernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirectdiff --git a/go.sum b/go.sumindex aa86638..02cb853 100644--- a/go.sum+++ b/go.sum@@ -52,7 +52,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkgithub.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=@@ -171,7 +170,6 @@ github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=github.com/jackc/pgx/v5 v5.3.0 h1:/NQi8KHMpKWHInxXesC8yD4DhkXPrVhmnwYkjp9AmBA=github.com/jackc/pgx/v5 v5.3.0/go.mod h1:t3JDKnCBlYIc0ewLF0Q7B8MXmoIaBOZj/ic7iHozM/8=-github.com/jackc/puddle/v2 v2.2.0/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=@@ -187,7 +185,6 @@ github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQegithub.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=-github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=@@ -223,10 +220,7 @@ github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKHgithub.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=-github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=-github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=-github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=github.com/sagikazarmark/locafero v0.3.0 h1:zT7VEGWC2DTflmccN/5T1etyKvxSxpHsjb9cJvm4SvQ=@@ -267,7 +261,6 @@ github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9degithub.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=-github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=@@ -289,9 +282,7 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8Ugolang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=-golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=-golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=@@ -329,7 +320,6 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=-golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=@@ -364,8 +354,6 @@ golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9vgolang.org/x/net v0.0.0-20201224014010-6772e930b67b/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=-golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=-golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=@@ -387,8 +375,6 @@ golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJgolang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=-golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=@@ -426,16 +412,11 @@ golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wgolang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=-golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=-golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=-golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=@@ -444,7 +425,6 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=-golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=@@ -497,7 +477,6 @@ golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fgolang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=-golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=golang.org/x/tools v0.33.0 h1:4qz2S3zmRxbGIhDIAgjxvFutSvH5EfnsYrRBj0UI0bc=golang.org/x/tools v0.33.0/go.mod h1:CIJMaWEY88juyUfo7UbgPqbC8rU2OqfAV1h2Qp0oMYI=golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=@@ -597,8 +576,7 @@ google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hsgoogle.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=-gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=-gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=+gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=@@ -617,7 +595,6 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=gorm.io/driver/sqlserver v1.4.1 h1:t4r4r6Jam5E6ejqP7N82qAJIJAht27EGT41HyPfXRw0=gorm.io/driver/sqlserver v1.4.1/go.mod h1:DJ4P+MeZbc5rvY58PnmN1Lnyvb5gw5NPzGshHDnJLig=-gorm.io/gorm v1.24.7-0.20230306060331-85eaf9eeda11/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=gorm.io/gorm v1.25.2-0.20230530020048-26663ab9bf55/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k=gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=diff --git a/infrastructure/database/database.go b/infrastructure/database/database.goindex bac7f52..ed44e57 100644--- a/infrastructure/database/database.go+++ b/infrastructure/database/database.go@@ -70,7 +70,7 @@ func NewDatabase(cfg config.DatabaseConfig) (*gorm.DB, error) {}func AutoMigrate(db *gorm.DB) error {- return db.AutoMigrate(+ err := db.AutoMigrate(// 核心模型&models.Drama{},&models.Episode{},@@ -96,4 +96,96 @@ func AutoMigrate(db *gorm.DB) error {// 任务管理&models.AsyncTask{},)+ if err != nil {+ return err+ }++ // 初始化 AI 厂商种子数据+ return SeedProviders(db)+}++// SeedProviders 初始化 AI 厂商种子数据(幂等,按 name 匹配,存在则更新预设模型)+func SeedProviders(db *gorm.DB) error {+ providers := []models.AIServiceProvider{+ // --- 文本 ---+ {Name: "chatfire-text", DisplayName: "Chatfire", ServiceType: "text", Provider: "chatfire", DefaultURL: "https://api.chatfire.site/v1", Description: "Chatfire 聚合服务 - 文本生成", IsActive: true,+ PresetModels: models.ModelField{"gemini-3-flash-preview", "gemini-3-pro-preview", "gemini-3.1-pro-preview", "claude-sonnet-4-5-20250929", "claude-sonnet-4", "doubao-seed-1-8-251228", "doubao-seed-2-0-pro-260215"}},+ {Name: "openai-text", DisplayName: "OpenAI", ServiceType: "text", Provider: "openai", DefaultURL: "https://api.openai.com/v1", Description: "OpenAI GPT 系列", IsActive: true,+ PresetModels: models.ModelField{"gpt-5.2", "gpt-4.1", "gpt-4.1-mini"}},+ {Name: "gemini-text", DisplayName: "Google Gemini", ServiceType: "text", Provider: "gemini", DefaultURL: "https://generativelanguage.googleapis.com", Description: "Google Gemini 系列", IsActive: true,+ PresetModels: models.ModelField{"gemini-3.1-pro-preview", "gemini-3-pro-preview", "gemini-3-flash-preview", "gemini-2.5-pro", "gemini-2.5-flash"}},+ {Name: "volcengine-text", DisplayName: "火山引擎", ServiceType: "text", Provider: "volcengine", DefaultURL: "https://ark.cn-beijing.volces.com/api/v3", Description: "火山引擎豆包系列", IsActive: true,+ PresetModels: models.ModelField{"doubao-seed-2-0-pro-260215", "doubao-seed-2-0-lite-260215", "doubao-seed-2-0-mini-260215", "doubao-seed-1-8-251228", "doubao-seed-1-6-251015", "doubao-seed-1-6-lite-251015"}},+ {Name: "openrouter-text", DisplayName: "OpenRouter", ServiceType: "text", Provider: "openrouter", DefaultURL: "https://openrouter.ai/api/v1", Description: "OpenRouter 聚合服务", IsActive: true,+ PresetModels: models.ModelField{"google/gemini-3.1-pro-preview", "google/gemini-3-pro-preview", "google/gemini-3-flash-preview", "anthropic/claude-sonnet-4.5", "anthropic/claude-sonnet-4"}},+ {Name: "minimax-text", DisplayName: "MiniMax 海螺", ServiceType: "text", Provider: "minimax", DefaultURL: "https://api.minimaxi.com/v1", Description: "MiniMax 大语言模型", IsActive: true,+ PresetModels: models.ModelField{"MiniMax-M2.5", "MiniMax-M2.5-highspeed", "MiniMax-M2.1", "MiniMax-M2.1-highspeed", "MiniMax-M2", "MiniMax-M1", "MiniMax-MCP"}},++ // --- 图片 ---+ {Name: "chatfire-image", DisplayName: "Chatfire", ServiceType: "image", Provider: "chatfire", DefaultURL: "https://api.chatfire.site/v1", Description: "Chatfire 聚合服务 - 图片生成", IsActive: true,+ PresetModels: models.ModelField{"nano-banana-pro", "banana-2", "doubao-seedream-4-5-251128"}},+ {Name: "volcengine-image", DisplayName: "火山引擎", ServiceType: "image", Provider: "volcengine", DefaultURL: "https://ark.cn-beijing.volces.com/api/v3", Description: "火山引擎 Seedream 系列", IsActive: true,+ PresetModels: models.ModelField{"doubao-seedream-4-5-251128", "doubao-seedream-4-0-250828"}},+ {Name: "gemini-image", DisplayName: "Google Gemini", ServiceType: "image", Provider: "gemini", DefaultURL: "https://generativelanguage.googleapis.com", Description: "Google Gemini / Imagen 图片生成", IsActive: true,+ PresetModels: models.ModelField{"gemini-3-pro-image-preview", "gemini-3.1-flash-image-preview", "gemini-2.5-flash-image", "imagen-4.0-generate-001", "imagen-4.0-ultra-generate-001", "imagen-4.0-fast-generate-001", "gemini-3-pro-image-preview-batch"}},+ {Name: "openai-image", DisplayName: "OpenAI", ServiceType: "image", Provider: "openai", DefaultURL: "https://api.openai.com/v1", Description: "OpenAI DALL-E 系列", IsActive: true,+ PresetModels: models.ModelField{"dall-e-3", "dall-e-2"}},+ {Name: "fal-image", DisplayName: "FAL", ServiceType: "image", Provider: "fal", DefaultURL: "https://queue.fal.run", Description: "FAL 图片生成", IsActive: true,+ PresetModels: models.ModelField{"banana", "banana-2"}},++ // --- 视频 ---+ {Name: "chatfire-video", DisplayName: "Chatfire", ServiceType: "video", Provider: "chatfire", DefaultURL: "https://api.chatfire.site/v1", Description: "Chatfire 聚合服务 - 视频生成", IsActive: true,+ PresetModels: models.ModelField{"doubao-seedance-1-5-pro-251215", "doubao-seedance-2-0-260128", "doubao-seedance-1-0-pro-fast-251015", "doubao-seedance-1-0-pro-250528", "doubao-seedance-1-0-lite-i2v-250428", "doubao-seedance-1-0-lite-t2v-250428", "sora-2", "sora-2-pro", "veo-3.0-generate-001", "veo-3.0-fast-generate-001"}},+ {Name: "volces-video", DisplayName: "火山引擎", ServiceType: "video", Provider: "volces", DefaultURL: "https://ark.cn-beijing.volces.com/api/v3", Description: "火山引擎 Seedance 系列", IsActive: true,+ PresetModels: models.ModelField{"doubao-seedance-1-5-pro-251215", "doubao-seedance-2-0-260128", "doubao-seedance-1-0-pro-fast-251015", "doubao-seedance-1-0-pro-250528", "doubao-seedance-1-0-lite-i2v-250428", "doubao-seedance-1-0-lite-t2v-250428"}},+ {Name: "gemini-video", DisplayName: "Google Gemini", ServiceType: "video", Provider: "gemini", DefaultURL: "https://generativelanguage.googleapis.com", Description: "Google Veo 视频生成", IsActive: true,+ PresetModels: models.ModelField{"veo-3.1-generate-preview", "veo-3.1-fast-generate-preview", "veo-3.0-generate-001", "veo-3.0-fast-generate-001", "veo-2.0-generate-001"}},+ {Name: "minimax-video", DisplayName: "MiniMax 海螺", ServiceType: "video", Provider: "minimax", DefaultURL: "https://api.minimaxi.com/v1", Description: "MiniMax Hailuo 视频生成", IsActive: true,+ PresetModels: models.ModelField{"MiniMax-Hailuo-2.3", "MiniMax-Hailuo-2.3-Fast", "MiniMax-Hailuo-02", "t2v-01", "t2v-01-director"}},+ {Name: "openai-video", DisplayName: "OpenAI", ServiceType: "video", Provider: "openai", DefaultURL: "https://api.openai.com/v1", Description: "OpenAI Sora 视频生成", IsActive: true,+ PresetModels: models.ModelField{"sora-2", "sora-2-pro"}},+ {Name: "vidu-video", DisplayName: "生数科技 Vidu", ServiceType: "video", Provider: "vidu", DefaultURL: "https://api.vidu.com/v1", Description: "Vidu 视频生成", IsActive: true,+ PresetModels: models.ModelField{"viduq3-pro", "viduq2-pro-fast", "viduq2-pro", "viduq2-turbo", "viduq1", "viduq1-classic", "vidu2.0"}},+ {Name: "fal-video", DisplayName: "FAL", ServiceType: "video", Provider: "fal", DefaultURL: "https://queue.fal.run", Description: "FAL 视频生成 (Kling/Wan/Veo/Sora)", IsActive: true,+ PresetModels: models.ModelField{"fal-wan25", "fal-veo31", "fal-sora2", "fal-ai/kling-video/v2.5-turbo/pro/image-to-video", "fal-ai/kling-video/v3/standard/image-to-video", "fal-ai/kling-video/v3/pro/image-to-video"}},++ // --- 音频 ---+ {Name: "minimax-audio", DisplayName: "MiniMax 海螺", ServiceType: "audio", Provider: "minimax", DefaultURL: "https://api.minimaxi.com/v1", Description: "MiniMax 海螺语音合成", IsActive: true,+ PresetModels: models.ModelField{"speech-03-hd", "speech-02-hd", "speech-02-turbo"}},+ {Name: "fal-audio", DisplayName: "FAL", ServiceType: "audio", Provider: "fal", DefaultURL: "https://queue.fal.run", Description: "FAL TTS 语音合成", IsActive: true,+ PresetModels: models.ModelField{"fal-ai/index-tts-2/text-to-speech"}},+ {Name: "qwen-audio", DisplayName: "阿里百炼", ServiceType: "audio", Provider: "qwen", DefaultURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", Description: "阿里百炼 TTS", IsActive: true,+ PresetModels: models.ModelField{"cosyvoice-v2"}},++ // --- 口型同步 ---+ {Name: "fal-lipsync", DisplayName: "FAL", ServiceType: "lipsync", Provider: "fal", DefaultURL: "https://queue.fal.run", Description: "FAL Kling 口型同步", IsActive: true,+ PresetModels: models.ModelField{"fal-ai/kling-video/lipsync/audio-to-video"}},+ {Name: "vidu-lipsync", DisplayName: "生数科技 Vidu", ServiceType: "lipsync", Provider: "vidu", DefaultURL: "https://api.vidu.com/v1", Description: "Vidu 口型同步", IsActive: true,+ PresetModels: models.ModelField{"vidu-lipsync"}},+ }++ for _, p := range providers {+ var existing models.AIServiceProvider+ result := db.Where("name = ?", p.Name).First(&existing)+ if result.Error != nil {+ // 不存在,创建+ if err := db.Create(&p).Error; err != nil {+ return fmt.Errorf("failed to seed provider %s: %w", p.Name, err)+ }+ } else {+ // 已存在,更新预设模型和 provider 字段+ if err := db.Model(&existing).Updates(map[string]interface{}{+ "preset_models": p.PresetModels,+ "provider": p.Provider,+ "display_name": p.DisplayName,+ "default_url": p.DefaultURL,+ "description": p.Description,+ "is_active": true,+ }).Error; err != nil {+ return fmt.Errorf("failed to update provider %s: %w", p.Name, err)+ }+ }+ }++ return nil}diff --git a/web/package.json b/web/package.jsonindex cecd5d4..7d447eb 100644--- a/web/package.json+++ b/web/package.json@@ -11,6 +11,7 @@"preview": "vite preview","lint": "eslint .","lint:fix": "eslint . --fix",+ "lint:i18n": "node scripts/check-i18n-duplicates.js","format": "prettier --write \"src/**/*.{ts,vue,css,scss,json}\"","test": "vitest --run","test:watch": "vitest"diff --git a/web/scripts/check-i18n-duplicates.js b/web/scripts/check-i18n-duplicates.jsnew file mode 100755index 0000000..a503efa--- /dev/null+++ b/web/scripts/check-i18n-duplicates.js@@ -0,0 +1,93 @@+#!/usr/bin/env node++/**+ * 检查 i18n 文件中同一对象内的重复键+ */++import fs from 'fs';+import path from 'path';+import { fileURLToPath } from 'url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);++function checkDuplicates(filePath) {+ const content = fs.readFileSync(filePath, 'utf-8');+ const lines = content.split('\n');++ const duplicates = [];+ const stack = []; // 跟踪嵌套层级+ const keysByLevel = [new Map()]; // 每层的键映射++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const lineNum = i + 1;++ // 检测对象开始 {+ const openBrace = line.match(/\{/g);+ if (openBrace) {+ for (let j = 0; j < openBrace.length; j++) {+ stack.push(lineNum);+ keysByLevel.push(new Map());+ }+ }++ // 检测键定义+ const keyMatch = line.match(/^\s*(\w+):\s*['{]/);+ if (keyMatch) {+ const key = keyMatch[1];+ const currentLevel = keysByLevel[keysByLevel.length - 1];++ if (currentLevel.has(key)) {+ duplicates.push({+ key,+ firstLine: currentLevel.get(key),+ secondLine: lineNum+ });+ } else {+ currentLevel.set(key, lineNum);+ }+ }++ // 检测对象结束 }+ const closeBrace = line.match(/\}/g);+ if (closeBrace) {+ for (let j = 0; j < closeBrace.length; j++) {+ if (stack.length > 0) {+ stack.pop();+ keysByLevel.pop();+ }+ }+ }+ }++ return duplicates;+}++const localesDir = path.join(__dirname, '../src/locales');+const files = ['zh-CN.ts', 'en-US.ts'];++let hasErrors = false;++for (const file of files) {+ const filePath = path.join(localesDir, file);+ console.log(`\nChecking ${file}...`);++ const duplicates = checkDuplicates(filePath);++ if (duplicates.length > 0) {+ hasErrors = true;+ console.error(`❌ Found ${duplicates.length} duplicate key(s) in same object:`);+ for (const { key, firstLine, secondLine } of duplicates) {+ console.error(` - "${key}" appears on lines: ${firstLine}, ${secondLine}`);+ }+ } else {+ console.log(`✅ No duplicates found`);+ }+}++if (hasErrors) {+ process.exit(1);+}++console.log('\n✅ All i18n files are valid');diff --git a/web/src/api/ai.ts b/web/src/api/ai.tsindex 5fbaab9..35790b3 100644--- a/web/src/api/ai.ts+++ b/web/src/api/ai.ts@@ -1,5 +1,6 @@import type {AIServiceConfig,+ AIServiceProvider,AIServiceType,CreateAIConfigRequest,TestConnectionRequest,@@ -32,5 +33,11 @@ export const aiAPI = {testConnection(data: TestConnectionRequest) {return request.post('/ai-configs/test', data)- }+ },++ listProviders(serviceType?: AIServiceType) {+ return request.get<AIServiceProvider[]>('/ai-providers', {+ params: { service_type: serviceType }+ })+ },}diff --git a/web/src/components/common/AIConfigDialog.vue b/web/src/components/common/AIConfigDialog.vueindex 6cab3ed..c72c1db 100644--- a/web/src/components/common/AIConfigDialog.vue+++ b/web/src/components/common/AIConfigDialog.vue@@ -16,54 +16,21 @@<el-icon><MagicStick /></el-icon><span>一键配置火宝</span></el-button>- <el-button type="primary" size="small" @click="showCreateDialog">- <el-icon><Plus /></el-icon>- <span>{{ $t("aiConfig.addConfig") }}</span>- </el-button></div></div></template>- <!-- Tabs -->- <el-tabs- v-model="activeTab"- @tab-change="handleTabChange"- class="config-tabs"- >- <el-tab-pane :label="$t('aiConfig.tabs.text')" name="text">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="true"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- @test="handleTest"- />- </el-tab-pane>-- <el-tab-pane :label="$t('aiConfig.tabs.image')" name="image">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="false"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- />- </el-tab-pane>-- <el-tab-pane :label="$t('aiConfig.tabs.video')" name="video">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="false"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- />- </el-tab-pane>- </el-tabs>+ <!-- Provider Cards Grid -->+ <div v-loading="loading" class="dialog-provider-grid">+ <ProviderCard+ v-for="group in providerGroupsWithConfigs"+ :key="group.key"+ :provider-group="group"+ :configs="group.configs"+ :preset-models="group.presetModels"+ @refresh="loadAll"+ />+ </div><!-- Quick Setup Dialog --><el-dialog@@ -76,15 +43,9 @@<div class="quick-setup-info"><p>将自动创建以下配置:</p><ul>- <li>- <strong>文本服务</strong>: {{ providerConfigs.text[1].models[0] }}- </li>- <li>- <strong>图片服务</strong>: {{ providerConfigs.image[1].models[0] }}- </li>- <li>- <strong>视频服务</strong>: {{ providerConfigs.video[1].models[0] }}- </li>+ <li><strong>文本服务</strong>: {{ chatfireFirstModel('text') }}</li>+ <li><strong>图片服务</strong>: {{ chatfireFirstModel('image') }}</li>+ <li><strong>视频服务</strong>: {{ chatfireFirstModel('video') }}</li></ul><p class="quick-setup-tip">Base URL: https://api.chatfire.site/v1</p></div>@@ -120,698 +81,157 @@</div></template></el-dialog>-- <!-- Edit/Create Sub-Dialog -->- <el-dialog- v-model="editDialogVisible"- :title="isEdit ? $t('aiConfig.editConfig') : $t('aiConfig.addConfig')"- width="600px"- :close-on-click-modal="false"- append-to-body- >- <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">- <el-form-item :label="$t('aiConfig.form.name')" prop="name">- <el-input- v-model="form.name"- :placeholder="$t('aiConfig.form.namePlaceholder')"- />- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.provider')" prop="provider">- <el-select- v-model="form.provider"- :placeholder="$t('aiConfig.form.providerPlaceholder')"- @change="handleProviderChange"- style="width: 100%"- >- <el-option- v-for="provider in availableProviders"- :key="provider.id"- :label="provider.name"- :value="provider.id"- :disabled="provider.disabled"- />- </el-select>- <div class="form-tip">{{ $t("aiConfig.form.providerTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.priority')" prop="priority">- <el-input-number- v-model="form.priority"- :min="0"- :max="100"- :step="1"- style="width: 100%"- />- <div class="form-tip">{{ $t("aiConfig.form.priorityTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.model')" prop="model">- <el-select- v-model="form.model"- :placeholder="$t('aiConfig.form.modelPlaceholder')"- multiple- filterable- allow-create- default-first-option- collapse-tags- collapse-tags-tooltip- style="width: 100%"- >- <el-option- v-for="model in availableModels"- :key="model"- :label="model"- :value="model"- />- </el-select>- <div class="form-tip">{{ $t("aiConfig.form.modelTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.baseUrl')" prop="base_url">- <el-input- v-model="form.base_url"- :placeholder="$t('aiConfig.form.baseUrlPlaceholder')"- />- <div class="form-tip">- {{ $t("aiConfig.form.baseUrlTip") }}- <br />- {{ $t("aiConfig.form.fullEndpoint") }}: {{ fullEndpointExample }}- </div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.apiKey')" prop="api_key">- <el-input- v-model="form.api_key"- type="password"- show-password- :placeholder="$t('aiConfig.form.apiKeyPlaceholder')"- />- <div class="form-tip">{{ $t("aiConfig.form.apiKeyTip") }}</div>- </el-form-item>-- <el-form-item v-if="isEdit" :label="$t('aiConfig.form.isActive')">- <el-switch v-model="form.is_active" />- </el-form-item>- </el-form>-- <template #footer>- <div class="quick-setup-footer">- <a- href="https://api.chatfire.site/login?inviteCode=C4453345"- target="_blank"- class="register-link"- >- 没有 API Key?点击注册- </a>- <div class="footer-buttons">- <el-button @click="editDialogVisible = false">{{- $t("common.cancel")- }}</el-button>- <el-button- v-if="form.service_type === 'text'"- @click="testConnection"- :loading="testing"- >{{ $t("aiConfig.actions.test") }}</el-button- >- <el-button- type="primary"- @click="handleSubmit"- :loading="submitting"- >- {{ isEdit ? $t("common.save") : $t("common.create") }}- </el-button>- </div>- </div>- </template>- </el-dialog></el-dialog></template><script setup lang="ts">-import { ref, reactive, computed, watch } from "vue";-import {- ElMessage,- ElMessageBox,- type FormInstance,- type FormRules,-} from "element-plus";-import { Plus, MagicStick } from "@element-plus/icons-vue";-import { aiAPI } from "@/api/ai";-import type {- AIServiceConfig,- AIServiceType,- CreateAIConfigRequest,- UpdateAIConfigRequest,-} from "@/types/ai";-import ConfigList from "@/views/settings/components/ConfigList.vue";+import { ref, computed, watch } from 'vue'+import { ElMessage } from 'element-plus'+import { MagicStick } from '@element-plus/icons-vue'+import { aiAPI } from '@/api/ai'+import type { AIServiceConfig, AIServiceProvider, AIServiceType } from '@/types/ai'+import { PROVIDER_GROUPS, buildPresetModels } from '@/constants/ai-providers'+import ProviderCard from '@/views/settings/components/ProviderCard.vue'const props = defineProps<{- modelValue: boolean;-}>();+ modelValue: boolean+}>()const emit = defineEmits<{- "update:modelValue": [value: boolean];- "config-updated": [];-}>();+ 'update:modelValue': [value: boolean]+ 'config-updated': []+}>()const visible = computed({get: () => props.modelValue,- set: (val) => emit("update:modelValue", val),-});--const activeTab = ref<AIServiceType>("text");-const loading = ref(false);-const configs = ref<AIServiceConfig[]>([]);-const editDialogVisible = ref(false);-const isEdit = ref(false);-const editingId = ref<number>();-const formRef = ref<FormInstance>();-const submitting = ref(false);-const testing = ref(false);-const quickSetupVisible = ref(false);-const quickSetupApiKey = ref("");-const quickSetupLoading = ref(false);--const form = reactive<- CreateAIConfigRequest & { is_active?: boolean; provider?: string }->({- service_type: "text",- provider: "",- name: "",- base_url: "",- api_key: "",- model: [],- priority: 0,- is_active: true,-});--// Provider configs-interface ProviderConfig {- id: string;- name: string;- models: string[];- disabled?: boolean;+ set: (val) => emit('update:modelValue', val),+})++// --- State ---+const loading = ref(false)+const allConfigs = ref<AIServiceConfig[]>([])+const allProviders = ref<AIServiceProvider[]>([])+const quickSetupVisible = ref(false)+const quickSetupApiKey = ref('')+const quickSetupLoading = ref(false)++// --- Computed ---+const presetModelsMap = computed(() => buildPresetModels(allProviders.value))++const providerGroupsWithConfigs = computed(() => {+ return PROVIDER_GROUPS.map(group => {+ const configs = allConfigs.value.filter(c => group.ids.includes(c.provider || ''))+ const presetModels = presetModelsMap.value[group.key] || { text: [], image: [], video: [], audio: [], lipsync: [] }+ return { ...group, configs, presetModels }+ })+})++function chatfireFirstModel(serviceType: AIServiceType): string {+ const models = presetModelsMap.value['chatfire']?.[serviceType]+ return models?.[0] || '-'}-const providerConfigs: Record<AIServiceType, ProviderConfig[]> = {- text: [- {- id: "openai",- name: "OpenAI",- models: ["gpt-5.2", "gemini-3-flash-preview"],- },- {- id: "chatfire",- name: "Chatfire",- models: [- "gemini-3-flash-preview",- "claude-sonnet-4-5-20250929",- "doubao-seed-1-8-251228",- ],- },- {- id: "gemini",- name: "Google Gemini",- models: ["gemini-2.5-pro", "gemini-3-flash-preview"],- },- ],- image: [- {- id: "volcengine",- name: "火山引擎",- models: ["doubao-seedream-4-5-251128", "doubao-seedream-4-0-250828"],- },- {- id: "chatfire",- name: "Chatfire",- models: ["nano-banana-pro", "doubao-seedream-4-5-251128"],- },- {- id: "gemini",- name: "Google Gemini",- models: ["gemini-3-pro-image-preview"],- },- { id: "openai", name: "OpenAI", models: ["dall-e-3", "dall-e-2"] },- ],- video: [- {- id: "volces",- name: "火山引擎",- models: [- "doubao-seedance-1-5-pro-251215",- "doubao-seedance-1-0-lite-i2v-250428",- "doubao-seedance-1-0-lite-t2v-250428",- "doubao-seedance-1-0-pro-250528",- "doubao-seedance-1-0-pro-fast-251015",- ],- },- {- id: "chatfire",- name: "Chatfire",- models: [- "doubao-seedance-1-5-pro-251215",- "doubao-seedance-1-0-lite-i2v-250428",- "doubao-seedance-1-0-lite-t2v-250428",- "doubao-seedance-1-0-pro-250528",- "doubao-seedance-1-0-pro-fast-251015",- "sora-2",- "sora-2-pro",- ],- },- {- id: "minimax",- name: "MiniMax 海螺",- models: [- "MiniMax-Hailuo-2.3",- "MiniMax-Hailuo-2.3-Fast",- "MiniMax-Hailuo-02",- ],- },- { id: "openai", name: "OpenAI", models: ["sora-2", "sora-2-pro"] },- ],-};--// 当前可用的厂商列表(显示所有配置的厂商)-const availableProviders = computed(() => {- // 返回当前service_type下的所有厂商- return providerConfigs[form.service_type] || [];-});--// 当前可用的模型列表(从预定义配置中获取)-const availableModels = computed(() => {- if (!form.provider || !form.service_type) return [];-- // 从预定义配置中查找当前厂商的模型列表- const providerConfig = providerConfigs[form.service_type]?.find(- (p) => p.id === form.provider,- );-- return providerConfig?.models || [];-});--const fullEndpointExample = computed(() => {- const baseUrl = form.base_url || "https://api.example.com";- const provider = form.provider;- const serviceType = form.service_type;-- let endpoint = "";-- if (serviceType === "text") {- if (provider === "gemini" || provider === "google") {- endpoint = "/v1beta/models/{model}:generateContent";- } else {- endpoint = "/chat/completions";- }- } else if (serviceType === "image") {- if (provider === "gemini" || provider === "google") {- endpoint = "/v1beta/models/{model}:generateContent";- } else {- endpoint = "/images/generations";- }- } else if (serviceType === "video") {- if (provider === "chatfire") {- endpoint = "/video/generations";- } else if (- provider === "doubao" ||- provider === "volcengine" ||- provider === "volces"- ) {- endpoint = "/contents/generations/tasks";- } else if (provider === "minimax") {- endpoint = "/video_generation";- } else if (provider === "openai") {- endpoint = "/videos";- } else {- endpoint = "/video/generations";- }- }-- return baseUrl + endpoint;-});--const rules: FormRules = {- name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],- provider: [{ required: true, message: "请选择厂商", trigger: "change" }],- base_url: [- { required: true, message: "请输入 Base URL", trigger: "blur" },- { type: "url", message: "请输入正确的 URL 格式", trigger: "blur" },- ],- api_key: [{ required: true, message: "请输入 API Key", trigger: "blur" }],- model: [- {- required: true,- message: "请至少选择一个模型",- trigger: "change",- validator: (rule: any, value: any, callback: any) => {- if (Array.isArray(value) && value.length > 0) {- callback();- } else if (typeof value === "string" && value.length > 0) {- callback();- } else {- callback(new Error("请至少选择一个模型"));- }- },- },- ],-};--const loadConfigs = async () => {- loading.value = true;+// --- Load ---+async function loadAll() {+ loading.value = truetry {- configs.value = await aiAPI.list(activeTab.value);+ const [text, image, video, audio, lipsync, providers] = await Promise.all([+ aiAPI.list('text'),+ aiAPI.list('image'),+ aiAPI.list('video'),+ aiAPI.list('audio'),+ aiAPI.list('lipsync'),+ aiAPI.listProviders(),+ ])+ allConfigs.value = [...text, ...image, ...video, ...audio, ...lipsync]+ allProviders.value = providers+ emit('config-updated')} catch (error: any) {- ElMessage.error(error.message || "加载失败");+ ElMessage.error(error.message || '加载失败')} finally {- loading.value = false;- }-};--const generateConfigName = (- provider: string,- serviceType: AIServiceType,-): string => {- const providerNames: Record<string, string> = {- chatfire: "ChatFire",- openai: "OpenAI",- gemini: "Gemini",- google: "Google",- };-- const serviceNames: Record<AIServiceType, string> = {- text: "文本",- image: "图片",- video: "视频",- };-- const randomNum = Math.floor(Math.random() * 10000)- .toString()- .padStart(4, "0");- const providerName = providerNames[provider] || provider;- const serviceName = serviceNames[serviceType] || serviceType;-- return `${providerName}-${serviceName}-${randomNum}`;-};--const showCreateDialog = () => {- isEdit.value = false;- editingId.value = undefined;- resetForm();- form.service_type = activeTab.value;- form.provider = "chatfire";- form.base_url = "https://api.chatfire.site/v1";- form.name = generateConfigName("chatfire", activeTab.value);- // 图片模型配置默认 nano- if (activeTab.value === "image") {- form.model = ["nano-banana-pro"];+ loading.value = false}- editDialogVisible.value = true;-};--const handleEdit = (config: AIServiceConfig) => {- isEdit.value = true;- editingId.value = config.id;-- Object.assign(form, {- service_type: config.service_type,- provider: config.provider || "chatfire",- name: config.name,- base_url: config.base_url,- api_key: config.api_key,- model: Array.isArray(config.model) ? config.model : [config.model],- priority: config.priority || 0,- is_active: config.is_active,- });- editDialogVisible.value = true;-};--const handleDelete = async (config: AIServiceConfig) => {- try {- await ElMessageBox.confirm("确定要删除该配置吗?", "警告", {- confirmButtonText: "确定",- cancelButtonText: "取消",- type: "warning",- });-- await aiAPI.delete(config.id);- ElMessage.success("删除成功");- loadConfigs();- } catch (error: any) {- if (error !== "cancel") {- ElMessage.error(error.message || "删除失败");- }- }-};--const handleToggleActive = async (config: AIServiceConfig) => {- try {- const newActiveState = !config.is_active;- await aiAPI.update(config.id, { is_active: newActiveState });- ElMessage.success(newActiveState ? "已启用配置" : "已禁用配置");- await loadConfigs();- } catch (error: any) {- ElMessage.error(error.message || "操作失败");- }-};--const testConnection = async () => {- if (!formRef.value) return;-- const valid = await formRef.value.validate().catch(() => false);- if (!valid) return;-- testing.value = true;- try {- await aiAPI.testConnection({- base_url: form.base_url,- api_key: form.api_key,- model: form.model,- provider: form.provider,- });- ElMessage.success("连接测试成功!");- } catch (error: any) {- ElMessage.error(error.message || "连接测试失败");- } finally {- testing.value = false;- }-};+}-const handleTest = async (config: AIServiceConfig) => {- testing.value = true;- try {- await aiAPI.testConnection({- base_url: config.base_url,- api_key: config.api_key,- model: config.model,- provider: config.provider,- });- ElMessage.success("连接测试成功!");- } catch (error: any) {- ElMessage.error(error.message || "连接测试失败");- } finally {- testing.value = false;- }-};--const handleSubmit = async () => {- if (!formRef.value) return;-- await formRef.value.validate(async (valid) => {- if (!valid) return;-- submitting.value = true;- try {- if (isEdit.value && editingId.value) {- const updateData: UpdateAIConfigRequest = {- name: form.name,- provider: form.provider,- base_url: form.base_url,- api_key: form.api_key,- model: form.model,- priority: form.priority,- is_active: form.is_active,- };- await aiAPI.update(editingId.value, updateData);- ElMessage.success("更新成功");- } else {- await aiAPI.create(form);- ElMessage.success("创建成功");- }+// --- Quick Setup ---+function showQuickSetupDialog() {+ quickSetupApiKey.value = ''+ quickSetupVisible.value = true+}- editDialogVisible.value = false;- loadConfigs();- emit("config-updated");- } catch (error: any) {- ElMessage.error(error.message || "操作失败");- } finally {- submitting.value = false;- }- });-};--const handleTabChange = (tabName: string | number) => {- activeTab.value = tabName as AIServiceType;- loadConfigs();-};--const handleProviderChange = () => {- form.model = [];-- // 根据厂商自动设置 Base URL- if (form.provider === "gemini" || form.provider === "google") {- form.base_url = "https://generativelanguage.googleapis.com";- } else if (form.provider === "minimax") {- form.base_url = "https://api.minimaxi.com/v1";- } else if (form.provider === "volces" || form.provider === "volcengine") {- form.base_url = "https://ark.cn-beijing.volces.com/api/v3";- } else if (form.provider === "openai") {- form.base_url = "https://api.openai.com/v1";- } else {- // chatfire 和其他厂商- form.base_url = "https://api.chatfire.site/v1";+const generateConfigName = (provider: string, serviceType: AIServiceType): string => {+ const providerNames: Record<string, string> = {+ chatfire: 'ChatFire', openai: 'OpenAI', gemini: 'Gemini', google: 'Google',}+ const serviceNames: Record<AIServiceType, string> = { text: '文本', image: '图片', video: '视频', audio: '音频', lipsync: '口型同步' }+ const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0')+ return `${providerNames[provider] || provider}-${serviceNames[serviceType]}-${randomNum}`+}- if (!isEdit.value) {- form.name = generateConfigName(form.provider ?? '', form.service_type);- }-};--const resetForm = () => {- const serviceType = form.service_type || "text";- Object.assign(form, {- service_type: serviceType,- provider: "",- name: "",- base_url: "",- api_key: "",- model: [],- priority: 0,- is_active: true,- });- formRef.value?.resetFields();-};--const showQuickSetupDialog = () => {- quickSetupApiKey.value = "";- quickSetupVisible.value = true;-};--const handleQuickSetup = async () => {+async function handleQuickSetup() {if (!quickSetupApiKey.value.trim()) {- ElMessage.warning("请输入 API Key");- return;+ ElMessage.warning('请输入 API Key')+ return}- quickSetupLoading.value = true;- const baseUrl = "https://api.chatfire.site/v1";- const apiKey = quickSetupApiKey.value.trim();+ quickSetupLoading.value = true+ const baseUrl = 'https://api.chatfire.site/v1'+ const apiKey = quickSetupApiKey.value.trim()try {- // 加载所有类型的配置,检查是否已存在相同 baseUrl 的配置const [textConfigs, imageConfigs, videoConfigs] = await Promise.all([- aiAPI.list("text"),- aiAPI.list("image"),- aiAPI.list("video"),- ]);-- const createdServices: string[] = [];- const skippedServices: string[] = [];-- // 创建文本配置(如果不存在)- const existingTextConfig = textConfigs.find((c) => c.base_url === baseUrl);- if (!existingTextConfig) {- const textProvider = providerConfigs.text.find(- (p) => p.id === "chatfire",- )!;- await aiAPI.create({- service_type: "text",- provider: "chatfire",- name: generateConfigName("chatfire", "text"),- base_url: baseUrl,- api_key: apiKey,- model: [textProvider.models[0]],- priority: 0,- });- createdServices.push("文本");- } else {- skippedServices.push("文本");- }-- // 创建图片配置(如果不存在)- const existingImageConfig = imageConfigs.find(- (c) => c.base_url === baseUrl,- );- if (!existingImageConfig) {- const imageProvider = providerConfigs.image.find(- (p) => p.id === "chatfire",- )!;- await aiAPI.create({- service_type: "image",- provider: "chatfire",- name: generateConfigName("chatfire", "image"),- base_url: baseUrl,- api_key: apiKey,- model: [imageProvider.models[0]],- priority: 0,- });- createdServices.push("图片");- } else {- skippedServices.push("图片");- }-- // 创建视频配置(如果不存在)- const existingVideoConfig = videoConfigs.find(- (c) => c.base_url === baseUrl,- );- if (!existingVideoConfig) {- const videoProvider = providerConfigs.video.find(- (p) => p.id === "chatfire",- )!;- await aiAPI.create({- service_type: "video",- provider: "chatfire",- name: generateConfigName("chatfire", "video"),- base_url: baseUrl,- api_key: apiKey,- model: [videoProvider.models[0]],- priority: 0,- });- createdServices.push("视频");- } else {- skippedServices.push("视频");+ aiAPI.list('text'),+ aiAPI.list('image'),+ aiAPI.list('video'),+ ])++ const createdServices: string[] = []+ const skippedServices: string[] = []++ const types: { key: AIServiceType; label: string; configs: AIServiceConfig[] }[] = [+ { key: 'text', label: '文本', configs: textConfigs },+ { key: 'image', label: '图片', configs: imageConfigs },+ { key: 'video', label: '视频', configs: videoConfigs },+ ]++ for (const { key, label, configs } of types) {+ if (!configs.find(c => c.base_url === baseUrl)) {+ const firstModel = chatfireFirstModel(key)+ await aiAPI.create({+ service_type: key, provider: 'chatfire',+ name: generateConfigName('chatfire', key),+ base_url: baseUrl, api_key: apiKey,+ model: firstModel !== '-' ? [firstModel] : [], priority: 0,+ })+ createdServices.push(label)+ } else {+ skippedServices.push(label)+ }}- // 显示结果消息if (createdServices.length > 0 && skippedServices.length > 0) {- ElMessage.success(- `已创建 ${createdServices.join("、")} 配置,${skippedServices.join("、")} 配置已存在`,- );+ ElMessage.success(`已创建 ${createdServices.join('、')} 配置,${skippedServices.join('、')} 配置已存在`)} else if (createdServices.length > 0) {- ElMessage.success(- `一键配置成功!已创建 ${createdServices.join("、")} 服务配置`,- );+ ElMessage.success(`一键配置成功!已创建 ${createdServices.join('、')} 服务配置`)} else {- ElMessage.info("所有配置已存在,无需重复创建");+ ElMessage.info('所有配置已存在,无需重复创建')}- quickSetupVisible.value = false;- loadConfigs();- if (createdServices.length > 0) {- emit("config-updated");- }+ quickSetupVisible.value = false+ loadAll()} catch (error: any) {- ElMessage.error(error.message || "配置失败");+ ElMessage.error(error.message || '配置失败')} finally {- quickSetupLoading.value = false;+ quickSetupLoading.value = false}-};+}-// Load configs when dialog opens+// Load when dialog openswatch(visible, (val) => {if (val) {- loadConfigs();+ loadAll()}-});+})</script><style scoped>@@ -834,6 +254,32 @@ watch(visible, (val) => {gap: 8px;}+.dialog-title {+ font-size: 1.125rem;+ font-weight: 600;+ color: var(--text-primary);+}++.ai-config-dialog :deep(.el-dialog__body) {+ padding: 20px;+ max-height: 70vh;+ overflow-y: auto;+}++.dialog-provider-grid {+ display: grid;+ grid-template-columns: 1fr;+ gap: 16px;+ min-height: 200px;+}++@media (min-width: 640px) {+ .dialog-provider-grid {+ grid-template-columns: repeat(2, 1fr);+ }+}++/* Quick Setup */.quick-setup-info {margin-bottom: 16px;padding: 12px 16px;@@ -886,31 +332,6 @@ watch(visible, (val) => {gap: 8px;}-.dialog-title {- font-size: 1.125rem;- font-weight: 600;- color: var(--text-primary);-}--.ai-config-dialog :deep(.el-dialog__body) {- padding: 20px;- max-height: 60vh;- overflow-y: auto;-}--.config-tabs {- margin: 0;-}--.form-tip {- font-size: 0.75rem;- color: var(--text-muted);- margin-top: 0.25rem;- word-break: break-all;- overflow-wrap: break-word;- line-height: 1.5;-}-/* Dark mode */.dark .ai-config-dialog :deep(.el-dialog) {background: var(--bg-card);@@ -919,21 +340,4 @@ watch(visible, (val) => {.dark .ai-config-dialog :deep(.el-dialog__header) {background: var(--bg-card);}--.dark :deep(.el-form-item__label) {- color: var(--text-primary);-}--.dark :deep(.el-input__wrapper) {- background: var(--bg-secondary);- box-shadow: 0 0 0 1px var(--border-primary) inset;-}--.dark :deep(.el-input__inner) {- color: var(--text-primary);-}--.dark :deep(.el-select .el-input__wrapper) {- background: var(--bg-secondary);-}</style>diff --git a/web/src/composables/useAIModelConfig.ts b/web/src/composables/useAIModelConfig.tsindex 0d5df99..7e6baab 100644--- a/web/src/composables/useAIModelConfig.ts+++ b/web/src/composables/useAIModelConfig.ts@@ -13,11 +13,15 @@ export function useAIModelConfig() {const textConfigs = ref<AIServiceConfig[]>([])const imageConfigs = ref<AIServiceConfig[]>([])const videoConfigs = ref<AIServiceConfig[]>([])+ const audioConfigs = ref<AIServiceConfig[]>([])+ const lipsyncConfigs = ref<AIServiceConfig[]>([])const loading = ref(false)const selectedTextModel = ref('')const selectedImageModel = ref('')const selectedVideoModel = ref('')+ const selectedAudioModel = ref('')+ const selectedLipsyncModel = ref('')const textModelOptions = computed<ModelOption[]>(() =>extractModelOptions(textConfigs.value)@@ -31,6 +35,14 @@ export function useAIModelConfig() {extractModelOptions(videoConfigs.value))+ const audioModelOptions = computed<ModelOption[]>(() =>+ extractModelOptions(audioConfigs.value)+ )++ const lipsyncModelOptions = computed<ModelOption[]>(() =>+ extractModelOptions(lipsyncConfigs.value)+ )+function extractModelOptions(configs: AIServiceConfig[]): ModelOption[] {const options: ModelOption[] = []const active = configs.filter((c) => c.is_active)@@ -64,6 +76,12 @@ export function useAIModelConfig() {if (!type || type === 'video') {videoConfigs.value = await aiAPI.list('video')}+ if (!type || type === 'audio') {+ audioConfigs.value = await aiAPI.list('audio')+ }+ if (!type || type === 'lipsync') {+ lipsyncConfigs.value = await aiAPI.list('lipsync')+ }} catch (error) {console.error('Failed to load AI configs:', error)} finally {@@ -79,6 +97,8 @@ export function useAIModelConfig() {if (parsed.textModel) selectedTextModel.value = parsed.textModelif (parsed.imageModel) selectedImageModel.value = parsed.imageModelif (parsed.videoModel) selectedVideoModel.value = parsed.videoModel+ if (parsed.audioModel) selectedAudioModel.value = parsed.audioModel+ if (parsed.lipsyncModel) selectedLipsyncModel.value = parsed.lipsyncModel}} catch {// ignore parse errors@@ -89,7 +109,9 @@ export function useAIModelConfig() {localStorage.setItem(storageKey, JSON.stringify({textModel: selectedTextModel.value,imageModel: selectedImageModel.value,- videoModel: selectedVideoModel.value+ videoModel: selectedVideoModel.value,+ audioModel: selectedAudioModel.value,+ lipsyncModel: selectedLipsyncModel.value}))}@@ -97,13 +119,19 @@ export function useAIModelConfig() {textConfigs,imageConfigs,videoConfigs,+ audioConfigs,+ lipsyncConfigs,loading,selectedTextModel,selectedImageModel,selectedVideoModel,+ selectedAudioModel,+ selectedLipsyncModel,textModelOptions,imageModelOptions,videoModelOptions,+ audioModelOptions,+ lipsyncModelOptions,loadConfigs,loadSavedSelections,saveSelectionsdiff --git a/web/src/constants/ai-providers.ts b/web/src/constants/ai-providers.tsnew file mode 100644index 0000000..3562197--- /dev/null+++ b/web/src/constants/ai-providers.ts@@ -0,0 +1,66 @@+/**+ * AI Provider 配置常量与工具函数+ * 厂商和模型数据从后端 /api/v1/ai-providers 获取+ */+import type { AIServiceType, AIServiceProvider } from '@/types/ai'++export interface ProviderGroup {+ key: string+ name: string+ ids: string[] // 该分组包含的 provider id 列表+}++/** Provider 分组映射(合并同一厂商不同 provider id) */+export const PROVIDER_GROUPS: ProviderGroup[] = [+ { key: 'chatfire', name: 'Chatfire', ids: ['chatfire'] },+ { key: 'gemini', name: 'Google Gemini', ids: ['gemini', 'google'] },+ { key: 'openai', name: 'OpenAI', ids: ['openai'] },+ { key: 'volcengine', name: '火山引擎', ids: ['volcengine', 'volces'] },+ { key: 'minimax', name: 'MiniMax 海螺', ids: ['minimax'] },+ { key: 'vidu', name: '生数科技 Vidu', ids: ['vidu'] },+ { key: 'openrouter', name: 'OpenRouter', ids: ['openrouter'] },+ { key: 'fal', name: 'FAL', ids: ['fal'] },+ { key: 'qwen', name: '阿里百炼', ids: ['qwen'] },+]++/**+ * 从后端 provider 列表构建每个 group 的预设模型+ * 返回 Record<groupKey, Record<serviceType, string[]>>+ */+export function buildPresetModels(+ providers: AIServiceProvider[]+): Record<string, Record<AIServiceType, string[]>> {+ const result: Record<string, Record<AIServiceType, string[]>> = {}++ for (const group of PROVIDER_GROUPS) {+ const presetModels: Record<AIServiceType, string[]> = { text: [], image: [], video: [], audio: [], lipsync: [] }+ const types: AIServiceType[] = ['text', 'image', 'video', 'audio', 'lipsync']++ for (const t of types) {+ const models = new Set<string>()+ const matchingProviders = providers.filter(+ p => p.service_type === t && group.ids.includes(p.provider)+ )+ for (const p of matchingProviders) {+ if (p.preset_models) {+ for (const m of p.preset_models) models.add(m)+ }+ }+ presetModels[t] = Array.from(models)+ }++ result[group.key] = presetModels+ }++ return result+}++/**+ * 根据 provider id 查找所属的 group key+ */+export function getGroupKeyForProvider(providerId: string): string | undefined {+ for (const group of PROVIDER_GROUPS) {+ if (group.ids.includes(providerId)) return group.key+ }+ return undefined+}diff --git a/web/src/locales/en-US.ts b/web/src/locales/en-US.tsindex bbb839f..753296d 100644--- a/web/src/locales/en-US.ts+++ b/web/src/locales/en-US.ts@@ -111,6 +111,7 @@ export default {},aiConfig: {title: 'AI Service Configuration',+ subtitle: 'Manage AI service configurations',addConfig: 'Add Configuration',editConfig: 'Edit Configuration',back: 'Back',@@ -347,6 +348,8 @@ export default {extractTitle: 'Extract Scenes',addScene: 'Add Scene',searchPlaceholder: 'Search scene name...',+ location: 'Location',+ prompt: 'Image Prompt',emptyTip: 'No scenes yet. Extract from script or add manually'},scriptGenerationPage: {@@ -530,6 +533,7 @@ export default {clickToUpload: 'Click to Upload',prevStep: 'Previous Step',nextStepSplitShots: 'Next Step: Split Shots',+ splitStoryboardHint: 'Please generate all character and scene images first, then split storyboard',reExtractConfirmTitle: 'Re-extract Confirmation',reExtractConfirmMessage: 'Re-extraction will overwrite extracted characters and scenes (including generated images). Continue?',startReExtracting: 'Starting re-extraction, please wait...',diff --git a/web/src/locales/zh-CN.ts b/web/src/locales/zh-CN.tsindex 765252a..21e1819 100644--- a/web/src/locales/zh-CN.ts+++ b/web/src/locales/zh-CN.ts@@ -38,6 +38,7 @@ export default {create: '创建',edit: '编辑',comingSoon: '即将上线',+ error: '出错了',delete: '删除',save: '保存',cancel: '取消',@@ -107,6 +108,7 @@ export default {},aiConfig: {title: 'AI 服务配置',+ subtitle: '管理 AI 服务配置',addConfig: '添加配置',editConfig: '编辑配置',back: '返回',@@ -342,6 +344,8 @@ export default {extractComplete: '提取完成:共 {scenes} 个场景,去重 {dedup} 个',extractTitle: '提取场景',addScene: '添加场景',+ location: '地点',+ prompt: '图片提示词',searchPlaceholder: '搜索场景名称...',emptyTip: '还没有场景,从剧本提取或手动添加'},@@ -504,6 +508,7 @@ export default {reSplitConfirm: '确定要重新拂分分镜吗?',deleteCharacter: '删除角色',splitStoryboardFirst: '请先对章节进行分镜拆解',+ splitStoryboardHint: '请先生成所有角色和场景图片,然后进行分镜拆分',aiSplitting: 'AI拆分中...',aiAutoSplit: 'AI自动拆分',batchTaskSubmitted: '批量生成任务已提交!',diff --git a/web/src/stores/aiConfig.ts b/web/src/stores/aiConfig.tsindex bfa45ed..1df5100 100644--- a/web/src/stores/aiConfig.ts+++ b/web/src/stores/aiConfig.ts@@ -14,11 +14,15 @@ export const useAIConfigStore = defineStore('aiConfig', () => {const textConfigs = ref<AIServiceConfig[]>([])const imageConfigs = ref<AIServiceConfig[]>([])const videoConfigs = ref<AIServiceConfig[]>([])+ const audioConfigs = ref<AIServiceConfig[]>([])+ const lipsyncConfigs = ref<AIServiceConfig[]>([])const loading = ref(false)const selectedTextModel = ref('')const selectedImageModel = ref('')const selectedVideoModel = ref('')+ const selectedAudioModel = ref('')+ const selectedLipsyncModel = ref('')function extractModelOptions(configs: AIServiceConfig[]): ModelOption[] {const options: ModelOption[] = []@@ -44,10 +48,14 @@ export const useAIConfigStore = defineStore('aiConfig', () => {const textModelOptions = computed(() => extractModelOptions(textConfigs.value))const imageModelOptions = computed(() => extractModelOptions(imageConfigs.value))const videoModelOptions = computed(() => extractModelOptions(videoConfigs.value))+ const audioModelOptions = computed(() => extractModelOptions(audioConfigs.value))+ const lipsyncModelOptions = computed(() => extractModelOptions(lipsyncConfigs.value))const hasTextConfig = computed(() => textConfigs.value.some((c) => c.is_active))const hasImageConfig = computed(() => imageConfigs.value.some((c) => c.is_active))const hasVideoConfig = computed(() => videoConfigs.value.some((c) => c.is_active))+ const hasAudioConfig = computed(() => audioConfigs.value.some((c) => c.is_active))+ const hasLipsyncConfig = computed(() => lipsyncConfigs.value.some((c) => c.is_active))async function loadConfigs(type?: AIServiceType) {loading.value = true@@ -61,6 +69,12 @@ export const useAIConfigStore = defineStore('aiConfig', () => {if (!type || type === 'video') {videoConfigs.value = await aiAPI.list('video')}+ if (!type || type === 'audio') {+ audioConfigs.value = await aiAPI.list('audio')+ }+ if (!type || type === 'lipsync') {+ lipsyncConfigs.value = await aiAPI.list('lipsync')+ }} catch (error) {console.error('Failed to load AI configs:', error)} finally {@@ -76,6 +90,8 @@ export const useAIConfigStore = defineStore('aiConfig', () => {if (parsed.textModel) selectedTextModel.value = parsed.textModelif (parsed.imageModel) selectedImageModel.value = parsed.imageModelif (parsed.videoModel) selectedVideoModel.value = parsed.videoModel+ if (parsed.audioModel) selectedAudioModel.value = parsed.audioModel+ if (parsed.lipsyncModel) selectedLipsyncModel.value = parsed.lipsyncModel}} catch {// ignore@@ -86,7 +102,9 @@ export const useAIConfigStore = defineStore('aiConfig', () => {localStorage.setItem(storageKey, JSON.stringify({textModel: selectedTextModel.value,imageModel: selectedImageModel.value,- videoModel: selectedVideoModel.value+ videoModel: selectedVideoModel.value,+ audioModel: selectedAudioModel.value,+ lipsyncModel: selectedLipsyncModel.value}))}@@ -94,16 +112,24 @@ export const useAIConfigStore = defineStore('aiConfig', () => {textConfigs,imageConfigs,videoConfigs,+ audioConfigs,+ lipsyncConfigs,loading,selectedTextModel,selectedImageModel,selectedVideoModel,+ selectedAudioModel,+ selectedLipsyncModel,textModelOptions,imageModelOptions,videoModelOptions,+ audioModelOptions,+ lipsyncModelOptions,hasTextConfig,hasImageConfig,hasVideoConfig,+ hasAudioConfig,+ hasLipsyncConfig,loadConfigs,loadSavedSelections,saveSelectionsdiff --git a/web/src/types/ai.ts b/web/src/types/ai.tsindex 5de6168..67a3062 100644--- a/web/src/types/ai.ts+++ b/web/src/types/ai.ts@@ -15,7 +15,7 @@ export interface AIServiceConfig {updated_at: string}-export type AIServiceType = 'text' | 'image' | 'video'+export type AIServiceType = 'text' | 'image' | 'video' | 'audio' | 'lipsync'export interface CreateAIConfigRequest {service_type: AIServiceType@@ -57,7 +57,9 @@ export interface AIServiceProvider {name: stringdisplay_name: stringservice_type: AIServiceType+ provider: string // 实际 provider id(如 chatfire, gemini, volces)default_url: string+ preset_models: string[] // 预设模型列表description: stringis_active: booleancreated_at: stringdiff --git a/web/src/views/settings/AIConfig.vue b/web/src/views/settings/AIConfig.vueindex 1e4c1a2..4bc94a8 100644--- a/web/src/views/settings/AIConfig.vue+++ b/web/src/views/settings/AIConfig.vue@@ -1,663 +1,279 @@<template><div class="animate-fade-in">- <!-- Page Header / 页面头部 -->+ <!-- Page Header --><PageHeader:title="$t('aiConfig.title')":subtitle="$t('aiConfig.subtitle') || '管理 AI 服务配置'">- <template #actions>- <el-button type="primary" @click="showCreateDialog">- <el-icon><Plus /></el-icon>- <span>{{ $t("aiConfig.addConfig") }}</span>- </el-button>- </template>- </PageHeader>-- <!-- Tabs / 标签页 -->- <div class="tabs-wrapper">- <el-tabs- v-model="activeTab"- @tab-change="handleTabChange"- class="config-tabs"- >- <el-tab-pane :label="$t('aiConfig.tabs.text')" name="text">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="true"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- @test="handleTest"- />- </el-tab-pane>-- <el-tab-pane :label="$t('aiConfig.tabs.image')" name="image">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="false"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- />- </el-tab-pane>-- <el-tab-pane :label="$t('aiConfig.tabs.video')" name="video">- <ConfigList- :configs="configs"- :loading="loading"- :show-test-button="false"- @edit="handleEdit"- @delete="handleDelete"- @toggle-active="handleToggleActive"- />- </el-tab-pane>- </el-tabs>+ <template #actions>+ <el-button type="success" @click="showQuickSetupDialog">+ <el-icon><MagicStick /></el-icon>+ <span>一键配置火宝</span>+ </el-button>+ </template>+ </PageHeader>++ <!-- Provider Cards Grid -->+ <div v-loading="loading" class="provider-grid">+ <ProviderCard+ v-for="group in providerGroupsWithConfigs"+ :key="group.key"+ :provider-group="group"+ :configs="group.configs"+ :preset-models="group.presetModels"+ @refresh="loadAll"+ />+ </div>++ <!-- Quick Setup Dialog -->+ <el-dialog+ v-model="quickSetupVisible"+ title="一键配置"+ width="500px"+ :close-on-click-modal="false"+ >+ <div class="quick-setup-info">+ <p>将自动创建以下配置:</p>+ <ul>+ <li><strong>文本服务</strong>: {{ chatfireFirstModel('text') }}</li>+ <li><strong>图片服务</strong>: {{ chatfireFirstModel('image') }}</li>+ <li><strong>视频服务</strong>: {{ chatfireFirstModel('video') }}</li>+ </ul>+ <p class="quick-setup-tip">Base URL: https://api.chatfire.site/v1</p></div>-- <!-- Edit/Create Dialog / 编辑创建弹窗 -->- <el-dialog- v-model="dialogVisible"- :title="isEdit ? $t('aiConfig.editConfig') : $t('aiConfig.addConfig')"- width="600px"- :close-on-click-modal="false"- >- <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">- <el-form-item :label="$t('aiConfig.form.name')" prop="name">- <el-input- v-model="form.name"- :placeholder="$t('aiConfig.form.namePlaceholder')"- />- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.provider')" prop="provider">- <el-select- v-model="form.provider"- :placeholder="$t('aiConfig.form.providerPlaceholder')"- @change="handleProviderChange"- style="width: 100%"- >- <el-option- v-for="provider in availableProviders"- :key="provider.id"- :label="provider.name"- :value="provider.id"- :disabled="provider.disabled"- />- </el-select>- <div class="form-tip">{{ $t("aiConfig.form.providerTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.priority')" prop="priority">- <el-input-number- v-model="form.priority"- :min="0"- :max="100"- :step="1"- style="width: 100%"- />- <div class="form-tip">{{ $t("aiConfig.form.priorityTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.model')" prop="model">- <el-select- v-model="form.model"- :placeholder="$t('aiConfig.form.modelPlaceholder')"- multiple- filterable- allow-create- default-first-option- collapse-tags- collapse-tags-tooltip- style="width: 100%"- >- <el-option- v-for="model in availableModels"- :key="model"- :label="model"- :value="model"- />- </el-select>- <div class="form-tip">{{ $t("aiConfig.form.modelTip") }}</div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.baseUrl')" prop="base_url">- <el-input- v-model="form.base_url"- :placeholder="$t('aiConfig.form.baseUrlPlaceholder')"- />- <div class="form-tip">- {{ $t("aiConfig.form.baseUrlTip") }}- <br />- {{ $t("aiConfig.form.fullEndpoint") }}: {{ fullEndpointExample }}- </div>- </el-form-item>-- <el-form-item :label="$t('aiConfig.form.apiKey')" prop="api_key">- <el-input- v-model="form.api_key"- type="password"- show-password- :placeholder="$t('aiConfig.form.apiKeyPlaceholder')"- />- <div class="form-tip">{{ $t("aiConfig.form.apiKeyTip") }}</div>- </el-form-item>-- <el-form-item v-if="isEdit" :label="$t('aiConfig.form.isActive')">- <el-switch v-model="form.is_active" />- </el-form-item>- </el-form>-- <template #footer>- <el-button @click="dialogVisible = false">{{- $t("common.cancel")- }}</el-button>- <el-button- v-if="form.service_type === 'text'"- @click="testConnection"- :loading="testing"- >{{ $t("aiConfig.actions.test") }}</el-button+ <el-form label-width="80px">+ <el-form-item label="API Key" required>+ <el-input+ v-model="quickSetupApiKey"+ type="password"+ show-password+ placeholder="请输入 ChatFire API Key"+ />+ </el-form-item>+ </el-form>+ <template #footer>+ <div class="quick-setup-footer">+ <a+ href="https://api.chatfire.site/login?inviteCode=C4453345"+ target="_blank"+ class="register-link">- <el-button type="primary" @click="handleSubmit" :loading="submitting">- {{ isEdit ? $t("common.save") : $t("common.create") }}- </el-button>- </template>- </el-dialog>+ 没有 API Key?点击注册+ </a>+ <div class="footer-buttons">+ <el-button @click="quickSetupVisible = false">取消</el-button>+ <el-button+ type="primary"+ @click="handleQuickSetup"+ :loading="quickSetupLoading"+ >+ 确认配置+ </el-button>+ </div>+ </div>+ </template>+ </el-dialog></div></template><script setup lang="ts">-import { ref, reactive, onMounted, computed } from "vue";-import {- ElMessage,- ElMessageBox,- type FormInstance,- type FormRules,-} from "element-plus";-import { Plus } from "@element-plus/icons-vue";-import { aiAPI } from "@/api/ai";-import { PageHeader } from "@/components/common";-import type {- AIServiceConfig,- AIServiceType,- CreateAIConfigRequest,- UpdateAIConfigRequest,-} from "@/types/ai";-import ConfigList from "./components/ConfigList.vue";--const activeTab = ref<AIServiceType>("text");-const loading = ref(false);-const configs = ref<AIServiceConfig[]>([]);-const dialogVisible = ref(false);-const isEdit = ref(false);-const editingId = ref<number>();-const formRef = ref<FormInstance>();-const submitting = ref(false);-const testing = ref(false);--const form = reactive<- CreateAIConfigRequest & { is_active?: boolean; provider?: string }->({- service_type: "text",- provider: "",- name: "",- base_url: "",- api_key: "",- model: [], // 改为数组支持多选- priority: 0, // 默认优先级为0- is_active: true,-});--// 厂商和模型配置-interface ProviderConfig {- id: string;- name: string;- models: string[];- disabled?: boolean;+import { ref, computed, onMounted } from 'vue'+import { ElMessage } from 'element-plus'+import { MagicStick } from '@element-plus/icons-vue'+import { aiAPI } from '@/api/ai'+import { PageHeader } from '@/components/common'+import type { AIServiceConfig, AIServiceProvider, AIServiceType } from '@/types/ai'+import { PROVIDER_GROUPS, buildPresetModels } from '@/constants/ai-providers'+import ProviderCard from './components/ProviderCard.vue'++// --- State ---+const loading = ref(false)+const allConfigs = ref<AIServiceConfig[]>([])+const allProviders = ref<AIServiceProvider[]>([])+const quickSetupVisible = ref(false)+const quickSetupApiKey = ref('')+const quickSetupLoading = ref(false)++// --- Computed ---+const presetModelsMap = computed(() => buildPresetModels(allProviders.value))++const providerGroupsWithConfigs = computed(() => {+ return PROVIDER_GROUPS.map(group => {+ const configs = allConfigs.value.filter(c => group.ids.includes(c.provider || ''))+ const presetModels = presetModelsMap.value[group.key] || { text: [], image: [], video: [], audio: [], lipsync: [] }+ return { ...group, configs, presetModels }+ })+})++/** 获取 chatfire 在指定 service_type 下的第一个预设模型 */+function chatfireFirstModel(serviceType: AIServiceType): string {+ const models = presetModelsMap.value['chatfire']?.[serviceType]+ return models?.[0] || '-'}-const providerConfigs: Record<AIServiceType, ProviderConfig[]> = {- text: [- {- id: "openai",- name: "OpenAI",- models: ["gpt-5.2", "gemini-3-flash-preview"],- },- {- id: "chatfire",- name: "Chatfire",- models: [- "gemini-3-flash-preview",- "claude-sonnet-4-5-20250929",- "doubao-seed-1-8-251228",- ],- },- {- id: "gemini",- name: "Google Gemini",- models: ["gemini-2.5-pro", "gemini-3-flash-preview"],- },- ],- image: [- {- id: "volcengine",- name: "火山引擎",- models: ["doubao-seedream-4-5-251128", "doubao-seedream-4-0-250828"],- },- {- id: "chatfire",- name: "Chatfire",- models: ["doubao-seedream-4-5-251128", "nano-banana-pro"],- },- {- id: "gemini",- name: "Google Gemini",- models: ["gemini-3-pro-image-preview"],- },- { id: "openai", name: "OpenAI", models: ["dall-e-3", "dall-e-2"] },- ],- video: [- {- id: "volces",- name: "火山引擎",- models: [- "doubao-seedance-1-5-pro-251215",- "doubao-seedance-1-0-lite-i2v-250428",- "doubao-seedance-1-0-lite-t2v-250428",- "doubao-seedance-1-0-pro-250528",- "doubao-seedance-1-0-pro-fast-251015",- ],- },- {- id: "chatfire",- name: "Chatfire",- models: [- "doubao-seedance-1-5-pro-251215",- "doubao-seedance-1-0-lite-i2v-250428",- "doubao-seedance-1-0-lite-t2v-250428",- "doubao-seedance-1-0-pro-250528",- "doubao-seedance-1-0-pro-fast-251015",- "sora-2",- "sora-2-pro",- ],- },- { id: "openai", name: "OpenAI", models: ["sora-2", "sora-2-pro"] },- // { id: 'minimax', name: 'MiniMax', models: ['MiniMax-Hailuo-2.3', 'MiniMax-Hailuo-2.3-Fast', 'MiniMax-Hailuo-02'] }- ],-};--// 当前可用的厂商列表-const availableProviders = computed(() => {- const allProviders = providerConfigs[form.service_type] || [];-- // 新建配置时显示所有厂商;编辑时只显示有激活配置的厂商- if (!isEdit.value) {- return allProviders;- }-- const activeConfigs = configs.value.filter(- (c) => c.service_type === form.service_type && c.is_active,- );- const activeProviderIds = new Set(activeConfigs.map((c) => c.provider));- return allProviders.filter((p) => activeProviderIds.has(p.id));-});--// 当前可用的模型列表(从已激活的配置中获取)-const availableModels = computed(() => {- if (!form.provider) return [];-- // 从已激活的配置中提取该 provider 的所有模型- const activeConfigsForProvider = configs.value.filter(- (c) =>- c.provider === form.provider &&- c.service_type === form.service_type &&- c.is_active,- );-- // 提取所有模型,去重- const models = new Set<string>();- activeConfigsForProvider.forEach((config) => {- const modelList = Array.isArray(config.model) ? config.model : [config.model];- modelList.forEach((m: string) => models.add(m));- });-- return Array.from(models);-});--// 完整端点示例-const fullEndpointExample = computed(() => {- const baseUrl = form.base_url || "https://api.example.com";- const provider = form.provider;- const serviceType = form.service_type;-- let endpoint = "";-- if (serviceType === "text") {- if (provider === "gemini" || provider === "google") {- endpoint = "/v1beta/models/{model}:generateContent";- } else {- endpoint = "/chat/completions";- }- } else if (serviceType === "image") {- if (provider === "gemini" || provider === "google") {- endpoint = "/v1beta/models/{model}:generateContent";- } else {- endpoint = "/images/generations";- }- } else if (serviceType === "video") {- if (provider === "chatfire") {- endpoint = "/video/generations";- } else if (- provider === "doubao" ||- provider === "volcengine" ||- provider === "volces"- ) {- endpoint = "/contents/generations/tasks";- } else if (provider === "openai") {- endpoint = "/videos";- } else {- endpoint = "/video/generations";- }- }-- return baseUrl + endpoint;-});--const rules: FormRules = {- name: [{ required: true, message: "请输入配置名称", trigger: "blur" }],- provider: [{ required: true, message: "请选择厂商", trigger: "change" }],- base_url: [- { required: true, message: "请输入 Base URL", trigger: "blur" },- { type: "url", message: "请输入正确的 URL 格式", trigger: "blur" },- ],- api_key: [{ required: true, message: "请输入 API Key", trigger: "blur" }],- model: [- {- required: true,- message: "请至少选择一个模型",- trigger: "change",- validator: (rule: any, value: any, callback: any) => {- if (Array.isArray(value) && value.length > 0) {- callback();- } else if (typeof value === "string" && value.length > 0) {- callback();- } else {- callback(new Error("请至少选择一个模型"));- }- },- },- ],-};--const loadConfigs = async () => {- loading.value = true;+// --- Load ---+async function loadAll() {+ loading.value = truetry {- configs.value = await aiAPI.list(activeTab.value);+ const [text, image, video, audio, lipsync, providers] = await Promise.all([+ aiAPI.list('text'),+ aiAPI.list('image'),+ aiAPI.list('video'),+ aiAPI.list('audio'),+ aiAPI.list('lipsync'),+ aiAPI.listProviders(),+ ])+ allConfigs.value = [...text, ...image, ...video, ...audio, ...lipsync]+ allProviders.value = providers} catch (error: any) {- ElMessage.error(error.message || "加载失败");+ ElMessage.error(error.message || '加载失败')} finally {- loading.value = false;+ loading.value = false}-};--// 生成随机配置名称-const generateConfigName = (- provider: string,- serviceType: AIServiceType,-): string => {- const providerNames: Record<string, string> = {- chatfire: "ChatFire",- openai: "OpenAI",- gemini: "Gemini",- google: "Google",- };-- const serviceNames: Record<AIServiceType, string> = {- text: "文本",- image: "图片",- video: "视频",- };-- const randomNum = Math.floor(Math.random() * 10000)- .toString()- .padStart(4, "0");- const providerName = providerNames[provider] || provider;- const serviceName = serviceNames[serviceType] || serviceType;-- return `${providerName}-${serviceName}-${randomNum}`;-};--const showCreateDialog = () => {- isEdit.value = false;- editingId.value = undefined;- resetForm();- form.service_type = activeTab.value;- // 默认选择 chatfire- form.provider = "chatfire";- // 设置默认 base_url- form.base_url = "https://api.chatfire.site/v1";- // 自动生成随机配置名称- form.name = generateConfigName("chatfire", activeTab.value);- dialogVisible.value = true;-};--const handleEdit = (config: AIServiceConfig) => {- isEdit.value = true;- editingId.value = config.id;-- Object.assign(form, {- service_type: config.service_type,- provider: config.provider || "chatfire", // 直接使用配置中的 provider,默认为 chatfire- name: config.name,- base_url: config.base_url,- api_key: config.api_key,- model: Array.isArray(config.model) ? config.model : [config.model], // 统一转换为数组- priority: config.priority || 0,- is_active: config.is_active,- });- dialogVisible.value = true;-};+}-const handleDelete = async (config: AIServiceConfig) => {- try {- await ElMessageBox.confirm("确定要删除该配置吗?", "警告", {- confirmButtonText: "确定",- cancelButtonText: "取消",- type: "warning",- });+// --- Quick Setup ---+function showQuickSetupDialog() {+ quickSetupApiKey.value = ''+ quickSetupVisible.value = true+}- await aiAPI.delete(config.id);- ElMessage.success("删除成功");- loadConfigs();- } catch (error: any) {- if (error !== "cancel") {- ElMessage.error(error.message || "删除失败");- }+const generateConfigName = (provider: string, serviceType: AIServiceType): string => {+ const providerNames: Record<string, string> = {+ chatfire: 'ChatFire', openai: 'OpenAI', gemini: 'Gemini', google: 'Google',}-};+ const serviceNames: Record<AIServiceType, string> = { text: '文本', image: '图片', video: '视频', audio: '音频', lipsync: '口型同步' }+ const randomNum = Math.floor(Math.random() * 10000).toString().padStart(4, '0')+ return `${providerNames[provider] || provider}-${serviceNames[serviceType]}-${randomNum}`+}-const handleToggleActive = async (config: AIServiceConfig) => {- try {- const newActiveState = !config.is_active;- await aiAPI.update(config.id, { is_active: newActiveState });- ElMessage.success(newActiveState ? "已启用配置" : "已禁用配置");- await loadConfigs();- } catch (error: any) {- ElMessage.error(error.message || "操作失败");+async function handleQuickSetup() {+ if (!quickSetupApiKey.value.trim()) {+ ElMessage.warning('请输入 API Key')+ return}-};--const testConnection = async () => {- if (!formRef.value) return;- const valid = await formRef.value.validate().catch(() => false);- if (!valid) return;+ quickSetupLoading.value = true+ const baseUrl = 'https://api.chatfire.site/v1'+ const apiKey = quickSetupApiKey.value.trim()- testing.value = true;try {- await aiAPI.testConnection({- base_url: form.base_url,- api_key: form.api_key,- model: form.model,- provider: form.provider,- });- ElMessage.success("连接测试成功!");- } catch (error: any) {- ElMessage.error(error.message || "连接测试失败");- } finally {- testing.value = false;- }-};--const handleTest = async (config: AIServiceConfig) => {- testing.value = true;- try {- await aiAPI.testConnection({- base_url: config.base_url,- api_key: config.api_key,- model: config.model,- provider: config.provider,- });- ElMessage.success("连接测试成功!");- } catch (error: any) {- ElMessage.error(error.message || "连接测试失败");- } finally {- testing.value = false;- }-};--const handleSubmit = async () => {- if (!formRef.value) return;-- await formRef.value.validate(async (valid) => {- if (!valid) return;-- submitting.value = true;- try {- if (isEdit.value && editingId.value) {- const updateData: UpdateAIConfigRequest = {- name: form.name,- provider: form.provider,- base_url: form.base_url,- api_key: form.api_key,- model: form.model,- priority: form.priority,- is_active: form.is_active,- };- await aiAPI.update(editingId.value, updateData);- ElMessage.success("更新成功");+ const [textConfigs, imageConfigs, videoConfigs] = await Promise.all([+ aiAPI.list('text'),+ aiAPI.list('image'),+ aiAPI.list('video'),+ ])++ const createdServices: string[] = []+ const skippedServices: string[] = []++ const types: { key: AIServiceType; label: string; configs: AIServiceConfig[] }[] = [+ { key: 'text', label: '文本', configs: textConfigs },+ { key: 'image', label: '图片', configs: imageConfigs },+ { key: 'video', label: '视频', configs: videoConfigs },+ ]++ for (const { key, label, configs } of types) {+ if (!configs.find(c => c.base_url === baseUrl)) {+ const firstModel = chatfireFirstModel(key)+ await aiAPI.create({+ service_type: key, provider: 'chatfire',+ name: generateConfigName('chatfire', key),+ base_url: baseUrl, api_key: apiKey,+ model: firstModel !== '-' ? [firstModel] : [], priority: 0,+ })+ createdServices.push(label)} else {- await aiAPI.create(form);- ElMessage.success("创建成功");+ skippedServices.push(label)}-- dialogVisible.value = false;- loadConfigs();- } catch (error: any) {- ElMessage.error(error.message || "操作失败");- } finally {- submitting.value = false;}- });-};-const handleTabChange = (tabName: string | number) => {- // 标签页切换时重新加载对应服务类型的配置- activeTab.value = tabName as AIServiceType;- loadConfigs();-};--const handleProviderChange = () => {- // 切换厂商时清空已选模型- form.model = [];-- // 根据厂商自动设置默认 base_url- if (form.provider === "gemini" || form.provider === "google") {- form.base_url = "https://api.chatfire.site";- } else {- // openai, chatfire 等其他厂商- form.base_url = "https://api.chatfire.site/v1";- }+ if (createdServices.length > 0 && skippedServices.length > 0) {+ ElMessage.success(`已创建 ${createdServices.join('、')} 配置,${skippedServices.join('、')} 配置已存在`)+ } else if (createdServices.length > 0) {+ ElMessage.success(`一键配置成功!已创建 ${createdServices.join('、')} 服务配置`)+ } else {+ ElMessage.info('所有配置已存在,无需重复创建')+ }- // 仅在新建配置时自动更新名称- if (!isEdit.value) {- form.name = generateConfigName(form.provider || '', form.service_type);+ quickSetupVisible.value = false+ loadAll()+ } catch (error: any) {+ ElMessage.error(error.message || '配置失败')+ } finally {+ quickSetupLoading.value = false}-};--const resetForm = () => {- const serviceType = form.service_type || "text";- Object.assign(form, {- service_type: serviceType,- provider: "",- name: "",- base_url: "",- api_key: "",- model: [], // 改为空数组- priority: 0,- is_active: true,- });- formRef.value?.resetFields();-};+}onMounted(() => {- loadConfigs();-});+ loadAll()+})</script><style scoped>-/* ========================================- Tabs / 标签页 - 紧凑内边距- ======================================== */-.tabs-wrapper {- background: var(--bg-card);- border: 1px solid var(--border-primary);- border-radius: var(--radius-lg);- padding: var(--space-3);- box-shadow: var(--shadow-card);+.provider-grid {+ display: grid;+ grid-template-columns: 1fr;+ gap: 16px;+ min-height: 200px;}@media (min-width: 768px) {- .tabs-wrapper {- padding: var(--space-4);+ .provider-grid {+ grid-template-columns: repeat(2, 1fr);}}-/* ========================================- Form Tips / 表单提示- ======================================== */-.form-tip {- font-size: 0.75rem;- color: var(--text-muted);- margin-top: 0.25rem;-}+/* Quick Setup Dialog */+.quick-setup-info {+ margin-bottom: 16px;+ padding: 12px 16px;+ background: var(--glass-bg-muted);+ border-radius: var(--glass-radius-md);+ font-size: 14px;+ color: var(--glass-text-primary);++ p {+ margin: 0 0 8px 0;+ }-/* ========================================- Dialog / 弹窗- ======================================== */-:deep(.el-dialog) {- border-radius: 0.75rem;-}+ ul {+ margin: 8px 0;+ padding-left: 20px;+ }-:deep(.el-dialog__header) {- padding: 1.25rem 1.5rem;- border-bottom: 1px solid var(--border-primary);- margin-right: 0;+ li {+ margin: 4px 0;+ color: var(--glass-text-secondary);+ }++ .quick-setup-tip {+ margin-top: 12px;+ font-size: 12px;+ color: var(--glass-text-tertiary);+ }}-:deep(.el-dialog__title) {- font-size: 1.125rem;- font-weight: 600;- color: var(--text-primary);+.quick-setup-footer {+ display: flex;+ justify-content: space-between;+ align-items: center;+ width: 100%;}-:deep(.el-dialog__body) {- padding: 1.5rem;+.register-link {+ font-size: 12px;+ color: var(--glass-text-tertiary);+ text-decoration: none;+ transition: color 0.2s;++ &:hover {+ color: var(--glass-accent-from);+ }}-:deep(.el-dialog__footer) {- padding: 1rem 1.5rem;- border-top: 1px solid var(--border-primary);+.footer-buttons {+ display: flex;+ gap: 8px;}</style>diff --git a/web/src/views/settings/components/ConfigList.vue b/web/src/views/settings/components/ConfigList.vuedeleted file mode 100644index 78fcc22..0000000--- a/web/src/views/settings/components/ConfigList.vue+++ /dev/null@@ -1,218 +0,0 @@-<template>- <div v-loading="loading" class="config-list">- <el-empty v-if="!loading && configs.length === 0" :description="$t('aiConfig.empty')" />-- <el-card- v-for="config in configs"- :key="config.id"- class="config-card"- shadow="hover"- >- <div class="config-header">- <div class="config-title">- <h3>{{ config.name }}</h3>- <el-tag v-if="config.is_active" type="success" size="small">{{ $t('aiConfig.enabled') }}</el-tag>- <el-tag v-else type="info" size="small">{{ $t('aiConfig.disabled') }}</el-tag>- </div>- <div class="config-actions">- <el-button v-if="showTestButton" text @click="$emit('test', config)" :icon="Connection">- {{ $t('aiConfig.actions.test') }}- </el-button>- <el-button text @click="$emit('edit', config)" :icon="Edit">- {{ $t('common.edit') }}- </el-button>- <el-button- text- :type="config.is_active ? 'warning' : 'success'"- @click="$emit('toggle-active', config)"- >- {{ config.is_active ? $t('aiConfig.disable') : $t('aiConfig.enable') }}- </el-button>- <el-popconfirm- :title="$t('aiConfig.messages.deleteConfirm')"- @confirm="$emit('delete', config)"- >- <template #reference>- <el-button text type="danger" :icon="Delete">- {{ $t('common.delete') }}- </el-button>- </template>- </el-popconfirm>- </div>- </div>-- <div class="config-info">- <div class="info-item">- <label>Base URL:</label>- <span class="url-text">{{ config.base_url }}</span>- </div>-- <div class="info-item">- <label>{{ $t('aiConfig.endpoint') }}:</label>- <span>{{ config.endpoint || '/v1/chat/completions' }}</span>- </div>-- <div v-if="config.service_type === 'video' && config.query_endpoint" class="info-item">- <label>{{ $t('aiConfig.queryEndpoint') }}:</label>- <span>{{ config.query_endpoint }}</span>- </div>-- <div class="info-item">- <label>优先级:</label>- <el-tag size="small" :type="(config.priority || 0) >= 50 ? 'danger' : (config.priority || 0) >= 20 ? 'warning' : 'info'">- {{ config.priority || 0 }}- </el-tag>- </div>-- <div class="info-item">- <label>模型:</label>- <template v-if="Array.isArray(config.model)">- <el-tag- v-for="(model, index) in config.model"- :key="index"- size="small"- effect="plain"- style="margin-right: 4px"- >- {{ model }}- </el-tag>- </template>- <el-tag v-else size="small" effect="plain">{{ config.model }}</el-tag>- </div>-- <div class="info-item">- <label>API Key:</label>- <span class="api-key">{{ maskApiKey(config.api_key) }}</span>- </div>-- <div class="info-item">- <label>创建时间:</label>- <span class="time-text">{{ formatDate(config.created_at) }}</span>- </div>- </div>- </el-card>- </div>-</template>--<script setup lang="ts">-import { Connection, Edit, Delete } from '@element-plus/icons-vue'-import type { AIServiceConfig } from '@/types/ai'--defineProps<{- configs: AIServiceConfig[]- loading: boolean- showTestButton?: boolean-}>()--defineEmits<{- edit: [config: AIServiceConfig]- delete: [config: AIServiceConfig]- 'toggle-active': [config: AIServiceConfig]- test: [config: AIServiceConfig]-}>()--const maskApiKey = (key: string) => {- if (!key) return ''- if (key.length <= 8) return '***'- return key.substring(0, 4) + '***' + key.substring(key.length - 4)-}--const formatDate = (dateString: string) => {- return new Date(dateString).toLocaleString('zh-CN')-}-</script>--<style scoped>-.config-list {- display: grid;- gap: 1rem;- min-height: 300px;-}--.config-card {- transition: all 0.2s ease;- background: var(--bg-card);- border: 1px solid var(--border-primary);-}--.config-card :deep(.el-card__body) {- padding: 1.25rem;-}--.config-card:hover {- border-color: var(--border-secondary);-}--.config-header {- display: flex;- justify-content: space-between;- align-items: center;- margin-bottom: 1rem;- padding-bottom: 0.75rem;- border-bottom: 1px solid var(--border-primary);-}--.config-title {- display: flex;- align-items: center;- gap: 0.75rem;-}--.config-title h3 {- margin: 0;- font-size: 1rem;- font-weight: 600;- color: var(--text-primary);-}--.config-actions {- display: flex;- gap: 0.5rem;-}--.config-info {- display: grid;- gap: 0.75rem;-}--.info-item {- display: flex;- align-items: center;- font-size: 0.875rem;- color: var(--text-primary);-}--.info-item label {- min-width: 5.5rem;- color: var(--text-muted);- font-weight: 500;-}--.info-item span {- color: var(--text-secondary);-}--.url-text {- color: #0ea5e9 !important;- word-break: break-all;-}--.api-key {- font-family: monospace;- color: var(--text-muted) !important;-}--.time-text {- color: var(--text-muted) !important;- font-size: 0.8125rem;-}--/* Dark mode overrides */-.dark .config-card {- background: var(--bg-card);-}--.dark .config-card :deep(.el-card__body) {- background: transparent;-}-</style>diff --git a/web/src/views/settings/components/ProviderCard.vue b/web/src/views/settings/components/ProviderCard.vuenew file mode 100644index 0000000..59579d0--- /dev/null+++ b/web/src/views/settings/components/ProviderCard.vue@@ -0,0 +1,591 @@+<template>+ <div class="provider-card glass-surface">+ <!-- Header -->+ <div class="card-header">+ <div class="provider-identity">+ <div class="provider-avatar" :style="{ background: avatarColor }">+ {{ providerGroup.name.charAt(0) }}+ </div>+ <div class="provider-info">+ <span class="provider-name">{{ providerGroup.name }}</span>+ <span :class="['status-dot', hasApiKey ? 'connected' : 'disconnected']" />+ </div>+ </div>+ </div>++ <!-- API Key & Base URL -->+ <div class="credentials-section glass-surface-soft">+ <!-- API Key Row -->+ <div class="credential-row">+ <label class="credential-label">API Key</label>+ <div class="credential-value">+ <template v-if="editingField === 'api_key'">+ <input+ v-model="editApiKey"+ type="password"+ class="glass-input-base glass-input-sm credential-input"+ placeholder="sk-..."+ @keyup.enter="saveCredential('api_key')"+ @keyup.escape="cancelEdit"+ />+ <button class="glass-icon-btn-sm" @click="saveCredential('api_key')" title="保存">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>+ </button>+ <button class="glass-icon-btn-sm" @click="cancelEdit" title="取消">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>+ </button>+ </template>+ <template v-else>+ <span class="masked-key">{{ maskedApiKey }}</span>+ <button v-if="hasApiKey" class="glass-icon-btn-sm" @click="toggleKeyVisibility" :title="showFullKey ? '隐藏' : '显示'">+ <svg v-if="showFullKey" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>+ <svg v-else width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>+ </button>+ <button class="glass-icon-btn-sm" @click="startEdit('api_key')" title="编辑">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>+ </button>+ </template>+ </div>+ </div>++ <!-- Base URL Row -->+ <div class="credential-row">+ <label class="credential-label">Base URL</label>+ <div class="credential-value">+ <template v-if="editingField === 'base_url'">+ <input+ v-model="editBaseUrl"+ type="text"+ class="glass-input-base glass-input-sm credential-input"+ placeholder="https://api.example.com/v1"+ @keyup.enter="saveCredential('base_url')"+ @keyup.escape="cancelEdit"+ />+ <button class="glass-icon-btn-sm" @click="saveCredential('base_url')" title="保存">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>+ </button>+ <button class="glass-icon-btn-sm" @click="cancelEdit" title="取消">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>+ </button>+ </template>+ <template v-else>+ <span class="base-url-text">{{ currentBaseUrl || '未配置' }}</span>+ <button class="glass-icon-btn-sm" @click="startEdit('base_url')" title="编辑">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>+ </button>+ </template>+ </div>+ </div>+ </div>++ <!-- Model Section -->+ <div class="models-section">+ <!-- Service Type Tabs -->+ <div class="service-tabs">+ <button+ v-for="tab in availableTabs"+ :key="tab.key"+ :class="['service-tab', { active: activeServiceType === tab.key }]"+ @click="activeServiceType = tab.key"+ >+ {{ tab.label }}+ </button>+ </div>++ <!-- Model List -->+ <div class="model-list glass-provider-model-scroll">+ <div+ v-for="model in currentModels"+ :key="model.name"+ class="model-row glass-list-row"+ >+ <span class="model-name">{{ model.name }}</span>+ <el-switch+ :model-value="model.active"+ size="small"+ @change="(val: boolean) => handleModelToggle(model, val)"+ />+ </div>++ <div v-if="currentModels.length === 0" class="empty-models">+ <span>暂无模型</span>+ </div>++ <!-- Add Custom Model -->+ <div v-if="addingModel" class="model-row add-model-row">+ <input+ v-model="newModelName"+ class="glass-input-base glass-input-sm add-model-input"+ placeholder="输入模型名称"+ @keyup.enter="confirmAddModel"+ @keyup.escape="addingModel = false"+ />+ <div class="add-model-actions">+ <button class="glass-icon-btn-sm" @click="confirmAddModel" title="确认">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>+ </button>+ <button class="glass-icon-btn-sm" @click="addingModel = false" title="取消">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>+ </button>+ </div>+ </div>++ <button v-else class="add-model-btn glass-btn-base glass-btn-ghost glass-btn-sm" @click="addingModel = true">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>+ 添加模型+ </button>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, computed, watch } from 'vue'+import { ElMessage } from 'element-plus'+import { aiAPI } from '@/api/ai'+import type { AIServiceConfig, AIServiceType } from '@/types/ai'+import type { ProviderGroup } from '@/constants/ai-providers'++const props = defineProps<{+ providerGroup: ProviderGroup+ configs: AIServiceConfig[]+ presetModels: Record<AIServiceType, string[]>+}>()++const emit = defineEmits<{+ refresh: []+}>()++// --- State ---+const editingField = ref<'api_key' | 'base_url' | null>(null)+const editApiKey = ref('')+const editBaseUrl = ref('')+const showFullKey = ref(false)+const activeServiceType = ref<AIServiceType>('text')+const addingModel = ref(false)+const newModelName = ref('')+const saving = ref(false)++// --- Avatar color ---+const avatarColors: Record<string, string> = {+ chatfire: 'linear-gradient(135deg, #f97316, #ef4444)',+ gemini: 'linear-gradient(135deg, #4285f4, #34a853)',+ openai: 'linear-gradient(135deg, #10a37f, #1a7f64)',+ volcengine: 'linear-gradient(135deg, #3370ff, #2b5fd9)',+ minimax: 'linear-gradient(135deg, #8b5cf6, #6d28d9)',+ vidu: 'linear-gradient(135deg, #06b6d4, #0891b2)',+ openrouter: 'linear-gradient(135deg, #f59e0b, #d97706)',+ fal: 'linear-gradient(135deg, #ec4899, #be185d)',+ qwen: 'linear-gradient(135deg, #6366f1, #4f46e5)',+}+const avatarColor = computed(() => avatarColors[props.providerGroup.key] || 'linear-gradient(135deg, #6366f1, #8b5cf6)')++// --- Computed ---+const hasApiKey = computed(() => props.configs.some(c => c.api_key && c.api_key.length > 0))++const currentApiKey = computed(() => {+ const config = props.configs.find(c => c.api_key)+ return config?.api_key || ''+})++const maskedApiKey = computed(() => {+ const key = showFullKey.value ? currentApiKey.value : currentApiKey.value+ if (!key) return '未配置'+ if (showFullKey.value) return key+ if (key.length <= 8) return '****'+ return key.substring(0, 4) + '****' + key.substring(key.length - 4)+})++const currentBaseUrl = computed(() => {+ const config = props.configs.find(c => c.base_url)+ return config?.base_url || ''+})++const SERVICE_TYPE_LABELS: Record<AIServiceType, string> = {+ text: '文本',+ image: '图片',+ video: '视频',+ audio: '音频',+ lipsync: '口型同步',+}++const availableTabs = computed(() => {+ const types: AIServiceType[] = ['text', 'image', 'video', 'audio', 'lipsync']+ return types+ .filter(t => (props.presetModels[t] && props.presetModels[t].length > 0) || props.configs.some(c => c.service_type === t))+ .map(t => ({ key: t, label: SERVICE_TYPE_LABELS[t] }))+})++// 确保 activeServiceType 始终指向有效 tab(MiniMax/Vidu 只有 video)+watch(availableTabs, (tabs) => {+ if (tabs.length > 0 && !tabs.some(t => t.key === activeServiceType.value)) {+ activeServiceType.value = tabs[0].key+ }+}, { immediate: true })++interface ModelItem {+ name: string+ active: boolean+ configId?: number+ providerId: string+}++const currentModels = computed<ModelItem[]>(() => {+ const st = activeServiceType.value+ const presets = props.presetModels[st] || []+ const configsForType = props.configs.filter(c => c.service_type === st)++ // Build a map of model -> config info from existing configs+ const configModelMap = new Map<string, { active: boolean; configId: number; providerId: string }>()+ for (const cfg of configsForType) {+ const models = Array.isArray(cfg.model) ? cfg.model : [cfg.model]+ for (const m of models) {+ configModelMap.set(m, { active: cfg.is_active, configId: cfg.id, providerId: cfg.provider || '' })+ }+ }++ // Merge presets + any extra models from configs not in presets+ const allModelNames = new Set([...presets])+ for (const m of configModelMap.keys()) {+ allModelNames.add(m)+ }++ return Array.from(allModelNames).map(name => {+ const info = configModelMap.get(name)+ return {+ name,+ active: info?.active ?? false,+ configId: info?.configId,+ providerId: info?.providerId || props.providerGroup.ids[0],+ }+ })+})++// --- Inline Edit ---+function startEdit(field: 'api_key' | 'base_url') {+ editingField.value = field+ if (field === 'api_key') {+ editApiKey.value = currentApiKey.value+ } else {+ editBaseUrl.value = currentBaseUrl.value+ }+}++function cancelEdit() {+ editingField.value = null+}++async function saveCredential(field: 'api_key' | 'base_url') {+ const value = field === 'api_key' ? editApiKey.value.trim() : editBaseUrl.value.trim()+ if (!value) {+ ElMessage.warning(field === 'api_key' ? '请输入 API Key' : '请输入 Base URL')+ return+ }++ saving.value = true+ try {+ // Update all configs under this provider+ const updates = props.configs.map(c =>+ aiAPI.update(c.id, { [field]: value })+ )+ await Promise.all(updates)+ ElMessage.success('保存成功')+ editingField.value = null+ emit('refresh')+ } catch (error: any) {+ ElMessage.error(error.message || '保存失败')+ } finally {+ saving.value = false+ }+}++// --- Model Toggle ---+async function handleModelToggle(model: ModelItem, active: boolean) {+ try {+ if (model.configId) {+ // Existing config — toggle is_active+ await aiAPI.update(model.configId, { is_active: active })+ } else {+ // No config yet — create one+ const providerId = props.providerGroup.ids[0]+ await aiAPI.create({+ service_type: activeServiceType.value,+ provider: providerId,+ name: `${props.providerGroup.name}-${SERVICE_TYPE_LABELS[activeServiceType.value]}-${model.name}`,+ base_url: currentBaseUrl.value || getDefaultBaseUrl(providerId),+ api_key: currentApiKey.value,+ model: [model.name],+ priority: 0,+ })+ }+ emit('refresh')+ } catch (error: any) {+ ElMessage.error(error.message || '操作失败')+ }+}++// --- Add Model ---+async function confirmAddModel() {+ const name = newModelName.value.trim()+ if (!name) return++ try {+ const providerId = props.providerGroup.ids[0]+ await aiAPI.create({+ service_type: activeServiceType.value,+ provider: providerId,+ name: `${props.providerGroup.name}-${SERVICE_TYPE_LABELS[activeServiceType.value]}-${name}`,+ base_url: currentBaseUrl.value || getDefaultBaseUrl(providerId),+ api_key: currentApiKey.value,+ model: [name],+ priority: 0,+ })+ ElMessage.success('模型已添加')+ addingModel.value = false+ newModelName.value = ''+ emit('refresh')+ } catch (error: any) {+ ElMessage.error(error.message || '添加失败')+ }+}++function getDefaultBaseUrl(providerId: string): string {+ const defaults: Record<string, string> = {+ chatfire: 'https://api.chatfire.site/v1',+ openai: 'https://api.openai.com/v1',+ gemini: 'https://generativelanguage.googleapis.com',+ google: 'https://generativelanguage.googleapis.com',+ volcengine: 'https://ark.cn-beijing.volces.com/api/v3',+ volces: 'https://ark.cn-beijing.volces.com/api/v3',+ minimax: 'https://api.minimaxi.com/v1',+ vidu: 'https://api.vidu.com/v1',+ openrouter: 'https://openrouter.ai/api/v1',+ fal: 'https://queue.fal.run',+ qwen: 'https://dashscope.aliyuncs.com/compatible-mode/v1',+ }+ return defaults[providerId] || 'https://api.chatfire.site/v1'+}++// --- Key Visibility ---+function toggleKeyVisibility() {+ showFullKey.value = !showFullKey.value+}+</script>++<style scoped>+.provider-card {+ padding: 20px;+ display: flex;+ flex-direction: column;+ gap: 16px;+ transition: all 0.2s ease;+}++.provider-card:hover {+ box-shadow: var(--glass-shadow-md);+}++/* Header */+.card-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.provider-identity {+ display: flex;+ align-items: center;+ gap: 12px;+}++.provider-avatar {+ width: 36px;+ height: 36px;+ border-radius: var(--glass-radius-md);+ display: flex;+ align-items: center;+ justify-content: center;+ font-weight: 700;+ font-size: 16px;+ color: #fff;+ flex-shrink: 0;+}++.provider-info {+ display: flex;+ align-items: center;+ gap: 8px;+}++.provider-name {+ font-size: 15px;+ font-weight: 700;+ color: var(--glass-text-primary);+}++.status-dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ flex-shrink: 0;+}++.status-dot.connected {+ background: #22c55e;+ box-shadow: 0 0 6px rgba(34, 197, 94, 0.4);+}++.status-dot.disconnected {+ background: #eab308;+ box-shadow: 0 0 6px rgba(234, 179, 8, 0.3);+}++/* Credentials */+.credentials-section {+ padding: 12px;+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.credential-row {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 32px;+}++.credential-label {+ font-size: 12px;+ font-weight: 600;+ color: var(--glass-text-tertiary);+ min-width: 60px;+ flex-shrink: 0;+}++.credential-value {+ display: flex;+ align-items: center;+ gap: 6px;+ flex: 1;+ min-width: 0;+}++.credential-input {+ flex: 1;+ min-width: 0;+}++.masked-key {+ font-family: monospace;+ font-size: 13px;+ color: var(--glass-text-secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.base-url-text {+ font-size: 13px;+ color: var(--glass-text-secondary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++/* Service Tabs */+.models-section {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.service-tabs {+ display: flex;+ gap: 4px;+ padding: 2px;+ background: var(--glass-bg-muted);+ border-radius: var(--glass-radius-xs);+ width: fit-content;+}++.service-tab {+ padding: 4px 12px;+ font-size: 12px;+ font-weight: 600;+ color: var(--glass-text-secondary);+ background: transparent;+ border: none;+ border-radius: var(--glass-radius-xs);+ cursor: pointer;+ transition: all 0.2s ease;+}++.service-tab:hover {+ color: var(--glass-text-primary);+}++.service-tab.active {+ background: var(--glass-bg-surface);+ color: var(--glass-text-primary);+ box-shadow: var(--glass-shadow-sm);+}++/* Model List */+.model-list {+ display: flex;+ flex-direction: column;+ gap: 4px;+ max-height: 240px;+ overflow-y: auto;+}++.model-row {+ padding: 6px 10px;+}++.model-name {+ font-size: 13px;+ font-weight: 500;+ color: var(--glass-text-primary);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.empty-models {+ padding: 16px;+ text-align: center;+ font-size: 13px;+ color: var(--glass-text-tertiary);+}++/* Add Model */+.add-model-btn {+ width: 100%;+ justify-content: center;+ margin-top: 4px;+ color: var(--glass-text-tertiary);+}++.add-model-btn:hover {+ color: var(--glass-text-primary);+}++.add-model-row {+ display: flex;+ align-items: center;+ gap: 8px;+}++.add-model-input {+ flex: 1;+ min-width: 0;+}++.add-model-actions {+ display: flex;+ gap: 2px;+ flex-shrink: 0;+}+</style>