llm

package
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	SceneVideoTitleResolve     = "video.title_resolve"
	SceneVideoSummary          = "video.summary"
	ScenePhotoSearchRewrite    = "photo.search_rewrite"
	ScenePhotoSearchRewriteSig = "photo.search_rewrite_siglip"
	ScenePhotoCaption          = "photo.caption"
	SceneMusicSearchRewrite    = "music.search_rewrite"
	// SceneMusicArtistScrapeJudge 艺人刮削:从多家候选里判断哪位是这位艺人、
	// 每个字段该取哪一家。要跨源比对一致性,比纯改写重,档位 balanced。
	SceneMusicArtistScrapeJudge = "music.artist_scrape_judge"
	SceneComicTagging           = "comic.tagging"
	SceneComicSummary           = "comic.summary"
)

业务场景名常量。命名规则:<服务>.<用途>,与前端场景表一一对应。

View Source
const (
	DefaultMaxOutputTokens = 1024
	DefaultCallTimeoutSecs = 120
	DefaultDailyCallLimit  = 5000
)

成本护栏默认值。挑这几个数字的依据:

  • 输出 1024:业务场景全是短回答,长回答只可能是模型跑飞;
  • 超时 120s:与 provider 的 HTTP 超时一致,够慢模型出结果,又不至于挂死;
  • 每日 5000 次:正常使用(打标签、改搜索词)一天几十到几百次, 5000 是数量级上的安全线,真踩到了说明有东西在循环。

Variables

View Source
var ErrQuotaExceeded = fmt.Errorf("LLM 今日调用次数已达上限")

ErrQuotaExceeded 当日调用次数用尽。调用方应当把它当成"功能暂时不可用"处理, 而不是重试——重试只会继续撞墙。

Functions

func GetPredefinedScenarios

func GetPredefinedScenarios() map[string]*BusinessScenarioConfig

GetPredefinedScenarios 获取预定义的业务场景配置

func ResolveProviderSpecs

func ResolveProviderSpecs(cfg *LLMConfig, shared *ProvidersFileContent) (map[string]*ProviderSpec, map[string]string)

ResolveProviderSpecs 合并"全局凭据"与"服务本地覆盖",得到最终生效的提供商集合。

返回 specs 与 source(global / local)。无法解析或未配置的 provider 也会 出现在结果里(Ready=false + 原因),这样 UI 才能显示"音乐选的 openai 没配", 而不是静默失败。

func SaveProvidersFile

func SaveProvidersFile(path string, content *ProvidersFileContent) error

SaveProvidersFile 原子写入共享凭据文件。

三个约束:0600(文件里是明文 Key)、先备份(用户改错了能回退)、 rename 落盘(避免服务恰好在这时 reload,读到半个文件)。

Types

type BusinessScenarioConfig

type BusinessScenarioConfig struct {
	Name            string            `json:"name"`             // 业务场景名称
	Description     string            `json:"description"`      // 业务场景描述
	DefaultTemplate string            `json:"default_template"` // 默认模板内容
	CustomTemplates map[string]string `json:"custom_templates"` // 自定义模板集合
	ActiveTemplate  string            `json:"active_template"`  // 当前使用的模板key,空表示使用默认模板
	Variables       []string          `json:"variables"`        // 该业务场景支持的变量列表
}

BusinessScenarioConfig 业务场景配置

type ChatOptions

type ChatOptions struct {
	Model       string  `json:"model,omitempty"`
	Temperature float64 `json:"temperature,omitempty"`
	MaxTokens   int     `json:"maxTokens,omitempty"`
}

ChatOptions 聊天选项

type GeminiConfig

type GeminiConfig struct {
	Enable   bool   `json:"enable"`
	APIKey   string `json:"api_key"`
	Model    string `json:"model"`    // 默认模型,如 "gemini-pro"
	Location string `json:"location"` // 用于Vertex AI,可选
	Project  string `json:"project"`  // 用于Vertex AI,可选
}

GeminiConfig Gemini配置

type GeminiProvider

type GeminiProvider struct {
	// contains filtered or unexported fields
}

GeminiProvider Gemini提供商

func NewGeminiProvider

func NewGeminiProvider(ctx context.Context, config *GeminiConfig) (*GeminiProvider, error)

func (*GeminiProvider) Close

