feat: 新增配置与提示词偏好页
后端新增 preferences 与 prompt_customizations 表及对应接口, 支持 BYOK 模型渠道密钥落库(仅回显掩码)与按任务类型定制 平台提示词模板;前端新增 /settings 页面及入口。
This commit is contained in:
1 parent
ae6cdf1551
commit
b9df2f84ab
27 files changed
+1515
-22
No files matched your search
@@ -38,6 +38,8 @@ func main() {
|
||||
|
||||
canvasRepo := repository.NewCanvasRepository(db)
|
||||
taskRepo := repository.NewTaskRepository(db)
|
||||
preferenceRepo := repository.NewPreferenceRepository(db)
|
||||
promptRepo := repository.NewPromptRepository(db)
|
||||
broker := sse.NewBroker()
|
||||
|
||||
store, err := storage.NewLocal(cfg.FilesDir(), cfg.PublicBaseURL)
|
||||
@@ -58,11 +60,13 @@ func main() {
|
||||
taskService.SetController(pool)
|
||||
|
||||
router := handler.NewRouter(handler.Deps{
|
||||
Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)),
|
||||
Task: handler.NewTaskHandler(taskService),
|
||||
Event: handler.NewEventHandler(broker),
|
||||
Config: cfg,
|
||||
FileDir: store.Root(),
|
||||
Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)),
|
||||
Task: handler.NewTaskHandler(taskService),
|
||||
Event: handler.NewEventHandler(broker),
|
||||
Preference: handler.NewPreferenceHandler(service.NewPreferenceService(preferenceRepo)),
|
||||
Prompt: handler.NewPromptHandler(service.NewPromptService(promptRepo)),
|
||||
Config: cfg,
|
||||
FileDir: store.Root(),
|
||||
})
|
||||
|
||||
server := &http.Server{
|
||||
|
||||
@@ -28,7 +28,12 @@ func Open(cfg config.Config) (*gorm.DB, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(&model.Canvas{}, &model.Task{}); err != nil {
|
||||
if err := db.AutoMigrate(
|
||||
&model.Canvas{},
|
||||
&model.Task{},
|
||||
&model.Preference{},
|
||||
&model.PromptCustomization{},
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/service"
|
||||
)
|
||||
|
||||
type PreferenceHandler struct {
|
||||
preferences *service.PreferenceService
|
||||
}
|
||||
|
||||
func NewPreferenceHandler(preferences *service.PreferenceService) *PreferenceHandler {
|
||||
return &PreferenceHandler{preferences: preferences}
|
||||
}
|
||||
|
||||
func (h *PreferenceHandler) Get(c *gin.Context) {
|
||||
view, err := h.preferences.Get()
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, view)
|
||||
}
|
||||
|
||||
func (h *PreferenceHandler) Update(c *gin.Context) {
|
||||
var body service.UpdatePreferenceInput
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体格式不正确"})
|
||||
return
|
||||
}
|
||||
|
||||
view, err := h.preferences.Update(body)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, view)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/service"
|
||||
)
|
||||
|
||||
type PromptHandler struct {
|
||||
prompts *service.PromptService
|
||||
}
|
||||
|
||||
func NewPromptHandler(prompts *service.PromptService) *PromptHandler {
|
||||
return &PromptHandler{prompts: prompts}
|
||||
}
|
||||
|
||||
func (h *PromptHandler) List(c *gin.Context) {
|
||||
preferences, err := h.prompts.Preferences()
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"preferences": preferences})
|
||||
}
|
||||
|
||||
func (h *PromptHandler) Customize(c *gin.Context) {
|
||||
var body struct {
|
||||
Mode string `json:"mode"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体格式不正确"})
|
||||
return
|
||||
}
|
||||
|
||||
preference, err := h.prompts.Customize(c.Param("operation"), body.Mode, body.Content)
|
||||
if err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"preference": preference})
|
||||
}
|
||||
|
||||
func (h *PromptHandler) Reset(c *gin.Context) {
|
||||
if err := h.prompts.Reset(c.Param("operation")); err != nil {
|
||||
respondError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"ok": true})
|
||||
}
|
||||
@@ -14,11 +14,13 @@ import (
|
||||
)
|
||||
|
||||
type Deps struct {
|
||||
Canvas *CanvasHandler
|
||||
Task *TaskHandler
|
||||
Event *EventHandler
|
||||
Config config.Config
|
||||
FileDir string
|
||||
Canvas *CanvasHandler
|
||||
Task *TaskHandler
|
||||
Event *EventHandler
|
||||
Preference *PreferenceHandler
|
||||
Prompt *PromptHandler
|
||||
Config config.Config
|
||||
FileDir string
|
||||
}
|
||||
|
||||
func NewRouter(deps Deps) *gin.Engine {
|
||||
@@ -42,6 +44,13 @@ func NewRouter(deps Deps) *gin.Engine {
|
||||
api.GET("/tasks", deps.Task.List)
|
||||
api.POST("/tasks", deps.Task.Create)
|
||||
api.POST("/tasks/:id/cancel", deps.Task.Cancel)
|
||||
|
||||
api.GET("/preferences", deps.Preference.Get)
|
||||
api.PUT("/preferences", deps.Preference.Update)
|
||||
|
||||
api.GET("/prompts", deps.Prompt.List)
|
||||
api.PATCH("/prompts/:operation", deps.Prompt.Customize)
|
||||
api.DELETE("/prompts/:operation", deps.Prompt.Reset)
|
||||
}
|
||||
|
||||
if deps.FileDir != "" {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// PreferenceID 当前没有用户体系,配置与偏好固定为一条全局记录。
|
||||
const PreferenceID = "default"
|
||||
|
||||
// APIKeyConfig 用户自带的模型渠道(BYOK)。
|
||||
// 密钥只落在本机数据库,对外输出时由 service 脱敏,不回传明文。
|
||||
type APIKeyConfig struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Label string `json:"label"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Model string `json:"model"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// Preference 配置与用户偏好。
|
||||
// 提示词定制单独存放,见 model.PromptCustomization 与 internal/prompts。
|
||||
type Preference struct {
|
||||
ID string `gorm:"primaryKey;size:32" json:"id"`
|
||||
APIKeys []APIKeyConfig `gorm:"type:text;serializer:json" json:"apiKeys"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// 提示词定制模式:跟随平台模板 / 在模板后追加要求 / 完全改写。
|
||||
const (
|
||||
PromptModeInherit = "inherit"
|
||||
PromptModeAppend = "append"
|
||||
PromptModeRewrite = "rewrite"
|
||||
)
|
||||
|
||||
// PromptCustomization 用户对某个任务类型提示词的定制。
|
||||
// 平台模板本身内置在 internal/prompts,只有定制需要落库;一个任务类型最多一条。
|
||||
type PromptCustomization struct {
|
||||
ID string `gorm:"primaryKey;size:64" json:"id"`
|
||||
Operation string `gorm:"size:64;not null;uniqueIndex" json:"operation"`
|
||||
Mode string `gorm:"size:16;not null" json:"mode"`
|
||||
Content string `gorm:"type:text" json:"content"`
|
||||
|
||||
// BaseTemplateVersion 定制时依据的平台模板版本,用于判断定制是否已落后于平台更新。
|
||||
BaseTemplateVersion int `json:"baseTemplateVersion"`
|
||||
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// Package prompts 维护平台内置的提示词模板目录。
|
||||
//
|
||||
// 结构与 open-ai-canvas 的 internal/prompts 对齐:
|
||||
// 任务类型(operation)+ 平台默认模板(DefaultContent)+ 用户定制模式(inherit / append / rewrite)。
|
||||
// 本项目暂不提供管理后台,平台模板直接内置在代码里,不落库;落库的只有用户定制。
|
||||
package prompts
|
||||
|
||||
// 内置任务类型。新增或改名时同步维护 web/src/types/prompt.ts。
|
||||
const (
|
||||
OperationTextToImage = "text_to_image"
|
||||
OperationReferenceImage = "reference_image"
|
||||
OperationTextToVideo = "text_to_video"
|
||||
OperationImageToVideo = "image_to_video"
|
||||
OperationTextToAudio = "text_to_audio"
|
||||
OperationPromptEnhance = "prompt_enhance"
|
||||
)
|
||||
|
||||
// TemplateVersion 平台模板版本。**修改任一 DefaultContent 后必须递增**,
|
||||
// 基于旧版本做过定制的用户会在界面上看到「平台模板已更新」提示。
|
||||
const TemplateVersion = 1
|
||||
|
||||
// Variable 模板里可被替换的占位符,供前端提示可用变量。
|
||||
type Variable struct {
|
||||
Label string `json:"label"`
|
||||
Placeholder string `json:"placeholder"`
|
||||
}
|
||||
|
||||
// Definition 一个任务类型的元信息。
|
||||
type Definition struct {
|
||||
Operation string `json:"operation"`
|
||||
Label string `json:"label"`
|
||||
Category string `json:"category"`
|
||||
Description string `json:"description"`
|
||||
OutputType string `json:"outputType"`
|
||||
Variables []Variable `json:"variables"`
|
||||
|
||||
// DefaultContent 平台默认模板,只用于后端组装响应,不随目录整体下发。
|
||||
DefaultContent string `json:"-"`
|
||||
}
|
||||
|
||||
// Definitions 返回全部内置任务类型,顺序即前端展示顺序。
|
||||
func Definitions() []Definition {
|
||||
return []Definition{
|
||||
{
|
||||
Operation: OperationTextToImage,
|
||||
Label: "文生图",
|
||||
Category: "图片",
|
||||
Description: "把文本提示词整理成图片模型的执行提示词。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "主体描述", Placeholder: "{{主体描述}}"},
|
||||
{Label: "画面风格", Placeholder: "{{画面风格}}"},
|
||||
{Label: "构图与镜头", Placeholder: "{{构图与镜头}}"},
|
||||
{Label: "光线与色调", Placeholder: "{{光线与色调}}"},
|
||||
{Label: "负面要求", Placeholder: "{{负面要求}}"},
|
||||
},
|
||||
DefaultContent: `生成一张单一、可执行的画面。只描述静止图像,不写后续运动。明确主体、环境与视觉焦点,写清前中后景关系、遮挡与材质表现,不添加未要求的人物、文字或水印。
|
||||
|
||||
【主体描述】
|
||||
{{主体描述}}
|
||||
|
||||
【画面风格】
|
||||
{{画面风格}}
|
||||
|
||||
【构图与镜头】
|
||||
{{构图与镜头}}
|
||||
|
||||
【光线与色调】
|
||||
{{光线与色调}}
|
||||
|
||||
【负面要求】
|
||||
{{负面要求}}`,
|
||||
},
|
||||
{
|
||||
Operation: OperationReferenceImage,
|
||||
Label: "参考图生成",
|
||||
Category: "图片",
|
||||
Description: "在参考图基础上生成新画面,写清要改什么、要保留什么。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "参考图说明", Placeholder: "{{参考图说明}}"},
|
||||
{Label: "目标修改", Placeholder: "{{目标修改}}"},
|
||||
{Label: "需要保持", Placeholder: "{{需要保持}}"},
|
||||
{Label: "负面要求", Placeholder: "{{负面要求}}"},
|
||||
},
|
||||
DefaultContent: `基于参考图生成新画面。先锁定必须保持不变的部分,再描述需要改变的部分;改动范围之外的构图、身份、服装与材质不要自行改写。
|
||||
|
||||
【参考图说明】
|
||||
{{参考图说明}}
|
||||
|
||||
【目标修改】
|
||||
{{目标修改}}
|
||||
|
||||
【需要保持】
|
||||
{{需要保持}}
|
||||
|
||||
【负面要求】
|
||||
{{负面要求}}`,
|
||||
},
|
||||
{
|
||||
Operation: OperationTextToVideo,
|
||||
Label: "文生视频",
|
||||
Category: "视频",
|
||||
Description: "把文本提示词整理成视频模型的执行提示词。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "主体描述", Placeholder: "{{主体描述}}"},
|
||||
{Label: "镜头运动", Placeholder: "{{镜头运动}}"},
|
||||
{Label: "时间节拍", Placeholder: "{{时间节拍}}"},
|
||||
{Label: "氛围与光线", Placeholder: "{{氛围与光线}}"},
|
||||
{Label: "负面要求", Placeholder: "{{负面要求}}"},
|
||||
},
|
||||
DefaultContent: `生成单一连续镜头。一个镜头只保留一个叙事目标、一个主运镜和一条主要动作链;摄影机运动必须有起点、动机和停止点。优先保证主体身份、关键动作和连续性,次要环境效果可以简化。
|
||||
|
||||
【主体描述】
|
||||
{{主体描述}}
|
||||
|
||||
【镜头运动】
|
||||
{{镜头运动}}
|
||||
|
||||
【时间节拍】
|
||||
{{时间节拍}}
|
||||
|
||||
【氛围与光线】
|
||||
{{氛围与光线}}
|
||||
|
||||
【负面要求】
|
||||
{{负面要求}}`,
|
||||
},
|
||||
{
|
||||
Operation: OperationImageToVideo,
|
||||
Label: "图生视频",
|
||||
Category: "视频",
|
||||
Description: "以首帧图片为起点驱动视频,专注运动与调度。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "首帧说明", Placeholder: "{{首帧说明}}"},
|
||||
{Label: "运动与调度", Placeholder: "{{运动与调度}}"},
|
||||
{Label: "镜头运动", Placeholder: "{{镜头运动}}"},
|
||||
{Label: "时间节拍", Placeholder: "{{时间节拍}}"},
|
||||
{Label: "负面要求", Placeholder: "{{负面要求}}"},
|
||||
},
|
||||
DefaultContent: `以给定首帧为起点生成单一连续镜头。构图、主体身份、服装与光线严格继承首帧,只描述首帧之后的运动与调度,不重新设计画面。
|
||||
|
||||
【首帧说明】
|
||||
{{首帧说明}}
|
||||
|
||||
【运动与调度】
|
||||
{{运动与调度}}
|
||||
|
||||
【镜头运动】
|
||||
{{镜头运动}}
|
||||
|
||||
【时间节拍】
|
||||
{{时间节拍}}
|
||||
|
||||
【负面要求】
|
||||
{{负面要求}}`,
|
||||
},
|
||||
{
|
||||
Operation: OperationTextToAudio,
|
||||
Label: "音频生成",
|
||||
Category: "音频",
|
||||
Description: "把文本整理成配音或音效的生成提示词。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "内容与情绪", Placeholder: "{{内容与情绪}}"},
|
||||
{Label: "音色与语速", Placeholder: "{{音色与语速}}"},
|
||||
{Label: "时长与节奏", Placeholder: "{{时长与节奏}}"},
|
||||
{Label: "负面要求", Placeholder: "{{负面要求}}"},
|
||||
},
|
||||
DefaultContent: `生成一段可直接使用的音频。发音清晰、断句自然,情绪与内容一致,不添加未要求的背景音乐或旁白。
|
||||
|
||||
【内容与情绪】
|
||||
{{内容与情绪}}
|
||||
|
||||
【音色与语速】
|
||||
{{音色与语速}}
|
||||
|
||||
【时长与节奏】
|
||||
{{时长与节奏}}
|
||||
|
||||
【负面要求】
|
||||
{{负面要求}}`,
|
||||
},
|
||||
{
|
||||
Operation: OperationPromptEnhance,
|
||||
Label: "提示词扩写",
|
||||
Category: "通用",
|
||||
Description: "把简短想法扩写为可直接投喂模型的提示词。",
|
||||
OutputType: "text",
|
||||
Variables: []Variable{
|
||||
{Label: "用户原始想法", Placeholder: "{{用户原始想法}}"},
|
||||
{Label: "目标模型", Placeholder: "{{目标模型}}"},
|
||||
{Label: "补充约束", Placeholder: "{{补充约束}}"},
|
||||
},
|
||||
DefaultContent: `你是一位提示词工程师。把用户的简短想法扩写为可直接投喂模型的提示词:保留原意,补齐主体、环境、构图、光线与材质等可执行细节,不添加用户未要求的元素,不解释你的改写过程,只输出提示词本身。
|
||||
|
||||
【用户原始想法】
|
||||
{{用户原始想法}}
|
||||
|
||||
【目标模型】
|
||||
{{目标模型}}
|
||||
|
||||
【补充约束】
|
||||
{{补充约束}}`,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Find 按任务类型查定义。
|
||||
func Find(operation string) (Definition, bool) {
|
||||
for _, definition := range Definitions() {
|
||||
if definition.Operation == operation {
|
||||
return definition, true
|
||||
}
|
||||
}
|
||||
return Definition{}, false
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
type PreferenceRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPreferenceRepository(db *gorm.DB) *PreferenceRepository {
|
||||
return &PreferenceRepository{db: db}
|
||||
}
|
||||
|
||||
// Get 读取全局偏好;尚未配置过时返回一个空骨架,不写入数据库。
|
||||
func (r *PreferenceRepository) Get() (*model.Preference, error) {
|
||||
var preference model.Preference
|
||||
if err := r.db.First(&preference, "id = ?", model.PreferenceID).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return &model.Preference{ID: model.PreferenceID}, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &preference, nil
|
||||
}
|
||||
|
||||
// Save 整条覆盖写入,记录不存在时创建。
|
||||
// CreatedAt 由调用方从旧记录带入,避免更新时被零值覆盖。
|
||||
func (r *PreferenceRepository) Save(preference *model.Preference) error {
|
||||
return r.db.Save(preference).Error
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
type PromptRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewPromptRepository(db *gorm.DB) *PromptRepository {
|
||||
return &PromptRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *PromptRepository) List() ([]model.PromptCustomization, error) {
|
||||
var rows []model.PromptCustomization
|
||||
err := r.db.Order("created_at asc").Find(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
|
||||
func (r *PromptRepository) Get(operation string) (*model.PromptCustomization, error) {
|
||||
var customization model.PromptCustomization
|
||||
if err := r.db.First(&customization, "operation = ?", operation).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &customization, nil
|
||||
}
|
||||
|
||||
// Save 覆盖写入一条定制。调用方需保证同 operation 复用已有 ID,否则会撞唯一索引。
|
||||
func (r *PromptRepository) Save(customization *model.PromptCustomization) error {
|
||||
return r.db.Save(customization).Error
|
||||
}
|
||||
|
||||
func (r *PromptRepository) Delete(operation string) error {
|
||||
result := r.db.Delete(&model.PromptCustomization{}, "operation = ?", operation)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/model"
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/repository"
|
||||
)
|
||||
|
||||
const maxAPIKeyEntries = 20
|
||||
|
||||
// APIKeyView 对外输出的渠道配置,只回传掩码,不含明文密钥。
|
||||
type APIKeyView struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Label string `json:"label"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
Model string `json:"model"`
|
||||
Enabled bool `json:"enabled"`
|
||||
HasKey bool `json:"hasKey"`
|
||||
KeyMask string `json:"keyMask"`
|
||||
}
|
||||
|
||||
// PreferenceView 配置与用户偏好。
|
||||
type PreferenceView struct {
|
||||
APIKeys []APIKeyView `json:"apiKeys"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// APIKeyInput 前端提交的渠道配置。APIKey 留空表示沿用已保存的密钥。
|
||||
type APIKeyInput struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Label string `json:"label"`
|
||||
BaseURL string `json:"baseUrl"`
|
||||
APIKey string `json:"apiKey"`
|
||||
Model string `json:"model"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
type UpdatePreferenceInput struct {
|
||||
APIKeys []APIKeyInput `json:"apiKeys"`
|
||||
}
|
||||
|
||||
type PreferenceService struct {
|
||||
preferences *repository.PreferenceRepository
|
||||
}
|
||||
|
||||
func NewPreferenceService(preferences *repository.PreferenceRepository) *PreferenceService {
|
||||
return &PreferenceService{preferences: preferences}
|
||||
}
|
||||
|
||||
func (s *PreferenceService) Get() (*PreferenceView, error) {
|
||||
preference, err := s.preferences.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toPreferenceView(preference), nil
|
||||
}
|
||||
|
||||
// Update 校验并覆盖保存;未填写密钥的渠道沿用已保存的值。
|
||||
func (s *PreferenceService) Update(input UpdatePreferenceInput) (*PreferenceView, error) {
|
||||
current, err := s.preferences.Get()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
apiKeys, err := mergeAPIKeys(current.APIKeys, input.APIKeys)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
preference := &model.Preference{
|
||||
ID: model.PreferenceID,
|
||||
APIKeys: apiKeys,
|
||||
CreatedAt: current.CreatedAt,
|
||||
}
|
||||
if err := s.preferences.Save(preference); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toPreferenceView(preference), nil
|
||||
}
|
||||
|
||||
func toPreferenceView(preference *model.Preference) *PreferenceView {
|
||||
apiKeys := make([]APIKeyView, 0, len(preference.APIKeys))
|
||||
for _, item := range preference.APIKeys {
|
||||
apiKeys = append(apiKeys, APIKeyView{
|
||||
ID: item.ID,
|
||||
Provider: item.Provider,
|
||||
Label: item.Label,
|
||||
BaseURL: item.BaseURL,
|
||||
Model: item.Model,
|
||||
Enabled: item.Enabled,
|
||||
HasKey: item.APIKey != "",
|
||||
KeyMask: maskSecret(item.APIKey),
|
||||
})
|
||||
}
|
||||
|
||||
return &PreferenceView{
|
||||
APIKeys: apiKeys,
|
||||
UpdatedAt: preference.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func mergeAPIKeys(current []model.APIKeyConfig, inputs []APIKeyInput) ([]model.APIKeyConfig, error) {
|
||||
if len(inputs) > maxAPIKeyEntries {
|
||||
return nil, fmt.Errorf("%w: 渠道数量不能超过 %d 个", ErrInvalidInput, maxAPIKeyEntries)
|
||||
}
|
||||
|
||||
existing := make(map[string]model.APIKeyConfig, len(current))
|
||||
for _, item := range current {
|
||||
existing[item.ID] = item
|
||||
}
|
||||
|
||||
result := make([]model.APIKeyConfig, 0, len(inputs))
|
||||
for _, input := range inputs {
|
||||
provider := strings.TrimSpace(input.Provider)
|
||||
if provider == "" {
|
||||
return nil, fmt.Errorf("%w: 渠道标识不能为空", ErrInvalidInput)
|
||||
}
|
||||
if len(provider) > 64 {
|
||||
return nil, fmt.Errorf("%w: 渠道标识不能超过 64 个字符", ErrInvalidInput)
|
||||
}
|
||||
|
||||
label := strings.TrimSpace(input.Label)
|
||||
if label == "" {
|
||||
label = provider
|
||||
}
|
||||
if len([]rune(label)) > 64 {
|
||||
return nil, fmt.Errorf("%w: 渠道名称不能超过 64 个字符", ErrInvalidInput)
|
||||
}
|
||||
|
||||
baseURL := strings.TrimSpace(input.BaseURL)
|
||||
if baseURL != "" && !isHTTPURL(baseURL) {
|
||||
return nil, fmt.Errorf("%w: Base URL 必须是 http/https 地址", ErrInvalidInput)
|
||||
}
|
||||
|
||||
apiKey := strings.TrimSpace(input.APIKey)
|
||||
if len(apiKey) > 512 {
|
||||
return nil, fmt.Errorf("%w: API Key 长度超出限制", ErrInvalidInput)
|
||||
}
|
||||
|
||||
id := strings.TrimSpace(input.ID)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
if apiKey == "" {
|
||||
if previous, ok := existing[id]; ok {
|
||||
apiKey = previous.APIKey
|
||||
}
|
||||
}
|
||||
|
||||
result = append(result, model.APIKeyConfig{
|
||||
ID: id,
|
||||
Provider: provider,
|
||||
Label: label,
|
||||
BaseURL: baseURL,
|
||||
APIKey: apiKey,
|
||||
Model: strings.TrimSpace(input.Model),
|
||||
Enabled: input.Enabled,
|
||||
})
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// maskSecret 只保留末 4 位,其余用圆点代替。
|
||||
func maskSecret(secret string) string {
|
||||
if secret == "" {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(secret)
|
||||
if len(runes) <= 4 {
|
||||
return strings.Repeat("•", len(runes))
|
||||
}
|
||||
return strings.Repeat("•", 4) + string(runes[len(runes)-4:])
|
||||
}
|
||||
|
||||
func isHTTPURL(raw string) bool {
|
||||
parsed, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != ""
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/model"
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/prompts"
|
||||
"github.com/ttstd/infinite-canvas/backend/internal/repository"
|
||||
)
|
||||
|
||||
const maxPromptContentRunes = 8000
|
||||
|
||||
// PromptTemplateView 平台模板视图。模板内置在代码里,这里给出前端需要的元信息与内容。
|
||||
type PromptTemplateView struct {
|
||||
Operation string `json:"operation"`
|
||||
Name string `json:"name"`
|
||||
Version int `json:"version"`
|
||||
Content string `json:"content"`
|
||||
OutputType string `json:"outputType"`
|
||||
}
|
||||
|
||||
// PromptPreferenceView 一个任务类型的提示词配置,结构对齐 open-ai-canvas 的 UserPromptPreference。
|
||||
type PromptPreferenceView struct {
|
||||
Definition prompts.Definition `json:"definition"`
|
||||
Template *PromptTemplateView `json:"template"`
|
||||
Customization *model.PromptCustomization `json:"customization,omitempty"`
|
||||
Outdated bool `json:"outdated"`
|
||||
}
|
||||
|
||||
type PromptService struct {
|
||||
prompts *repository.PromptRepository
|
||||
}
|
||||
|
||||
func NewPromptService(promptsRepo *repository.PromptRepository) *PromptService {
|
||||
return &PromptService{prompts: promptsRepo}
|
||||
}
|
||||
|
||||
// Preferences 返回全部任务类型及其平台模板与用户定制。
|
||||
func (s *PromptService) Preferences() ([]PromptPreferenceView, error) {
|
||||
rows, err := s.prompts.List()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
byOperation := make(map[string]*model.PromptCustomization, len(rows))
|
||||
for index := range rows {
|
||||
byOperation[rows[index].Operation] = &rows[index]
|
||||
}
|
||||
|
||||
definitions := prompts.Definitions()
|
||||
result := make([]PromptPreferenceView, 0, len(definitions))
|
||||
for _, definition := range definitions {
|
||||
result = append(result, buildPromptPreference(definition, byOperation[definition.Operation]))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// Customize 保存定制。mode=inherit 视为放弃定制,直接删除已有记录。
|
||||
func (s *PromptService) Customize(operation, mode, content string) (*PromptPreferenceView, error) {
|
||||
definition, ok := prompts.Find(operation)
|
||||
if !ok {
|
||||
return nil, repository.ErrNotFound
|
||||
}
|
||||
|
||||
switch strings.TrimSpace(mode) {
|
||||
case model.PromptModeInherit:
|
||||
if err := s.prompts.Delete(operation); err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return nil, err
|
||||
}
|
||||
preference := buildPromptPreference(definition, nil)
|
||||
return &preference, nil
|
||||
case model.PromptModeAppend, model.PromptModeRewrite:
|
||||
default:
|
||||
return nil, fmt.Errorf("%w: 不支持的定制模式", ErrInvalidInput)
|
||||
}
|
||||
|
||||
trimmed := strings.TrimSpace(content)
|
||||
if trimmed == "" {
|
||||
return nil, fmt.Errorf("%w: 请填写个人提示词内容", ErrInvalidInput)
|
||||
}
|
||||
if len([]rune(trimmed)) > maxPromptContentRunes {
|
||||
return nil, fmt.Errorf("%w: 提示词内容不能超过 %d 个字符", ErrInvalidInput, maxPromptContentRunes)
|
||||
}
|
||||
|
||||
customization := &model.PromptCustomization{
|
||||
ID: uuid.NewString(),
|
||||
Operation: operation,
|
||||
Mode: strings.TrimSpace(mode),
|
||||
Content: trimmed,
|
||||
BaseTemplateVersion: prompts.TemplateVersion,
|
||||
}
|
||||
|
||||
// 同一任务类型只保留一条记录:复用原有 ID 与创建时间。
|
||||
existing, err := s.prompts.Get(operation)
|
||||
switch {
|
||||
case err == nil:
|
||||
customization.ID = existing.ID
|
||||
customization.CreatedAt = existing.CreatedAt
|
||||
case errors.Is(err, repository.ErrNotFound):
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := s.prompts.Save(customization); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
preference := buildPromptPreference(definition, customization)
|
||||
return &preference, nil
|
||||
}
|
||||
|
||||
// Reset 恢复平台模板。
|
||||
func (s *PromptService) Reset(operation string) error {
|
||||
if _, ok := prompts.Find(operation); !ok {
|
||||
return repository.ErrNotFound
|
||||
}
|
||||
if err := s.prompts.Delete(operation); err != nil && !errors.Is(err, repository.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildPromptPreference(definition prompts.Definition, customization *model.PromptCustomization) PromptPreferenceView {
|
||||
preference := PromptPreferenceView{
|
||||
Definition: definition,
|
||||
Template: &PromptTemplateView{
|
||||
Operation: definition.Operation,
|
||||
Name: "默认" + definition.Label + "模板",
|
||||
Version: prompts.TemplateVersion,
|
||||
Content: definition.DefaultContent,
|
||||
OutputType: definition.OutputType,
|
||||
},
|
||||
Customization: customization,
|
||||
}
|
||||
if customization != nil {
|
||||
preference.Outdated = customization.BaseTemplateVersion < prompts.TemplateVersion
|
||||
}
|
||||
return preference
|
||||
}
|
||||
Reference in new issue
Block a user