feat(persona,model,loop): 人格 thinking 配置 + 5 个死字段接线 + 推理旋钮(按 provider 映射)
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

按 DevDocs/design/01 §2.1/§2.2 与 design/04 §3.2 实现(规格含联网核过的官方依据:思考内容刻意不角色化、不写分步思考指令、思考控制只走参数级)。
- 人格 schema 新增 thinking:budgetTokens / effort / showToUser(*bool,省略=nil=保持现行为,显式 false=只落库) / mode(default|on|off→Enable 三态);非法 mode/负预算 → ErrInvalidThinking(不静默)
- 5 个死字段接上注入:personality→values→speechStyle→catchphrase→background 拼为独立段落(带【】小标题,空值不拼);**全空时输出与旧实现逐字节一致**(有专门测试)
- model.Request 新增 Thinking{ BudgetTokens, Enable } 与 ReasoningEffort;新增 model/reasoning.go:厂商识别(模型名→baseURL 兜底)、取值白名单(OpenAI 系 none…max / DeepSeek low|high|max)、非法值降级+WARN、**不支持一律 WARN 而非静默**;Anthropic 映射 thinking{budget_tokens} 并**保证 budget<max_tokens**(不足时抬高 max_tokens+WARN,正是历史上思考吃光预算→空回复那个坑)
- loop:新增 Options.ThinkingShowToUser(*bool) 仅门控 thinking_* 帧(正文/工具帧不受影响);场景级 mute 语义不变
- 补一处任务清单外但必需的接线:persona→model.Request 的 thinking 映射(否则 budget/effort/mode 会变成新的死字段);showToUser 刻意不产生 Thinking(纯呈现开关)
- 管理端:personaUpsertRequest 补 thinking DTO + 校验(400);PUT 省略时**保留已存块**(防旧客户端抹配置);写侧 yaml round-trip 已验证
- Docs/api-client v0.40→v0.41(可选请求字段)
- 测试:26 个新用例(loader 解析/拼接逐字节/映射、anthropic 非流式+流式预算约束、openai 透传/降级/丢弃、Qwen 诚实 WARN、loop 门控、DTO round-trip);3 次变异验证(省略与 false 混同 / 去掉预算约束 / 短路门控 各自 FAIL)
- 验收:go build/vet/test 全绿(含 57 包)+ linux/darwin 交叉编译 + 前端 build;唯一 FAIL 是既有 flake TestInterruptCancelsTurnAndClearsPending(3/20 新代码 vs 3/20 纯 HEAD,已归因非本次引入)
This commit is contained in:
AskaEth committed 2026-10-03 19:54:22 +08:00
1 parent e4e18ce2a2
commit 38a403afca
22 files changed
+1714 -56

No files matched your search