func (p *GeminiProvider) Close() error

func (*GeminiProvider) GenerateText

func (p *GeminiProvider) GenerateText(ctx context.Context, prompt string) (string, error)

func (*GeminiProvider) GetProviderName

func (p *GeminiProvider) GetProviderName() string

type LLMClient

type LLMClient interface {
	Chat(messages []Message, options *ChatOptions) (string, error)
	GenerateText(ctx context.Context, prompt string) (string, error)
	// GenerateTextForScene 按业务场景生成文本,场景决定模型(见 SceneXxx 常量)。
	// 传空场景等价于 GenerateText。
	GenerateTextForScene(ctx context.Context, scene, prompt string) (string, error)
}

LLMClient LLM客户端接口

type LLMConfig

type LLMConfig struct {
	Enable         bool            `json:"enable"`
	OpenAI         *OpenAIConfig   `json:"openai,omitempty"`
	Ollama         *OllamaConfig   `json:"ollama,omitempty"`
	Gemini         *GeminiConfig   `json:"gemini,omitempty"`
	Default        string          `json:"default"`                   // 默认使用的LLM提供商: "openai", "ollama", "gemini"
	TemplateConfig *TemplateConfig `json:"template_config,omitempty"` // 模板配置

	// ProvidersFile 全局凭据文件路径。非空且文件存在时,凭据来自该文件,
	// 服务只保存"用谁、用哪个模型";为空则完全退回旧的三段式配置。
	ProvidersFile string `json:"providers_file,omitempty"`
	// Model 服务级默认模型(所有场景共用),空则用提供商的 default_model
	Model string `json:"model,omitempty"`
	// Providers 服务对单个提供商的声明(继承或本地覆盖)
	Providers map[string]*ProviderOverride `json:"providers,omitempty"`
	// Scenes 场景级模型覆盖,key 为场景名(如 comic.tagging)
	Scenes map[string]*SceneSelection `json:"scenes,omitempty"`

	// MaxOutputTokens 单次生成的最大输出 token。不设上限时模型可能一口气吐满上下文,
	// 单次成本不可控;所有业务场景都是"短回答"(几个标签、一句改写),1024 足够。
	MaxOutputTokens int `json:"max_output_tokens,omitempty"`
	// CallTimeoutSeconds 单次上游调用超时。调用方没传 deadline 时兜底,
	// 避免 provider 挂起把批量任务永久卡住。
	CallTimeoutSeconds int `json:"call_timeout_seconds,omitempty"`
	// DailyCallLimit 每日上游调用次数上限(按自然日重置)。超了直接拒绝,
	// 这是"无人值守时把 token 烧光"的最后一道闸。0 表示不限。
	DailyCallLimit int `json:"daily_call_limit,omitempty"`
}

LLMConfig LLM插件配置

func LoadConfig

func LoadConfig(mgr *viper.Viper) *LLMConfig

LoadConfig 从 viper 读取完整配置。 OnInit 与 ReloadConfig 共用这一处,避免两边字段漏读(历史上就是这样漏掉 template_config 的,导致场景配置重启即丢)。

func (*LLMConfig) EffectiveCallTimeout added in v0.3.0

func (c *LLMConfig) EffectiveCallTimeout() time.Duration

func (*LLMConfig) EffectiveDailyCallLimit added in v0.3.0

func (c *LLMConfig) EffectiveDailyCallLimit() int

func (*LLMConfig) EffectiveMaxOutputTokens added in v0.3.0

func (c *LLMConfig) EffectiveMaxOutputTokens() int

生效值:配置里写了就用配置,没写用默认。

type LLMPlugin

type LLMPlugin struct {
	Config *LLMConfig
	// contains filtered or unexported fields
}

LLMPlugin LLM插件

func NewPlugin

func NewPlugin() *LLMPlugin

NewPlugin 创建新的LLM插件实例

func (*LLMPlugin) ApplyUpdate

func (p *LLMPlugin) ApplyUpdate(req *UpdateRequest) error

ApplyUpdate 把局部修改合并进当前配置并(可选)落盘。

func (*LLMPlugin) Close

func (p *LLMPlugin) Close() error

Close 关闭插件,清理资源

func (*LLMPlugin) ConfigPayload

func (p *LLMPlugin) ConfigPayload() map[string]any

ConfigPayload 构造 /llm/config 的响应体。

凭据只暴露 has_key,不回传 api_key——设置页没有任何地方需要看到明文, 看到明文只会让浏览器历史/日志多一份泄漏面。

func (*LLMPlugin) GenerateText

func (p *LLMPlugin) GenerateText(ctx context.Context, prompt string) (string, error)

GenerateText 生成文本(使用默认提供商与服务级默认模型)

func (*LLMPlugin) GenerateTextForScene

func (p *LLMPlugin) GenerateTextForScene(ctx context.Context, scene, prompt string) (string, error)

GenerateTextForScene 按业务场景生成文本。

模型解析顺序:scene.model → service.model → provider.default_model。 场景为空等价于"用服务级默认",所以老调用点不改也能工作。

func (*LLMPlugin) GenerateTextWithProvider

func (p *LLMPlugin) GenerateTextWithProvider(ctx context.Context, prompt string, providerName string) (string, error)

GenerateTextWithProvider 使用指定提供商生成文本(模型用该提供商默认)

func (*LLMPlugin) GetAvailableProviders

func (p *LLMPlugin) GetAvailableProviders() []string

GetAvailableProviders 获取可用的提供商列表

func (*LLMPlugin) GetAvailableScenarios

func (p *LLMPlugin) GetAvailableScenarios() []string

GetAvailableScenarios 获取所有可用的业务场景

func (*LLMPlugin) GetClient

func (p *LLMPlugin) GetClient() (LLMClient, error)

GetClient 获取LLM客户端

func (*LLMPlugin) GetCurrentConfig

func (p *LLMPlugin) GetCurrentConfig() *LLMConfig

GetCurrentConfig 获取当前配置的副本

func (*LLMPlugin) GetDefaultProvider

func (p *LLMPlugin) GetDefaultProvider() string

GetDefaultProvider 获取默认提供商名称

func (*LLMPlugin) GetPluginConfig

func (p *LLMPlugin) GetPluginConfig() map[string]interface{}

GetPluginConfig 获取插件配置

func (*LLMPlugin) GetResolvedProviders

func (p *LLMPlugin) GetResolvedProviders() []ResolvedProvider

GetResolvedProviders 返回提供商现状(含来源与不可用原因),供管理接口展示。

func (*LLMPlugin) GetResolvedScenes

func (p *LLMPlugin) GetResolvedScenes() []SceneInfo

GetResolvedScenes 返回场景 → 模型现状(含来源),供设置页展示。

func (*LLMPlugin) GetScenarioInfo

func (p *LLMPlugin) GetScenarioInfo(scenarioName string) (*BusinessScenarioConfig, error)

GetScenarioInfo 获取业务场景的详细信息

func (*LLMPlugin) GetTemplate

func (p *LLMPlugin) GetTemplate(scenarioName string) (string, error)

GetTemplate 根据业务场景获取当前使用的模板 scenarioName: 业务场景名称 返回模板内容

func (*LLMPlugin) ListProviderModels

func (p *LLMPlugin) ListProviderModels(ctx context.Context, providerID string) ([]ModelSpec, string, error)

ListProviderModels 读取某个提供商实际可用的模型;先问上游,失败时退回配置的候选。

func (*LLMPlugin) OnInit

func (p *LLMPlugin) OnInit(e *harukap.HarukaAppEngine) error

OnInit 初始化插件

func (*LLMPlugin) ReloadConfig

func (p *LLMPlugin) ReloadConfig() error

ReloadConfig 从配置文件重新加载配置

func (*LLMPlugin) ReloadConfigWithPersistence

func (p *LLMPlugin) ReloadConfigWithPersistence(persist bool) error

ReloadConfigWithPersistence 从配置文件重新加载配置,可选择是否在重新加载后立即保存(用于配置规范化)

func (*LLMPlugin) RenderTemplate

func (p *LLMPlugin) RenderTemplate(scenarioName string, variables map[string]string) (string, error)

RenderTemplate 根据业务场景渲染模板 scenarioName: 业务场景名称 variables: 模板变量映射 返回渲染后的文本

func (*LLMPlugin) ResolveSceneModel

func (p *LLMPlugin) ResolveSceneModel(scene string) (string, string)

ResolveSceneModel 计算指定场景最终使用的模型与来源。