+3
View File
@@ -80,6 +80,9 @@ func (p *Persona) validate() error {
if len(missing) > 0 {
return fmt.Errorf("%w %q: %s", ErrRequiredField, p.ID, strings.Join(missing, ", "))
}
if err := p.ValidateThinking(); err != nil {
return err
}
return nil
}
+78 -1
View File
@@ -5,6 +5,9 @@
package loader
import (
"errors"
"fmt"
"git.yeij.top/AskaEth/Cyrene_v2/internal/persona/emotion"
)
@@ -17,6 +20,22 @@ const (
defaultAffectionDelta = 5
)
// Thinking-move values accepted by ThinkingParams.Mode (design/01 §2.1). The
// empty string is equivalent to ThinkingModeDefault.
const (
// ThinkingModeDefault leaves the provider's own reasoning behavior alone.
ThinkingModeDefault = "default"
// ThinkingModeOn explicitly enables reasoning where the provider has a switch.
ThinkingModeOn = "on"
// ThinkingModeOff explicitly disables reasoning where the provider has a switch.
ThinkingModeOff = "off"
)
// ErrInvalidThinking is wrapped by the thinking-config validation error so a
// caller can detect a bad `thinking` block (unknown mode, negative budget)
// instead of seeing it silently ignored.
var ErrInvalidThinking = errors.New("persona: invalid thinking config")
// defaultMemoryNS is the namespace prefix used when a persona omits a concrete
// memory namespace; the full namespace becomes prefix + "." + persona id.
const defaultMemoryNS = "persona"
@@ -50,6 +69,45 @@ type AffectionParams struct {
Delta int `yaml:"delta"`
}
// ThinkingParams is the persona's optional `thinking` section (design/01 §2.1).
// It describes presentation/resource knobs only — never an ability bound — and
// defaults are chosen so an absent section changes nothing. It is marshaled by
// the admin persona write path, so every field is omitempty: a persona that
// configures no thinking gets no `thinking:` key in its YAML.
type ThinkingParams struct {
// BudgetTokens is the reasoning budget (Anthropic thinking.budget_tokens; the
// official semantic is a target, not a hard cap). Zero = unset.
BudgetTokens int `yaml:"budgetTokens,omitempty"`
// Effort is the OpenAI-compatible reasoning strength (reasoning_effort). The
// accepted values depend on the provider; the model layer validates them
// against its per-provider whitelist (design/04 §3.2).
Effort string `yaml:"effort,omitempty"`
// ShowToUser says whether streamed thinking frames are pushed to the client.
// It is a POINTER on purpose: a missing key means "keep the current behavior"
// (thinking frames are shown), while an explicit false means "store it, but
// do not push it". A plain bool would conflate "unset" with "off".
ShowToUser *bool `yaml:"showToUser,omitempty"`
// Mode is the explicit hard switch: default | on | off. Empty = default.
Mode string `yaml:"mode,omitempty"`
}
// Enable maps Mode onto the model layer's tri-state switch: "on" → true, "off" →
// false, ""/"default" → nil (no explicit switch, leave it to the provider). The
// reasoning knobs the model layer consumes never include a null switch, so
// "default" cannot accidentally turn provider thinking on.
func (t ThinkingParams) Enable() *bool {
switch t.Mode {
case ThinkingModeOn:
v := true
return &v
case ThinkingModeOff:
v := false
return &v
default:
return nil
}
}
// Persona is a loaded persona definition. It describes who a character is (the
// identity, personality, speech style, catchphrase, background, values) and
// never restricts what that character can do.
@@ -85,7 +143,10 @@ type Persona struct {
Values []string `yaml:"values"`
Emotion EmotionParams `yaml:"emotion"`
Affection AffectionParams `yaml:"affection"`
Visual PersonaVisual `yaml:"visual,omitempty"`
// Thinking is the optional reasoning/presentation config (design/01 §2.1);
// omitted when the persona configures none, so no existing YAML gains noise.
Thinking ThinkingParams `yaml:"thinking,omitempty"`
Visual PersonaVisual `yaml:"visual,omitempty"`
// TriggerWords are the role-name words that, when a public-platform group
// message mentions one, route the message into the participation PROBING
// stage even without a direct @ (design/18 §2 触发②). Each persona defines its
@@ -143,3 +204,19 @@ func (p *Persona) AffectionStep() int {
}
return defaultAffectionDelta
}
// ValidateThinking checks the optional `thinking` section and returns a
// %w-wrapped ErrInvalidThinking error for an unrecognized mode or a negative
// budget, so a bad value is reported instead of silently ignored.
func (p *Persona) ValidateThinking() error {
switch p.Thinking.Mode {
case "", ThinkingModeDefault, ThinkingModeOn, ThinkingModeOff:
default:
return fmt.Errorf("%w: mode %q (want %s|%s|%s)",
ErrInvalidThinking, p.Thinking.Mode, ThinkingModeDefault, ThinkingModeOn, ThinkingModeOff)
}
if p.Thinking.BudgetTokens < 0 {
return fmt.Errorf("%w: budgetTokens %d must not be negative", ErrInvalidThinking, p.Thinking.BudgetTokens)
}
return nil
}
+161
View File
@@ -0,0 +1,161 @@
package loader
import (
"errors"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
// thinkingPersonaYAML builds a minimal valid persona with an extra `thinking`
// block appended verbatim (an empty extra means "no thinking section at all").
func thinkingPersonaYAML(extra string) string {
return "id: xilian\nname: 昔涟\ncharacterRef: c\nidentity:\n role: r\n systemPrompt: s\n" + extra
}
// TestLoad_ThinkingAbsentKeepsCurrentBehavior locks the "optional section"
// promise: without a `thinking` key every field stays at its zero value, the
// showToUser pointer stays nil (the distinction the design calls out) and
// re-marshaling the persona does NOT emit a thinking block, so the admin write
// path cannot add noise to an existing persona file.
func TestLoad_ThinkingAbsentKeepsCurrentBehavior(t *testing.T) {
t.Parallel()
path := writeFile(t, t.TempDir(), "xilian.yaml", thinkingPersonaYAML(""))
p, err := Load(path)
if err != nil {
t.Fatalf("Load() error: %v", err)
}
if p.Thinking.BudgetTokens != 0 || p.Thinking.Effort != "" || p.Thinking.Mode != "" {
t.Fatalf("Thinking = %+v, want the zero value", p.Thinking)
}
if p.Thinking.ShowToUser != nil {
t.Fatalf("ShowToUser = %v, want nil (unset)", *p.Thinking.ShowToUser)
}
if p.Thinking.Enable() != nil {
t.Fatalf("Enable() = %v, want nil for an unset mode", *p.Thinking.Enable())
}
out, err := yaml.Marshal(p)
if err != nil {
t.Fatalf("Marshal() error: %v", err)
}
if strings.Contains(string(out), "thinking") {
t.Fatalf("marshal emitted a thinking block for an unset section:\n%s", out)
}
}
// TestLoad_ThinkingParsed asserts the documented YAML keys land on the struct.
func TestLoad_ThinkingParsed(t *testing.T) {
t.Parallel()
yaml := thinkingPersonaYAML("thinking:\n budgetTokens: 4096\n effort: medium\n showToUser: false\n mode: on\n")
path := writeFile(t, t.TempDir(), "xilian.yaml", yaml)
p, err := Load(path)
if err != nil {
t.Fatalf("Load() error: %v", err)
}
if p.Thinking.BudgetTokens != 4096 {
t.Errorf("BudgetTokens = %d, want 4096", p.Thinking.BudgetTokens)
}
if p.Thinking.Effort != "medium" {
t.Errorf("Effort = %q, want medium", p.Thinking.Effort)
}
if p.Thinking.Mode != ThinkingModeOn {
t.Errorf("Mode = %q, want on", p.Thinking.Mode)
}
if p.Thinking.ShowToUser == nil {
t.Fatal("ShowToUser = nil, want an explicit false")
}
if *p.Thinking.ShowToUser {
t.Error("ShowToUser = true, want false")
}
if en := p.Thinking.Enable(); en == nil || !*en {
t.Fatalf("Enable() = %v, want true for mode=on", en)
}
}
// TestLoad_ThinkingShowToUserFalseDiffersFromOmitted is the pointer contract:
// omitting the key must keep the current behavior (nil, frames are shown) while
// an explicit false must be distinguishable from it (store, don't push). A plain
// bool field would collapse both into false and fail here.
func TestLoad_ThinkingShowToUserFalseDiffersFromOmitted(t *testing.T) {
t.Parallel()
dir := t.TempDir()
omitted, err := Load(writeFile(t, dir, "omitted.yaml", thinkingPersonaYAML("thinking:\n budgetTokens: 1024\n")))
if err != nil {
t.Fatalf("Load(omitted) error: %v", err)
}
off, err := Load(writeFile(t, dir, "off.yaml", thinkingPersonaYAML("thinking:\n showToUser: false\n")))
if err != nil {
t.Fatalf("Load(off) error: %v", err)
}
if omitted.Thinking.ShowToUser != nil {
t.Fatalf("omitted ShowToUser = %v, want nil", *omitted.Thinking.ShowToUser)
}
if off.Thinking.ShowToUser == nil {
t.Fatal("explicit false ShowToUser = nil, want a pointer to false")
}
if *off.Thinking.ShowToUser {
t.Fatal("explicit false ShowToUser = true")
}
}
// TestLoad_ThinkingInvalidModeRejected asserts a bad mode is reported with its
// own identifiable error instead of being silently ignored.
func TestLoad_ThinkingInvalidModeRejected(t *testing.T) {
t.Parallel()
path := writeFile(t, t.TempDir(), "bad.yaml", thinkingPersonaYAML("thinking:\n mode: sometimes\n"))
_, err := Load(path)
if err == nil {
t.Fatal("Load(mode: sometimes) want error, got nil")
}
if !errors.Is(err, ErrInvalidThinking) {
t.Fatalf("error = %v, want ErrInvalidThinking", err)
}
if !strings.Contains(err.Error(), "sometimes") {
t.Fatalf("error %q does not name the offending value", err)
}
}
// TestLoad_ThinkingNegativeBudgetRejected asserts a negative budget is rejected
// (it would otherwise become a nonsensical provider request).
func TestLoad_ThinkingNegativeBudgetRejected(t *testing.T) {
t.Parallel()
path := writeFile(t, t.TempDir(), "bad.yaml", thinkingPersonaYAML("thinking:\n budgetTokens: -1\n"))
if _, err := Load(path); !errors.Is(err, ErrInvalidThinking) {
t.Fatalf("error = %v, want ErrInvalidThinking", err)
}
}
// TestThinkingParams_EnableModeMapping pins the tri-state mapping the model layer
// depends on: only an explicit on/off produces a switch, default/unset yields nil
// so provider thinking is never turned on as a side effect.
func TestThinkingParams_EnableModeMapping(t *testing.T) {
t.Parallel()
cases := []struct {
mode string
want *bool
}{
{mode: "", want: nil},
{mode: ThinkingModeDefault, want: nil},
}
for _, tt := range cases {
got := ThinkingParams{Mode: tt.mode}.Enable()
if got != nil {
t.Fatalf("Enable(%q) = %v, want nil", tt.mode, *got)
}
}
on := ThinkingParams{Mode: ThinkingModeOn}.Enable()
if on == nil || !*on {
t.Fatalf("Enable(on) = %v, want true", on)
}
off := ThinkingParams{Mode: ThinkingModeOff}.Enable()
if off == nil || *off {
t.Fatalf("Enable(off) = %v, want false", off)
}
}