func (*LLMPlugin) SaveConfig

func (p *LLMPlugin) SaveConfig() error

SaveConfig 保存当前配置到配置文件

func (*LLMPlugin) SetConfig

func (p *LLMPlugin) SetConfig(config LLMConfig)

SetConfig 设置配置

func (*LLMPlugin) StatusPayload

func (p *LLMPlugin) StatusPayload() map[string]any

StatusPayload 构造 /llm/status 的响应体。

func (*LLMPlugin) UpdateAndSaveConfig

func (p *LLMPlugin) UpdateAndSaveConfig(newConfig *LLMConfig) error

UpdateAndSaveConfig 更新配置并持久化到配置文件

func (*LLMPlugin) UpdateConfig

func (p *LLMPlugin) UpdateConfig(newConfig *LLMConfig) error

UpdateConfig 动态更新配置

func (*LLMPlugin) UpdateConfigWithPersistence

func (p *LLMPlugin) UpdateConfigWithPersistence(newConfig *LLMConfig, persist bool) error

UpdateConfigWithPersistence 动态更新配置,可选择是否持久化

type LLMProvider

type LLMProvider interface {
	GenerateText(ctx context.Context, prompt string) (string, error)
	GetProviderName() string
}

LLMProvider LLM提供商接口

func BuildProvider

func BuildProvider(ctx context.Context, spec *ProviderSpec) (LLMProvider, error)

BuildProvider 根据 spec 构造提供商实例。

type Message

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

Message 聊天消息

type ModelAwareProvider

type ModelAwareProvider interface {
	LLMProvider
	GenerateTextWithModel(ctx context.Context, model, prompt string) (string, error)
}

ModelAwareProvider 支持"按次指定模型"的提供商。

借鉴 Bifrost 的做法:核心接口保持最小(LLMProvider 只有 GenerateText), 额外能力用可选接口 + 类型断言暴露,避免一上来就定义 60 个方法, 也保证老的实现不需要改动就能继续工作。

type ModelLister

type ModelLister interface {
	ListModels(ctx context.Context) ([]ModelSpec, error)
}

ModelLister 能向用户报告"这台上游实际有哪些模型"。 借鉴 one-api 的 GetModelList 与 Bifrost 的 ListModels: 模型列表属于提供商自己的能力,不该由前端硬编码。

type ModelSpec

type ModelSpec struct {
	ID    string `json:"id" yaml:"id"`
	Label string `json:"label,omitempty" yaml:"label,omitempty"`
	Tier  string `json:"tier,omitempty" yaml:"tier,omitempty"`
}

ModelSpec 一个可选模型。 Tier 用于"小白不配也能得到合理默认":fast / balanced / quality。

type OllamaConfig

type OllamaConfig struct {
	Enable  bool   `json:"enable"`
	BaseURL string `json:"base_url"` // Ollama服务地址,如 "http://localhost:11434"
	Model   string `json:"model"`    // 默认模型,如 "llama2"
}

OllamaConfig Ollama配置

type OllamaProvider

type OllamaProvider struct {
	// contains filtered or unexported fields
}

OllamaProvider Ollama提供商

func NewOllamaProvider

func NewOllamaProvider(config *OllamaConfig) *OllamaProvider

func (*OllamaProvider) GenerateText

func (p *OllamaProvider) GenerateText(ctx context.Context, prompt string) (string, error)

func (*OllamaProvider) GetProviderName

func (p *OllamaProvider) GetProviderName() string

type OpenAIConfig

type OpenAIConfig struct {
	Enable  bool   `json:"enable"`
	APIKey  string `json:"api_key"`
	BaseURL string `json:"base_url,omitempty"` // 可选,用于支持OpenAI兼容的API
	Model   string `json:"model"`              // 默认模型,如 "gpt-3.5-turbo"
}

OpenAIConfig OpenAI配置

type OpenAIProvider

type OpenAIProvider struct {
	// contains filtered or unexported fields
}

OpenAIProvider OpenAI提供商

func NewOpenAIProvider

func NewOpenAIProvider(config *OpenAIConfig) *OpenAIProvider

func (*OpenAIProvider) GenerateText

func (p *OpenAIProvider) GenerateText(ctx context.Context, prompt string) (string, error)

func (*OpenAIProvider) GetProviderName

func (p *OpenAIProvider) GetProviderName() string

type ProviderKind

type ProviderKind string

ProviderKind 决定与上游通信使用哪种协议。

借鉴 one-api 的结论:几乎所有厂商都提供 OpenAI 兼容端点(DeepSeek、通义、 Kimi、智谱、硅基流动、OpenRouter、vLLM、one-api/new-api 自身……), 所以只要有 openai-compatible 这一种,就能接住绝大多数上游; 只有 Gemini 的原生 SDK(尤其 Vertex 鉴权)和 Ollama 的原生 /api/generate 需要单独实现。新增厂商 = 新增一条配置,不需要写代码。

const (
	// KindOpenAICompatible 任何 OpenAI 兼容端点(含自建中转)
	KindOpenAICompatible ProviderKind = "openai-compatible"
	// KindOllama Ollama 原生协议
	KindOllama ProviderKind = "ollama"
	// KindGemini Gemini Developer API 或 Vertex AI
	KindGemini ProviderKind = "gemini"
	// KindAnthropic Anthropic Messages 协议(Claude 原生,以及 MiniMax / 智谱 / Kimi
	// 提供的 /anthropic 兼容端点)
	KindAnthropic ProviderKind = "anthropic"
)

type ProviderOverride

type ProviderOverride struct {
	Mode         string `json:"mode" yaml:"mode"`
	ProviderSpec `yaml:",inline"`
}

ProviderOverride 服务本地对某个提供商的声明。 Mode=inherit(默认)表示用全局那份;Mode=override 表示整段使用本地字段。

设计红线:**不做字段级合并**。"继承 base_url 但自己填 key" 会造出 看起来配了、实际连不通的配置,这类谜题比多填几个字段更贵。

func (*ProviderOverride) IsOverride

func (o *ProviderOverride) IsOverride() bool

IsOverride 判断是否使用了本地自定义凭据。

type ProviderPreset

type ProviderPreset struct {
	ID      string       `json:"id"`
	Label   string       `json:"label"`
	Kind    ProviderKind `json:"kind"`
	BaseURL string       `json:"base_url,omitempty"`
	// Region cn | global | gateway | local,前端按此分组
	Region string `json:"region"`
	// Doc 官方文档 / 控制台地址,方便查 Key 在哪申请
	Doc string `json:"doc,omitempty"`
	// Note 一句话提示:特殊鉴权、模型 ID 规则、需要额外字段等
	Note string `json:"note,omitempty"`
	// DefaultModel 选中模板时预填的模型(本家 + 均衡档 + 非实验版)
	DefaultModel string      `json:"default_model,omitempty"`
	Models       []ModelSpec `json:"models,omitempty"`
}

内置提供商目录:来自 models.dev 的公开清单(opencode / Crush 等工具用的同一份数据), 国内几家按各自官网文档补上兼容端点。

为什么要这张表:几乎所有厂商都提供 OpenAI 兼容端点,接一家实际上只是 "填对 base_url + 模型名"。让用户从零背这些地址是纯粹的浪费——选一家, 地址和候选模型自动填好,他只需要粘一个 Key。

这个文件由 presets_gen.py 生成,不要直接改;要改请改脚本再重新生成。

维护约定:

  • BaseURL 只到版本段(/v1、/v2、/v3、/compatible-mode/v1),不带具体资源路径
  • Models 只是候选,真实可用列表以「读取模型」问上游为准
  • 地址会随厂商变动,限制条件写进 Note,别让用户以为是我们的 bug

func ProviderPresets

func ProviderPresets() []ProviderPreset

ProviderPresets 返回全部内置预设(副本,调用方可安全修改)。

type ProviderSpec

type ProviderSpec struct {
	ID       string            `json:"id" yaml:"-"`
	Kind     ProviderKind      `json:"kind" yaml:"kind"`
	Label    string            `json:"label,omitempty" yaml:"label,omitempty"`
	Enable   bool              `json:"enable" yaml:"enable"`
	BaseURL  string            `json:"base_url,omitempty" yaml:"base_url,omitempty"`
	APIKey   string            `json:"api_key,omitempty" yaml:"api_key,omitempty"`
	Project  string            `json:"project,omitempty" yaml:"project,omitempty"`
	Location string            `json:"location,omitempty" yaml:"location,omitempty"`
	Headers  map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
	Timeout  int               `json:"timeout,omitempty" yaml:"timeout,omitempty"`
	// MaxTokens 单次生成的最大输出 token。0 表示用插件级默认(见 LLMConfig.EffectiveMaxOutputTokens)。
	// 这里不设上限时模型会一路吐到上下文尽头,单次成本完全不可控。
	MaxTokens int `json:"max_tokens,omitempty" yaml:"max_tokens,omitempty"`
	// ExtraBody 原样合并进请求体(OpenAI 兼容上游专有字段的通用出口)。
	// 典型用法是关掉思考:extra_body: {thinking: {type: disabled}}。
	// 走请求体改写而不是 SDK 字段,是因为各家关思考的参数名不统一
	// (thinking / reasoning_effort / enable_thinking / chat_template_kwargs),
	// SDK 不可能穷举,写死任何一个都会绑死某一家。
	ExtraBody map[string]interface{} `json:"extra_body,omitempty" yaml:"extra_body,omitempty"`
	// DefaultModel 该提供商未指定模型时使用
	DefaultModel string      `json:"default_model,omitempty" yaml:"default_model,omitempty"`
	Models       []ModelSpec `json:"models,omitempty" yaml:"models,omitempty"`
}

ProviderSpec 一个提供商的完整描述(凭据 + 端点 + 模型)。 它同时是"全局凭据文件"和"服务本地覆盖"的唯一数据形态, 这样继承与覆盖只是"用哪一份 spec",不涉及字段级合并。

func (*ProviderSpec) Normalize

func (s *ProviderSpec) Normalize()

Normalize 补全默认值,使"人写的配置"和"代码期望的配置"一致。

func (*ProviderSpec) Ready

func (s *ProviderSpec) Ready() (bool, string)

Ready 判断凭据是否足以发起调用,并给出**可读的原因**。 设计红线:不可用必须显式说明原因,不允许静默回退到别的配置。

type ProvidersFileContent

type ProvidersFileContent struct {
	Version int `yaml:"version" json:"version"`
	// Providers 的 key 即 provider id(deepseek / gemini / ollama / newapi…)
	Providers map[string]*ProviderSpec `yaml:"providers" json:"providers"`
}

ProvidersFileContent 全局凭据文件的结构。

func LoadProvidersFile

func LoadProvidersFile(path string) (*ProvidersFileContent, error)

LoadProvidersFile 读取全局凭据文件。文件不存在时返回 nil 且不报错, 这样"没有这条路"能干净地退化回旧行为,而不是让服务起不来。

type ResolvedProvider

type ResolvedProvider struct {
	ID           string       `json:"id"`
	Kind         ProviderKind `json:"kind"`
	Label        string       `json:"label,omitempty"`
	Source       string       `json:"source"` // global | local | legacy | missing
	Ready        bool         `json:"ready"`
	Reason       string       `json:"reason,omitempty"`
	DefaultModel string       `json:"default_model,omitempty"`
	Models       []ModelSpec  `json:"models,omitempty"`
	HasKey       bool         `json:"has_key"`
}

ResolvedProvider 暴露给管理接口的提供商现状。

func DescribeProviders

func DescribeProviders(specs map[string]*ProviderSpec, sources map[string]string) []ResolvedProvider

DescribeProviders 生成稳定的(按 id 排序的)现状列表。

type SceneInfo

type SceneInfo struct {
	SceneSpec
	// Model 实际会用的模型(空表示没解析出来,调用会退回提供商默认)
	Model string `json:"model"`
	// Source 模型来源:scene | service | provider | tier | none
	Source string `json:"source"`
	// Overridden 用户是否显式给这个场景选了模型
	Overridden bool `json:"overridden"`
}

SceneInfo 是场景的运行时状态,供管理接口返回。

func DescribeScenes

func DescribeScenes(cfg *LLMConfig, specs map[string]*ProviderSpec) []SceneInfo

DescribeScenes 返回全部场景的运行状态。

只返回内置场景:用户配了但代码里没人调的场景(拼错 id)显示出来只会误导人, 所以额外收集 cfg.Scenes 里"没有对应调用点"的 id 单独标记出来。

type SceneSelection

type SceneSelection struct {
	Model string `json:"model,omitempty" yaml:"model,omitempty"`
}

SceneSelection 单个业务场景的模型覆盖。 只允许覆盖 model:换提供商意味着换凭据/计费,属于服务级决策。

type SceneSpec

type SceneSpec struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Service     string `json:"service"`
	Tier        string `json:"tier"`
}

场景表:代码里每个 LLM 调用点都对应一个场景 id。

为什么要有这张表:调用点写死了 prompt,但"用哪个模型"是运维决策。 把 id 暴露出来,前端才能给每个场景单独选模型;不做这张表的话,用户只能 全局换模型,改一处小任务也会把大任务一起换掉。

档位(Tier)只用于"用户没选"时挑默认模型:

fast      —— 短文本、高并发(搜索改写、打标签)
balanced  —— 默认
quality   —— 长文本推理(摘要、识别)

func BuiltinScenes

func BuiltinScenes() []SceneSpec

BuiltinScenes 返回全部内置场景(副本,调用方可安全修改)。

type TemplateConfig

type TemplateConfig struct {
	BusinessScenarios map[string]*BusinessScenarioConfig `json:"business_scenarios"` // 业务场景配置
	DefaultScenario   string                             `json:"default_scenario"`   // 默认业务场景
}

TemplateConfig 模板配置

func (*TemplateConfig) GetAvailableScenarios

func (tc *TemplateConfig) GetAvailableScenarios() []string

GetAvailableScenarios 获取所有可用的业务场景

func (*TemplateConfig) GetTemplate

func (tc *TemplateConfig) GetTemplate(scenario string) (string, error)

GetTemplate 获取指定业务场景的当前模板

func (*TemplateConfig) InitializeWithPredefinedScenarios

func (tc *TemplateConfig) InitializeWithPredefinedScenarios()

InitializeWithPredefinedScenarios 使用预定义场景初始化模板配置

func (*TemplateConfig) RenderTemplate

func (tc *TemplateConfig) RenderTemplate(scenario string, variables map[string]string) (string, error)

RenderTemplate 渲染模板,将{{变量名}}替换为实际值

type UpdateRequest

type UpdateRequest struct {
	Enable        *bool                        `json:"enable,omitempty"`
	Default       *string                      `json:"default,omitempty"`
	Model         *string                      `json:"model,omitempty"`
	ProvidersFile *string                      `json:"providers_file,omitempty"`
	Providers     map[string]*ProviderOverride `json:"providers,omitempty"`
	Scenes        map[string]*SceneSelection   `json:"scenes,omitempty"`

	// 成本护栏(缺省即不改)
	MaxOutputTokens    *int `json:"max_output_tokens,omitempty"`
	CallTimeoutSeconds *int `json:"call_timeout_seconds,omitempty"`
	DailyCallLimit     *int `json:"daily_call_limit,omitempty"`

	// 旧三段式(兼容老前端)
	OpenAI *OpenAIConfig `json:"openai,omitempty"`
	Ollama *OllamaConfig `json:"ollama,omitempty"`
	Gemini *GeminiConfig `json:"gemini,omitempty"`

	Persist bool `json:"persist,omitempty"`
}

UpdateRequest 是 PUT /llm/config 的请求体。

全部用指针:设置页是"局部编辑",缺字段必须表示"别动"。 老实现直接 new 一个 LLMConfig 覆盖,导致任何一次保存都会把场景配置抹掉。

type UsageSnapshot added in v0.3.0

type UsageSnapshot struct {
	Day        string         `json:"day"`
	Calls      int            `json:"calls"`
	Failed     int            `json:"failed"`
	Limit      int            `json:"limit"`     // 0 表示不限
	Remaining  int            `json:"remaining"` // -1 表示不限
	ByScene    map[string]int `json:"by_scene"`  // 场景 → 次数
	ByProvider map[string]int `json:"by_provider"`
	ResetsAt   string         `json:"resets_at"` // 次日零点(本地时区)
}

UsageSnapshot 是 /llm/status 暴露给前端的用量视图。

为什么不记 token 而记调用次数:token 数只有部分上游会在响应里返回, OpenAI/Gemini/Ollama 口径不一致,拿到也是估算;调用次数是本地可以精确统计的, 而且"上限次数的调用"和"上限 token"在业务上等价——每个场景的 prompt 长度基本恒定。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL