feat(persona,model,loop): 人格 thinking 配置 + 5 个死字段接线 + 推理旋钮(按 provider 映射)
按 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:
1 parent
e4e18ce2a2
commit
38a403afca
22 files changed
+1714
-56
No files matched your search
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -104,6 +104,9 @@ type Loop struct {
|
||||
toolParallelism int
|
||||
hooks ToolLoopHooks
|
||||
onStream func(model.StreamEvent)
|
||||
thinking *model.Thinking
|
||||
reasoningEffort string
|
||||
thinkingShow *bool
|
||||
onAudit func(AuditEvent)
|
||||
onTurnEnd TurnEndHook
|
||||
maxContextTokens int
|
||||
@@ -157,6 +160,9 @@ func New(opts Options) *Loop {
|
||||
toolParallelism: toolParallelism,
|
||||
hooks: opts.Hooks,
|
||||
onStream: opts.OnStream,
|
||||
thinking: opts.Thinking,
|
||||
reasoningEffort: opts.ReasoningEffort,
|
||||
thinkingShow: opts.ThinkingShowToUser,
|
||||
onAudit: opts.OnAudit,
|
||||
onTurnEnd: opts.OnTurnEnd,
|
||||
maxContextTokens: opts.MaxContextTokens,
|
||||
|
||||
@@ -89,6 +89,22 @@ type Options struct {
|
||||
// forwarded to this callback (model.StreamEvent), so the frontend can render
|
||||
// body text, tool calls and (eventually) reasoning segments independently.
|
||||
OnStream func(model.StreamEvent)
|
||||
// Thinking carries the reasoning knobs (budget / explicit switch) injected
|
||||
// into every model request the loop builds. nil means "do not intervene",
|
||||
// which is the pre-existing behavior. It is a loop option rather than a
|
||||
// persona read inside the loop so the per-turn, per-role resolution a later
|
||||
// multi-character batch adds only changes the wiring-time resolver.
|
||||
Thinking *model.Thinking
|
||||
// ReasoningEffort is the OpenAI-compatible strength knob injected into every
|
||||
// model request. Empty means "do not intervene".
|
||||
ReasoningEffort string
|
||||
// ThinkingShowToUser gates the thinking frames the loop broadcasts: nil (the
|
||||
// default) keeps the pre-existing behavior and pushes them; an explicit false
|
||||
// keeps thinking_start/delta/end out of the client stream while text and tool
|
||||
// frames are unaffected. The frames are still produced and still reach the
|
||||
// model/transcript paths — only the UI broadcast is gated, so display and
|
||||
// persistence stay decoupled (design/04 §3.2).
|
||||
ThinkingShowToUser *bool
|
||||
// ToolExecution selects how a batch of tool calls is run: "parallel" (the
|
||||
// default) or "sequential". Empty means parallel.
|
||||
ToolExecution string
|
||||
|
||||
@@ -13,12 +13,14 @@ import (
|
||||
// RunStep (leading instruction message, tool schemas, model routing).
|
||||
func (l *Loop) buildRequest(ctx context.Context, messages []model.Message) model.Request {
|
||||
req := model.Request{
|
||||
Model: l.agent.Model(),
|
||||
Messages: l.assembleMessages(messages),
|
||||
Temperature: l.temperature(),
|
||||
MaxTokens: l.agent.MaxTokens(),
|
||||
Purpose: l.agent.Purpose(),
|
||||
Tools: l.toolSchemas(ctx, messages),
|
||||
Model: l.agent.Model(),
|
||||
Messages: l.assembleMessages(messages),
|
||||
Temperature: l.temperature(),
|
||||
MaxTokens: l.agent.MaxTokens(),
|
||||
Purpose: l.agent.Purpose(),
|
||||
Tools: l.toolSchemas(ctx, messages),
|
||||
Thinking: l.thinking,
|
||||
ReasoningEffort: l.reasoningEffort,
|
||||
}
|
||||
if l.agent.Router() != nil {
|
||||
if m, _ := l.agent.Router().RouteRequest(req); m != "" {
|
||||
|
||||
@@ -39,8 +39,11 @@ func (l *Loop) streamStep(ctx context.Context, messages []model.Message) (*stepO
|
||||
ev.SessionID = loopSession(ctx)
|
||||
ev.TurnID = loopTurn(ctx)
|
||||
// Suppress UI broadcast for internal autonomous passes (backthink),
|
||||
// whose intermediate reasoning must not leak into the chat stream.
|
||||
if l.onStream != nil && !isMutedBroadcast(ctx) {
|
||||
// whose intermediate reasoning must not leak into the chat stream, and for
|
||||
// thinking frames when the bound persona turned them off (showToUser:
|
||||
// false). Both gates are broadcast-only: the response the model produced is
|
||||
// unchanged, so display and persistence stay decoupled.
|
||||
if l.onStream != nil && !isMutedBroadcast(ctx) && l.broadcasts(ev) {
|
||||
l.onStream(ev)
|
||||
}
|
||||
})
|
||||
@@ -65,3 +68,25 @@ func (l *Loop) streamStep(ctx context.Context, messages []model.Message) (*stepO
|
||||
return &stepOutcome{final: true, text: resp.Content, stopReason: agent.StopReasonStop,
|
||||
modelStopReason: resp.StopReason, model: resp.Model}, nil
|
||||
}
|
||||
|
||||
// broadcasts reports whether a streamed event may be pushed to the UI. Only
|
||||
// thinking frames are ever withheld, and only when the wiring resolved the
|
||||
// persona's showToUser to false; text, tool-call and tool-progress frames are
|
||||
// never affected, so turning thinking off cannot change what the client sees of
|
||||
// the answer itself.
|
||||
func (l *Loop) broadcasts(ev model.StreamEvent) bool {
|
||||
if !isThinkingKind(ev.Kind) {
|
||||
return true
|
||||
}
|
||||
return l.thinkingShow == nil || *l.thinkingShow
|
||||
}
|
||||
|
||||
// isThinkingKind reports whether kind is one of the reasoning segment events.
|
||||
func isThinkingKind(kind model.StreamKind) bool {
|
||||
switch kind {
|
||||
case model.StreamKindThinkingStart, model.StreamKindThinkingDelta, model.StreamKindThinkingEnd:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package loop
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
|
||||
)
|
||||
|
||||
// thinkingAdapter emits one full thinking segment followed by one text segment,
|
||||
// and records every request it is handed so a test can assert the loop's
|
||||
// reasoning knobs actually reached the model call.
|
||||
type thinkingAdapter struct {
|
||||
reqs []model.Request
|
||||
}
|
||||
|
||||
func (a *thinkingAdapter) Name() string { return "thinking-mock" }
|
||||
|
||||
func (a *thinkingAdapter) Chat(_ context.Context, req model.Request, _ model.Options) (model.Response, error) {
|
||||
a.reqs = append(a.reqs, req)
|
||||
return model.Response{Content: "Hello"}, nil
|
||||
}
|
||||
|
||||
func (a *thinkingAdapter) ChatStream(_ context.Context, req model.Request, on func(model.StreamEvent)) (model.Response, error) {
|
||||
a.reqs = append(a.reqs, req)
|
||||
events := []model.StreamEvent{
|
||||
{Kind: model.StreamKindThinkingStart},
|
||||
{Kind: model.StreamKindThinkingDelta, Delta: "let me think"},
|
||||
{Kind: model.StreamKindThinkingEnd},
|
||||
{Kind: model.StreamKindTextStart},
|
||||
{Kind: model.StreamKindTextDelta, Delta: "Hello"},
|
||||
{Kind: model.StreamKindTextEnd},
|
||||
}
|
||||
for _, ev := range events {
|
||||
if on != nil {
|
||||
on(ev)
|
||||
}
|
||||
}
|
||||
return model.Response{Content: "Hello"}, nil
|
||||
}
|
||||
|
||||
// kindsOf returns the event kinds as a set for compact assertions.
|
||||
func kindsOf(events []model.StreamEvent) map[model.StreamKind]int {
|
||||
out := make(map[model.StreamKind]int, len(events))
|
||||
for _, ev := range events {
|
||||
out[ev.Kind]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// runThinkingTurn drives one streaming turn through a loop configured with the
|
||||
// given broadcast switch and returns the events OnStream saw.
|
||||
func runThinkingTurn(t *testing.T, show *bool) ([]model.StreamEvent, *thinkingAdapter) {
|
||||
t.Helper()
|
||||
ad := &thinkingAdapter{}
|
||||
onStream, streams := collectStream()
|
||||
l := New(Options{
|
||||
Agent: newTestAgent(t, ad, nil),
|
||||
OnStream: onStream,
|
||||
MaxRounds: 8,
|
||||
ThinkingShowToUser: show,
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "hi")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
return streams(), ad
|
||||
}
|
||||
|
||||
// TestRun_ThinkingShowToUserFalseWithholdsThinkingFrames is the showToUser=false
|
||||
// contract: thinking frames never reach the client callback while the body text
|
||||
// segment is delivered untouched (display is gated, the answer is not).
|
||||
func TestRun_ThinkingShowToUserFalseWithholdsThinkingFrames(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
show := false
|
||||
events, _ := runThinkingTurn(t, &show)
|
||||
kinds := kindsOf(events)
|
||||
for _, k := range []model.StreamKind{model.StreamKindThinkingStart, model.StreamKindThinkingDelta, model.StreamKindThinkingEnd} {
|
||||
if n := kinds[k]; n != 0 {
|
||||
t.Fatalf("event kind %q emitted %d time(s) with showToUser=false", k, n)
|
||||
}
|
||||
}
|
||||
for _, k := range []model.StreamKind{model.StreamKindTextStart, model.StreamKindTextDelta, model.StreamKindTextEnd} {
|
||||
if kinds[k] != 1 {
|
||||
t.Fatalf("event kind %q emitted %d time(s), want 1 (body must be unaffected)", k, kinds[k])
|
||||
}
|
||||
}
|
||||
if len(events) != 3 {
|
||||
t.Fatalf("events = %d, want only the 3 text frames", len(events))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_ThinkingShowToUserDefaultBroadcastsThinking keeps the pre-existing
|
||||
// behavior when the option is unset (nil): thinking frames are pushed.
|
||||
func TestRun_ThinkingShowToUserDefaultBroadcastsThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
events, _ := runThinkingTurn(t, nil)
|
||||
kinds := kindsOf(events)
|
||||
if kinds[model.StreamKindThinkingDelta] != 1 || kinds[model.StreamKindThinkingStart] != 1 || kinds[model.StreamKindThinkingEnd] != 1 {
|
||||
t.Fatalf("thinking frames = %v, want start/delta/end each once with the option unset", kinds)
|
||||
}
|
||||
if len(events) != 6 {
|
||||
t.Fatalf("events = %d, want all 6 frames", len(events))
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_ThinkingShowToUserTrueBroadcastsThinking asserts an explicit true
|
||||
// behaves like the default.
|
||||
func TestRun_ThinkingShowToUserTrueBroadcastsThinking(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
show := true
|
||||
events, _ := runThinkingTurn(t, &show)
|
||||
if kinds := kindsOf(events); kinds[model.StreamKindThinkingDelta] != 1 {
|
||||
t.Fatalf("thinking delta frames = %d, want 1 with showToUser=true", kinds[model.StreamKindThinkingDelta])
|
||||
}
|
||||
}
|
||||
|
||||
// TestRun_RequestCarriesThinkingKnobs asserts the loop injects its reasoning
|
||||
// options into every model request it builds, so a persona's thinking config is
|
||||
// actually applied rather than validated-and-ignored.
|
||||
func TestRun_RequestCarriesThinkingKnobs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
ad := &thinkingAdapter{}
|
||||
onStream, _ := collectStream()
|
||||
want := &model.Thinking{BudgetTokens: 4096}
|
||||
l := New(Options{
|
||||
Agent: newTestAgent(t, ad, nil),
|
||||
OnStream: onStream,
|
||||
MaxRounds: 8,
|
||||
Thinking: want,
|
||||
ReasoningEffort: "low",
|
||||
})
|
||||
if _, err := l.Run(context.Background(), "web", []model.Message{model.TextMessage(model.RoleUser, "hi")}); err != nil {
|
||||
t.Fatalf("Run: %v", err)
|
||||
}
|
||||
if len(ad.reqs) == 0 {
|
||||
t.Fatal("no model request was recorded")
|
||||
}
|
||||
got := ad.reqs[0]
|
||||
if got.Thinking != want {
|
||||
t.Fatalf("request.Thinking = %+v, want %+v", got.Thinking, want)
|
||||
}
|
||||
if got.Thinking.BudgetTokens != 4096 {
|
||||
t.Fatalf("request.Thinking.BudgetTokens = %d, want 4096", got.Thinking.BudgetTokens)
|
||||
}
|
||||
if got.ReasoningEffort != "low" {
|
||||
t.Fatalf("request.ReasoningEffort = %q, want low", got.ReasoningEffort)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -24,8 +25,19 @@ const (
|
||||
anthropicDefaultMaxTokens = 8192
|
||||
// anthropicDataPrefix marks a payload embedded as a data: URI.
|
||||
anthropicDataPrefix = "data:"
|
||||
// anthropicThinkingTypeEnabled is the wire value of an enabled extended-
|
||||
// thinking directive.
|
||||
anthropicThinkingTypeEnabled = "enabled"
|
||||
)
|
||||
|
||||
// anthropicThinking is the wire form of the extended-thinking directive. It is
|
||||
// omitted entirely when the caller did not ask for thinking (or asked for it to
|
||||
// be off), because Anthropic treats a missing field as "no thinking".
|
||||
type anthropicThinking struct {
|
||||
Type string `json:"type"`
|
||||
BudgetTokens int `json:"budget_tokens"`
|
||||
}
|
||||
|
||||
// anthropicRequest is the body sent to /v1/messages. Messages carry Anthropic's
|
||||
// content-block model and the system prompt lives at the request root.
|
||||
type anthropicRequest struct {
|
||||
@@ -36,6 +48,7 @@ type anthropicRequest struct {
|
||||
ToolChoice any `json:"tool_choice,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
Thinking *anthropicThinking `json:"thinking,omitempty"`
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
}
|
||||
|
||||
@@ -90,6 +103,10 @@ type AnthropicChatAdapter struct {
|
||||
model string
|
||||
client *http.Client
|
||||
recorder Recorder
|
||||
// log reports reasoning adjustments and ignored directives. It is never nil:
|
||||
// a discard logger tagged with this adapter's source is installed when the
|
||||
// caller supplies none, so a provider decision is always traceable.
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// AnthropicOption configures an AnthropicChatAdapter.
|
||||
@@ -111,6 +128,17 @@ func WithAnthropicModel(m string) AnthropicOption {
|
||||
return func(a *AnthropicChatAdapter) { a.model = m }
|
||||
}
|
||||
|
||||
// WithAnthropicLogger attaches the logger used to report reasoning adjustments
|
||||
// (budget raised to fit max_tokens, ignored directives). A nil logger is ignored
|
||||
// so the discard default stays in place.
|
||||
func WithAnthropicLogger(l *slog.Logger) AnthropicOption {
|
||||
return func(a *AnthropicChatAdapter) {
|
||||
if l != nil {
|
||||
a.log = l
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewAnthropicChat builds an Anthropic adapter from a supplier config. baseURL is
|
||||
// trimmed of any trailing slash before the /v1/messages path is appended.
|
||||
func NewAnthropicChat(cfg config.LLMConfig, opts ...AnthropicOption) *AnthropicChatAdapter {
|
||||
@@ -123,6 +151,7 @@ func NewAnthropicChat(cfg config.LLMConfig, opts ...AnthropicOption) *AnthropicC
|
||||
Transport: http.DefaultTransport,
|
||||
Timeout: defaultHTTPTimeout,
|
||||
},
|
||||
log: discardLogger("runtime/model/anthropic"),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
@@ -264,6 +293,9 @@ func (a *AnthropicChatAdapter) buildRequest(req Request, stream bool) ([]byte, e
|
||||
return nil, err
|
||||
}
|
||||
tokenLimit := effectiveMaxTokens(req.MaxTokens, anthropicDefaultMaxTokens)
|
||||
// Extended thinking shares max_tokens with the visible answer, so the budget
|
||||
// is resolved together with the limit it requires (design/04 §3.2 red line).
|
||||
tokenLimit, thinking := anthropicThinkingFor(req.Thinking, tokenLimit, a.log)
|
||||
wire := anthropicRequest{
|
||||
Model: req.Model,
|
||||
System: system,
|
||||
@@ -272,6 +304,7 @@ func (a *AnthropicChatAdapter) buildRequest(req Request, stream bool) ([]byte, e
|
||||
ToolChoice: req.ToolChoice,
|
||||
Temperature: req.Temperature,
|
||||
MaxTokens: tokenLimit,
|
||||
Thinking: thinking,
|
||||
Stream: stream,
|
||||
}
|
||||
buf, err := json.Marshal(wire)
|
||||
|
||||
@@ -3,6 +3,7 @@ package model
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/config"
|
||||
)
|
||||
@@ -40,11 +41,19 @@ func NewChatAdapter(cfg config.LLMConfig) (Adapter, error) {
|
||||
// step is served by an adapter of the selected protocol. The empty provider
|
||||
// defaults to openai. An unrecognized provider returns ErrUnknownProvider.
|
||||
func NewChatChain(cfg config.LLMConfig) (*Chain, error) {
|
||||
return NewChatChainWithLog(cfg, nil)
|
||||
}
|
||||
|
||||
// NewChatChainWithLog is NewChatChain with a logger attached to every adapter it
|
||||
// builds, so a provider-level reasoning decision (a thinking budget raised to fit
|
||||
// max_tokens, a reasoning_effort value downgraded or ignored) is reported with
|
||||
// its module source. A nil logger leaves the adapters' discard default in place.
|
||||
func NewChatChainWithLog(cfg config.LLMConfig, log *slog.Logger) (*Chain, error) {
|
||||
switch cfg.Provider {
|
||||
case ProviderOpenAI, "":
|
||||
return newOpenAIChain(cfg)
|
||||
return newOpenAIChain(cfg, WithOpenAILogger(log))
|
||||
case ProviderAnthropic:
|
||||
return newAnthropicChain(cfg)
|
||||
return newAnthropicChain(cfg, WithAnthropicLogger(log))
|
||||
default:
|
||||
return nil, fmt.Errorf("model: %w: provider %q", ErrUnknownProvider, cfg.Provider)
|
||||
}
|
||||
@@ -65,13 +74,13 @@ func newOpenAIChain(cfg config.LLMConfig, opts ...OpenAIOption) (*Chain, error)
|
||||
|
||||
// newAnthropicChain builds a fallback chain from the Anthropic config block. Each
|
||||
// step is an AnthropicChatAdapter against the configured /v1/messages endpoint.
|
||||
func newAnthropicChain(cfg config.LLMConfig) (*Chain, error) {
|
||||
func newAnthropicChain(cfg config.LLMConfig, opts ...AnthropicOption) (*Chain, error) {
|
||||
if cfg.AnthropicBaseURL == "" || cfg.AnthropicModel == "" {
|
||||
return nil, ErrNoModel
|
||||
}
|
||||
steps := []Step{{Model: cfg.AnthropicModel, Adapter: NewAnthropicChat(cfg)}}
|
||||
steps := []Step{{Model: cfg.AnthropicModel, Adapter: NewAnthropicChat(cfg, opts...)}}
|
||||
if cfg.AnthropicFallback != "" && cfg.AnthropicFallback != cfg.AnthropicModel {
|
||||
steps = append(steps, Step{Model: cfg.AnthropicFallback, Adapter: NewAnthropicChat(cfg)})
|
||||
steps = append(steps, Step{Model: cfg.AnthropicFallback, Adapter: NewAnthropicChat(cfg, opts...)})
|
||||
}
|
||||
return NewChain(steps...), nil
|
||||
}
|
||||
|
||||
@@ -170,6 +170,28 @@ type Request struct {
|
||||
// "name":"x"}); empty means the provider default. Passed through verbatim to
|
||||
// protocols that support it (Anthropic's tool_choice).
|
||||
ToolChoice any
|
||||
// Thinking controls the provider's reasoning budget/switch (design/04 §3.2).
|
||||
// nil means "do not intervene" and uses the provider default. A provider
|
||||
// whose protocol has no mapping for it logs a WARN rather than silently
|
||||
// ignoring it.
|
||||
Thinking *Thinking
|
||||
// ReasoningEffort is the OpenAI-compatible reasoning strength knob
|
||||
// (reasoning_effort). Empty means "do not intervene". The value is validated
|
||||
// against the detected provider's whitelist; an unsupported value is
|
||||
// downgraded to the nearest allowed tier (or dropped) with a WARN.
|
||||
ReasoningEffort string
|
||||
}
|
||||
|
||||
// Thinking carries the reasoning knobs a caller wants applied (design/04 §3.2).
|
||||
// Providers map the fields they actually support and report the rest; it only
|
||||
// controls budget/switch, never the thought content (design/01 §2.1 red line).
|
||||
type Thinking struct {
|
||||
// BudgetTokens is the Anthropic thinking.budget_tokens target (the official
|
||||
// semantic is a target, not a hard cap). Zero selects the adapter default.
|
||||
BudgetTokens int
|
||||
// Enable is an explicit on/off switch for providers that expose a boolean
|
||||
// thinking flag. nil = no explicit switch.
|
||||
Enable *bool
|
||||
}
|
||||
|
||||
// Response is a normalized completion result.
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -39,6 +40,10 @@ type OpenAIChatAdapter struct {
|
||||
model string
|
||||
client *http.Client
|
||||
recorder Recorder
|
||||
// log reports reasoning_effort validation and ignored thinking directives. It
|
||||
// is never nil: a discard logger tagged with this adapter's source is
|
||||
// installed when the caller supplies none, so a decision is always traceable.
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// OpenAIOption configures an OpenAIChatAdapter.
|
||||
@@ -60,6 +65,17 @@ func WithModel(m string) OpenAIOption {
|
||||
return func(a *OpenAIChatAdapter) { a.model = m }
|
||||
}
|
||||
|
||||
// WithOpenAILogger attaches the logger used to report reasoning_effort
|
||||
// validation and ignored thinking directives. A nil logger is ignored so the
|
||||
// discard default stays in place.
|
||||
func WithOpenAILogger(l *slog.Logger) OpenAIOption {
|
||||
return func(a *OpenAIChatAdapter) {
|
||||
if l != nil {
|
||||
a.log = l
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewOpenAIChat builds an adapter from a supplier config. baseURL is trimmed of
|
||||
// any trailing slash before the /chat/completions path is appended.
|
||||
func NewOpenAIChat(cfg config.LLMConfig, opts ...OpenAIOption) *OpenAIChatAdapter {
|
||||
@@ -72,6 +88,7 @@ func NewOpenAIChat(cfg config.LLMConfig, opts ...OpenAIOption) *OpenAIChatAdapte
|
||||
Transport: http.DefaultTransport,
|
||||
Timeout: defaultHTTPTimeout,
|
||||
},
|
||||
log: discardLogger("runtime/model/openai"),
|
||||
}
|
||||
for _, o := range opts {
|
||||
o(a)
|
||||
|
||||
@@ -15,6 +15,10 @@ type openAIChatRequest struct {
|
||||
Stream bool `json:"stream,omitempty"`
|
||||
StreamOptions *openAIStreamOpts `json:"stream_options,omitempty"`
|
||||
Tools []openAITool `json:"tools,omitempty"`
|
||||
// ReasoningEffort is the OpenAI-compatible reasoning strength knob. It is set
|
||||
// only after validation against the detected vendor's whitelist (design/04
|
||||
// §3.2); an unsupported value is downgraded or dropped, never forwarded as-is.
|
||||
ReasoningEffort string `json:"reasoning_effort,omitempty"`
|
||||
}
|
||||
|
||||
// openAIStreamOpts asks the provider to include usage in the final stream chunk.
|
||||
@@ -66,13 +70,19 @@ func (a *OpenAIChatAdapter) buildRequest(req Request, stream bool) ([]byte, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// The vendor behind an OpenAI-compatible endpoint decides which
|
||||
// reasoning_effort tiers are legal; classify it from the resolved model (and
|
||||
// the base URL as a fallback) before touching the request (design/04 §3.2).
|
||||
vendor := reasoningVendorFor(req.Model, a.baseURL)
|
||||
reportUnmappedThinking(a.log, vendor, req.Model, req.Thinking)
|
||||
wire := openAIChatRequest{
|
||||
Model: req.Model,
|
||||
Messages: msgs,
|
||||
Temperature: req.Temperature,
|
||||
MaxTokens: req.MaxTokens,
|
||||
Stream: stream,
|
||||
Tools: buildTools(req.Tools),
|
||||
Model: req.Model,
|
||||
Messages: msgs,
|
||||
Temperature: req.Temperature,
|
||||
MaxTokens: req.MaxTokens,
|
||||
Stream: stream,
|
||||
Tools: buildTools(req.Tools),
|
||||
ReasoningEffort: resolveReasoningEffort(a.log, vendor, req.ReasoningEffort, req.Model),
|
||||
}
|
||||
if stream {
|
||||
wire.StreamOptions = &openAIStreamOpts{IncludeUsage: true}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
||||
)
|
||||
|
||||
// discardLogger returns a logger that drops every record but still carries the
|
||||
// adapter's module source, so an adapter built without an injected logger can
|
||||
// never emit an unsourced record.
|
||||
func discardLogger(source string) *slog.Logger {
|
||||
return logger.WithSource(slog.New(slog.NewTextHandler(io.Discard, nil)), source)
|
||||
}
|
||||
|
||||
// Anthropic extended-thinking protocol bounds (design/04 §3.2).
|
||||
const (
|
||||
// anthropicMinThinkingBudget is the smallest budget_tokens the Messages API
|
||||
// accepts for thinking.type=enabled; anything below it is rejected with a
|
||||
// 400, so a lower non-zero budget is raised and reported rather than sent.
|
||||
anthropicMinThinkingBudget = 1024
|
||||
// anthropicDefaultThinkingBudget is used when thinking is switched on without
|
||||
// an explicit budget.
|
||||
anthropicDefaultThinkingBudget = 4096
|
||||
// anthropicThinkingBodyReserve is the body room kept on top of the thinking
|
||||
// budget: max_tokens is shared by thinking and the visible answer, so the
|
||||
// budget must never be allowed to consume it all (design/04 §3.2 red line:
|
||||
// "预算与正文不得互相吃光").
|
||||
anthropicThinkingBodyReserve = 2048
|
||||
)
|
||||
|
||||
// reasoningVendor identifies the vendor behind an OpenAI-compatible endpoint.
|
||||
// The wire protocol is the same for all of them, but the accepted
|
||||
// reasoning_effort values are not, so a value must be checked against the right
|
||||
// whitelist instead of being forwarded blindly.
|
||||
type reasoningVendor string
|
||||
|
||||
const (
|
||||
vendorOpenAI reasoningVendor = "openai"
|
||||
vendorDeepSeek reasoningVendor = "deepseek"
|
||||
vendorQwen reasoningVendor = "qwen"
|
||||
vendorUnknown reasoningVendor = "unknown"
|
||||
)
|
||||
|
||||
// reasoningEffortLadder is the canonical ascending order of reasoning_effort
|
||||
// tiers. It is used to round an unsupported value down to the nearest tier a
|
||||
// vendor accepts.
|
||||
var reasoningEffortLadder = []string{"none", "minimal", "low", "medium", "high", "xhigh", "max"}
|
||||
|
||||
// reasoningEffortAllowed is the per-vendor whitelist. A vendor absent from this
|
||||
// table has no reasoning_effort support at all, which is reported rather than
|
||||
// guessed.
|
||||
var reasoningEffortAllowed = map[reasoningVendor]map[string]bool{
|
||||
vendorOpenAI: tierSet("none", "minimal", "low", "medium", "high", "xhigh", "max"),
|
||||
vendorDeepSeek: tierSet("low", "high", "max"),
|
||||
}
|
||||
|
||||
// tierSet builds a membership set from the given tiers.
|
||||
func tierSet(tiers ...string) map[string]bool {
|
||||
set := make(map[string]bool, len(tiers))
|
||||
for _, t := range tiers {
|
||||
set[t] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
// reasoningVendorFor classifies the vendor of an OpenAI-compatible request from
|
||||
// its model name, falling back to the base URL when the name does not identify
|
||||
// one. An unrecognized pair yields vendorUnknown so the caller reports "not
|
||||
// supported" instead of assuming OpenAI semantics.
|
||||
func reasoningVendorFor(model, baseURL string) reasoningVendor {
|
||||
m := strings.ToLower(strings.TrimSpace(model))
|
||||
switch {
|
||||
case strings.Contains(m, "deepseek"):
|
||||
return vendorDeepSeek
|
||||
case strings.Contains(m, "qwen"):
|
||||
return vendorQwen
|
||||
case strings.Contains(m, "gpt-"), strings.Contains(m, "chatgpt"),
|
||||
strings.HasPrefix(m, "o1"), strings.HasPrefix(m, "o3"), strings.HasPrefix(m, "o4"):
|
||||
return vendorOpenAI
|
||||
}
|
||||
u := strings.ToLower(strings.TrimSpace(baseURL))
|
||||
switch {
|
||||
case strings.Contains(u, "deepseek"):
|
||||
return vendorDeepSeek
|
||||
case strings.Contains(u, "dashscope"), strings.Contains(u, "aliyuncs"):
|
||||
return vendorQwen
|
||||
case strings.Contains(u, "openai"):
|
||||
return vendorOpenAI
|
||||
}
|
||||
return vendorUnknown
|
||||
}
|
||||
|
||||
// resolveReasoningEffort validates effort against the vendor's whitelist and
|
||||
// returns the value to send. An unsupported tier is rounded down to the nearest
|
||||
// tier the vendor accepts; a value the vendor does not accept at all — or a
|
||||
// vendor with no whitelist — yields "", meaning the field is dropped. Every
|
||||
// decision is logged (provider, field, value), never silently applied.
|
||||
func resolveReasoningEffort(log *slog.Logger, vendor reasoningVendor, effort, model string) string {
|
||||
effort = strings.TrimSpace(effort)
|
||||
if effort == "" {
|
||||
return ""
|
||||
}
|
||||
allowed, ok := reasoningEffortAllowed[vendor]
|
||||
if !ok {
|
||||
log.Warn("reasoning_effort ignored: provider does not support it",
|
||||
"provider", string(vendor), "field", "reasoning_effort", "value", effort, "model", model)
|
||||
return ""
|
||||
}
|
||||
if allowed[effort] {
|
||||
return effort
|
||||
}
|
||||
downgraded, ok := downgradeReasoningEffort(allowed, effort)
|
||||
if !ok {
|
||||
log.Warn("reasoning_effort dropped: unrecognized value",
|
||||
"provider", string(vendor), "field", "reasoning_effort", "value", effort, "model", model)
|
||||
return ""
|
||||
}
|
||||
log.Warn("reasoning_effort downgraded: value not accepted by provider",
|
||||
"provider", string(vendor), "field", "reasoning_effort",
|
||||
"value", effort, "sent", downgraded, "model", model)
|
||||
return downgraded
|
||||
}
|
||||
|
||||
// downgradeReasoningEffort rounds an unsupported tier down to the nearest tier
|
||||
// the vendor accepts using the canonical ladder order; a tier below the vendor's
|
||||
// minimum maps to that minimum. It reports false when effort is not on the
|
||||
// ladder at all, so the caller drops the field instead of inventing a value.
|
||||
func downgradeReasoningEffort(allowed map[string]bool, effort string) (string, bool) {
|
||||
start := -1
|
||||
for i, tier := range reasoningEffortLadder {
|
||||
if tier == effort {
|
||||
start = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if start < 0 {
|
||||
return "", false
|
||||
}
|
||||
for i := start; i >= 0; i-- {
|
||||
if allowed[reasoningEffortLadder[i]] {
|
||||
return reasoningEffortLadder[i], true
|
||||
}
|
||||
}
|
||||
for _, tier := range reasoningEffortLadder {
|
||||
if allowed[tier] {
|
||||
return tier, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// anthropicThinkingFor resolves the extended-thinking directive together with the
|
||||
// max_tokens it requires. It returns the (possibly raised) max_tokens and the
|
||||
// wire block; a nil block means "do not send thinking" (no directive, or an
|
||||
// explicit off). Because max_tokens is shared by thinking and the visible answer,
|
||||
// the returned budget always leaves anthropicThinkingBodyReserve for the body,
|
||||
// and a request whose budget would eat the answer raises max_tokens instead — the
|
||||
// adjustment is logged so it is never a silent rewrite.
|
||||
func anthropicThinkingFor(th *Thinking, maxTokens int, log *slog.Logger) (int, *anthropicThinking) {
|
||||
if th == nil || (th.Enable != nil && !*th.Enable) {
|
||||
return maxTokens, nil
|
||||
}
|
||||
budget := th.BudgetTokens
|
||||
if budget == 0 {
|
||||
budget = anthropicDefaultThinkingBudget
|
||||
}
|
||||
if budget < anthropicMinThinkingBudget {
|
||||
log.Warn("thinking budget raised to the protocol minimum",
|
||||
"provider", "anthropic", "field", "thinking.budget_tokens",
|
||||
"budget_tokens", th.BudgetTokens, "sent", anthropicMinThinkingBudget)
|
||||
budget = anthropicMinThinkingBudget
|
||||
}
|
||||
if need := budget + anthropicThinkingBodyReserve; maxTokens < need {
|
||||
log.Warn("max_tokens raised to leave room for thinking plus the answer",
|
||||
"provider", "anthropic", "budget_tokens", budget,
|
||||
"max_tokens_requested", maxTokens, "max_tokens_sent", need,
|
||||
"body_reserve", anthropicThinkingBodyReserve)
|
||||
maxTokens = need
|
||||
}
|
||||
return maxTokens, &anthropicThinking{Type: anthropicThinkingTypeEnabled, BudgetTokens: budget}
|
||||
}
|
||||
|
||||
// reportUnmappedThinking logs why a Thinking directive cannot be carried by an
|
||||
// OpenAI-compatible request, naming the provider and the field that was ignored.
|
||||
// Qwen3 does have enable_thinking, but the protocol has no portable field for
|
||||
// it (vLLM wants chat_template_kwargs.enable_thinking, DashScope's compatible
|
||||
// mode wants a top-level enable_thinking), and sending the wrong shape can 400
|
||||
// the request — so this version reports it instead of guessing.
|
||||
func reportUnmappedThinking(log *slog.Logger, vendor reasoningVendor, model string, th *Thinking) {
|
||||
if th == nil {
|
||||
return
|
||||
}
|
||||
if th.Enable != nil {
|
||||
switch vendor {
|
||||
case vendorQwen:
|
||||
log.Warn("enable_thinking not forwarded: the OpenAI-compatible protocol has no portable field for it",
|
||||
"provider", "qwen", "field", "extra_body.chat_template_kwargs.enable_thinking",
|
||||
"enable", *th.Enable, "model", model)
|
||||
case vendorDeepSeek:
|
||||
log.Warn("deepseek thinking switch not mapped in this version; only reasoning_effort is forwarded",
|
||||
"provider", "deepseek", "field", "thinking.type", "enable", *th.Enable, "model", model)
|
||||
default:
|
||||
log.Warn("thinking switch ignored: provider has no boolean thinking switch",
|
||||
"provider", string(vendor), "field", "thinking.enable", "enable", *th.Enable, "model", model)
|
||||
}
|
||||
return
|
||||
}
|
||||
if th.BudgetTokens > 0 {
|
||||
log.Warn("thinking budget ignored: OpenAI-compatible providers take reasoning_effort, not a token budget",
|
||||
"provider", string(vendor), "field", "thinking.budget_tokens",
|
||||
"budget_tokens", th.BudgetTokens, "model", model)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/config"
|
||||
)
|
||||
|
||||
// captureLog returns a logger writing text records into a buffer, plus the
|
||||
// buffer, so a test can assert the WARN an adapter emits.
|
||||
func captureLog() (*slog.Logger, *bytes.Buffer) {
|
||||
buf := &bytes.Buffer{}
|
||||
return slog.New(slog.NewTextHandler(buf, &slog.HandlerOptions{Level: slog.LevelDebug})), buf
|
||||
}
|
||||
|
||||
// boolPtr is a convenience for the tri-state Thinking.Enable.
|
||||
func boolPtr(v bool) *bool { return &v }
|
||||
|
||||
// TestAnthropicChat_ThinkingBudgetLeavesRoomForTheAnswer is the design/04 §3.2
|
||||
// red line: a budget large enough to eat max_tokens must not be sent as-is —
|
||||
// the adapter raises max_tokens so thinking and the visible answer both fit, and
|
||||
// it logs the adjustment (never a silent rewrite).
|
||||
func TestAnthropicChat_ThinkingBudgetLeavesRoomForTheAnswer(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan anthropicCaptured, 1)
|
||||
srv := newAnthropicServer(t, http.StatusOK, "application/json", anthropicTextResponse, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewAnthropicChat(
|
||||
config.LLMConfig{AnthropicBaseURL: srv.URL, AnthropicModel: "claude-test"},
|
||||
WithAnthropicLogger(log))
|
||||
|
||||
const budget = 4096
|
||||
// max_tokens equals the budget: without the guard the whole budget would be
|
||||
// consumed by thinking and the answer would come back empty.
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "claude-test",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
MaxTokens: budget,
|
||||
Thinking: &Thinking{BudgetTokens: budget},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
body := (<-ch).body
|
||||
think, ok := body["thinking"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("body.thinking = %v, want an enabled directive", body["thinking"])
|
||||
}
|
||||
if think["type"] != anthropicThinkingTypeEnabled {
|
||||
t.Errorf("thinking.type = %v, want %q", think["type"], anthropicThinkingTypeEnabled)
|
||||
}
|
||||
gotBudget, _ := think["budget_tokens"].(float64)
|
||||
maxTokens, _ := body["max_tokens"].(float64)
|
||||
if int(gotBudget) != budget {
|
||||
t.Errorf("thinking.budget_tokens = %v, want %d", gotBudget, budget)
|
||||
}
|
||||
if maxTokens <= gotBudget {
|
||||
t.Fatalf("max_tokens = %v, want > budget_tokens %v (thinking would eat the answer)", maxTokens, gotBudget)
|
||||
}
|
||||
if maxTokens < gotBudget+anthropicThinkingBodyReserve {
|
||||
t.Errorf("max_tokens = %v, want >= budget %v + body reserve %d", maxTokens, gotBudget, anthropicThinkingBodyReserve)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "max_tokens raised") {
|
||||
t.Errorf("log = %q, want a WARN explaining the max_tokens raise", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthropicChat_ThinkingBudgetBelowMaxTokensUnchanged pins the non-saturated
|
||||
// case: when the caller's max_tokens already leaves room, it is sent untouched
|
||||
// and the budget stays strictly below it.
|
||||
func TestAnthropicChat_ThinkingBudgetBelowMaxTokensUnchanged(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan anthropicCaptured, 1)
|
||||
srv := newAnthropicServer(t, http.StatusOK, "application/json", anthropicTextResponse, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewAnthropicChat(
|
||||
config.LLMConfig{AnthropicBaseURL: srv.URL, AnthropicModel: "claude-test"},
|
||||
WithAnthropicLogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "claude-test",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
MaxTokens: anthropicDefaultMaxTokens,
|
||||
Thinking: &Thinking{BudgetTokens: 4096},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
body := (<-ch).body
|
||||
think := body["thinking"].(map[string]any)
|
||||
gotBudget, _ := think["budget_tokens"].(float64)
|
||||
maxTokens, _ := body["max_tokens"].(float64)
|
||||
if maxTokens != float64(anthropicDefaultMaxTokens) {
|
||||
t.Errorf("max_tokens = %v, want the requested %d (unchanged)", maxTokens, anthropicDefaultMaxTokens)
|
||||
}
|
||||
if gotBudget >= maxTokens {
|
||||
t.Errorf("budget_tokens %v >= max_tokens %v", gotBudget, maxTokens)
|
||||
}
|
||||
if strings.Contains(buf.String(), "max_tokens raised") {
|
||||
t.Errorf("unexpected adjustment log: %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthropicChat_ThinkingDisabledOmitsField asserts the explicit off switch
|
||||
// sends no thinking directive at all (Anthropic treats a missing field as off).
|
||||
func TestAnthropicChat_ThinkingDisabledOmitsField(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan anthropicCaptured, 1)
|
||||
srv := newAnthropicServer(t, http.StatusOK, "application/json", anthropicTextResponse, ch)
|
||||
ad := NewAnthropicChat(config.LLMConfig{AnthropicBaseURL: srv.URL, AnthropicModel: "claude-test"})
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "claude-test",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
Thinking: &Thinking{BudgetTokens: 4096, Enable: boolPtr(false)},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
if body := (<-ch).body; body["thinking"] != nil {
|
||||
t.Fatalf("body.thinking = %v, want the field omitted", body["thinking"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthropicChat_ThinkingBudgetRaisedToProtocolMinimum asserts a budget below
|
||||
// the API minimum is raised (sending it as-is would 400) and reported.
|
||||
func TestAnthropicChat_ThinkingBudgetRaisedToProtocolMinimum(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan anthropicCaptured, 1)
|
||||
srv := newAnthropicServer(t, http.StatusOK, "application/json", anthropicTextResponse, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewAnthropicChat(
|
||||
config.LLMConfig{AnthropicBaseURL: srv.URL, AnthropicModel: "claude-test"},
|
||||
WithAnthropicLogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "claude-test",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
Thinking: &Thinking{BudgetTokens: 512},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
think := (<-ch).body["thinking"].(map[string]any)
|
||||
if got, _ := think["budget_tokens"].(float64); int(got) != anthropicMinThinkingBudget {
|
||||
t.Errorf("thinking.budget_tokens = %v, want the minimum %d", got, anthropicMinThinkingBudget)
|
||||
}
|
||||
if !strings.Contains(buf.String(), "protocol minimum") {
|
||||
t.Errorf("log = %q, want a WARN about the minimum budget", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIChat_ReasoningEffortPassthrough asserts a supported tier on a known
|
||||
// provider is forwarded verbatim, with no warning.
|
||||
func TestOpenAIChat_ReasoningEffortPassthrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan capturedRequest, 1)
|
||||
srv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewOpenAIChat(config.LLMConfig{BaseURL: srv.URL, Model: "gpt-test"}, WithOpenAILogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "gpt-4o",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
ReasoningEffort: "high",
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
if got := (<-ch).body["reasoning_effort"]; got != "high" {
|
||||
t.Fatalf("body.reasoning_effort = %v, want high", got)
|
||||
}
|
||||
if buf.Len() != 0 {
|
||||
t.Errorf("unexpected log for a supported value: %q", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIChat_ReasoningEffortDowngradedForDeepSeek asserts a tier the vendor
|
||||
// does not accept (DeepSeek allows only low/high/max) is rounded down to the
|
||||
// nearest allowed tier and reported, never forwarded as-is.
|
||||
func TestOpenAIChat_ReasoningEffortDowngradedForDeepSeek(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan capturedRequest, 1)
|
||||
srv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewOpenAIChat(config.LLMConfig{BaseURL: srv.URL, Model: "deepseek-chat"}, WithOpenAILogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "deepseek-chat",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
ReasoningEffort: "medium",
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
if got := (<-ch).body["reasoning_effort"]; got != "low" {
|
||||
t.Fatalf("body.reasoning_effort = %v, want the downgraded low", got)
|
||||
}
|
||||
rec := buf.String()
|
||||
for _, want := range []string{"level=WARN", "reasoning_effort", "deepseek", "medium", "low"} {
|
||||
if !strings.Contains(rec, want) {
|
||||
t.Errorf("log %q missing %q", rec, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIChat_ReasoningEffortDroppedForUnknownProvider asserts an
|
||||
// unrecognized provider/model leaves the request untouched and reports the
|
||||
// ignored field (design/04 §3.2: never silently ineffective).
|
||||
func TestOpenAIChat_ReasoningEffortDroppedForUnknownProvider(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan capturedRequest, 1)
|
||||
srv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewOpenAIChat(config.LLMConfig{BaseURL: srv.URL, Model: "mystery-1"}, WithOpenAILogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "mystery-1",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
ReasoningEffort: "high",
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
body := (<-ch).body
|
||||
if _, present := body["reasoning_effort"]; present {
|
||||
t.Fatalf("body.reasoning_effort = %v, want the field dropped", body["reasoning_effort"])
|
||||
}
|
||||
rec := buf.String()
|
||||
for _, want := range []string{"level=WARN", "reasoning_effort", "unknown", "high"} {
|
||||
if !strings.Contains(rec, want) {
|
||||
t.Errorf("log %q missing %q", rec, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIChat_QwenEnableThinkingReportedNotForwarded documents the deliberate
|
||||
// choice for the Qwen3 hard switch: the OpenAI-compatible protocol has no
|
||||
// portable wire shape for enable_thinking, so this version reports it and leaves
|
||||
// the request byte-identical instead of guessing a shape that could 400.
|
||||
func TestOpenAIChat_QwenEnableThinkingReportedNotForwarded(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan capturedRequest, 1)
|
||||
srv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewOpenAIChat(config.LLMConfig{BaseURL: srv.URL, Model: "qwen3-max"}, WithOpenAILogger(log))
|
||||
|
||||
plain := make(chan capturedRequest, 1)
|
||||
plainSrv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, plain)
|
||||
plainAd := NewOpenAIChat(config.LLMConfig{BaseURL: plainSrv.URL, Model: "qwen3-max"})
|
||||
if _, err := plainAd.Chat(context.Background(), Request{
|
||||
Model: "qwen3-max",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "qwen3-max",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
Thinking: &Thinking{Enable: boolPtr(false)},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
body := (<-ch).body
|
||||
for _, key := range []string{"enable_thinking", "chat_template_kwargs", "extra_body", "thinking"} {
|
||||
if _, present := body[key]; present {
|
||||
t.Errorf("body.%s = %v, want the request unchanged", key, body[key])
|
||||
}
|
||||
}
|
||||
if len(body) != len((<-plain).body) {
|
||||
t.Errorf("request shape changed with a thinking directive: %v", body)
|
||||
}
|
||||
rec := buf.String()
|
||||
for _, want := range []string{"level=WARN", "enable_thinking", "qwen"} {
|
||||
if !strings.Contains(rec, want) {
|
||||
t.Errorf("log %q missing %q", rec, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpenAIChat_ThinkingBudgetReportedIgnored asserts a token budget (an
|
||||
// Anthropic-style directive) is reported as unmappable on an OpenAI-compatible
|
||||
// endpoint rather than silently dropped.
|
||||
func TestOpenAIChat_ThinkingBudgetReportedIgnored(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan capturedRequest, 1)
|
||||
srv := newCompletionServer(t, http.StatusOK, "application/json", okCompletion, ch)
|
||||
log, buf := captureLog()
|
||||
ad := NewOpenAIChat(config.LLMConfig{BaseURL: srv.URL, Model: "gpt-4o"}, WithOpenAILogger(log))
|
||||
|
||||
if _, err := ad.Chat(context.Background(), Request{
|
||||
Model: "gpt-4o",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
Thinking: &Thinking{BudgetTokens: 8192},
|
||||
}, Options{}); err != nil {
|
||||
t.Fatalf("Chat error: %v", err)
|
||||
}
|
||||
if _, present := (<-ch).body["thinking"]; present {
|
||||
t.Fatal("body.thinking was sent to an OpenAI-compatible endpoint")
|
||||
}
|
||||
rec := buf.String()
|
||||
for _, want := range []string{"level=WARN", "thinking.budget_tokens", "gpt"} {
|
||||
if !strings.Contains(rec, want) {
|
||||
t.Errorf("log %q missing %q", rec, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthropicChatStream_ThinkingBudgetLeavesRoomForTheAnswer runs the same
|
||||
// red-line check on the streaming path, which builds its own request body.
|
||||
func TestAnthropicChatStream_ThinkingBudgetLeavesRoomForTheAnswer(t *testing.T) {
|
||||
t.Parallel()
|
||||
ch := make(chan anthropicCaptured, 1)
|
||||
const sse = "event: message_start\ndata: {\"type\":\"message_start\"}\n\n" +
|
||||
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n" +
|
||||
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n" +
|
||||
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
|
||||
srv := newAnthropicServer(t, http.StatusOK, "text/event-stream", sse, ch)
|
||||
ad := NewAnthropicChat(config.LLMConfig{AnthropicBaseURL: srv.URL, AnthropicModel: "claude-test"})
|
||||
|
||||
if _, err := ad.ChatStream(context.Background(), Request{
|
||||
Model: "claude-test",
|
||||
Messages: []Message{TextMessage(RoleUser, "hi")},
|
||||
MaxTokens: 2048,
|
||||
Thinking: &Thinking{BudgetTokens: 2048},
|
||||
}, func(StreamEvent) {}); err != nil {
|
||||
t.Fatalf("ChatStream error: %v", err)
|
||||
}
|
||||
body := (<-ch).body
|
||||
think, ok := body["thinking"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("stream body.thinking = %v, want an enabled directive", body["thinking"])
|
||||
}
|
||||
gotBudget, _ := think["budget_tokens"].(float64)
|
||||
maxTokens, _ := body["max_tokens"].(float64)
|
||||
if gotBudget >= maxTokens {
|
||||
t.Fatalf("stream max_tokens = %v, want > budget_tokens %v", maxTokens, gotBudget)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReasoningVendorFor_Classification locks the vendor detection the whitelist
|
||||
// depends on, including the fallback to the base URL.
|
||||
func TestReasoningVendorFor_Classification(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cases := []struct {
|
||||
model string
|
||||
baseURL string
|
||||
want reasoningVendor
|
||||
}{
|
||||
{model: "deepseek-reasoner", want: vendorDeepSeek},
|
||||
{model: "Qwen3-Max", want: vendorQwen},
|
||||
{model: "gpt-4o", want: vendorOpenAI},
|
||||
{model: "o3-mini", want: vendorOpenAI},
|
||||
{model: "chatgpt-4o-latest", want: vendorOpenAI},
|
||||
{model: "claude-sonnet-4", baseURL: "https://api.openai.com/v1", want: vendorOpenAI},
|
||||
{model: "qwen-plus", baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", want: vendorQwen},
|
||||
{model: "some-model", baseURL: "https://api.deepseek.com/v1", want: vendorDeepSeek},
|
||||
{model: "some-model", baseURL: "http://localhost:8000/v1", want: vendorUnknown},
|
||||
}
|
||||
for _, tt := range cases {
|
||||
if got := reasoningVendorFor(tt.model, tt.baseURL); got != tt.want {
|
||||
t.Errorf("reasoningVendorFor(%q, %q) = %q, want %q", tt.model, tt.baseURL, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,7 +141,7 @@ func (m *RuntimeLLM) swap(groups []runtimeconfig.Group) error {
|
||||
if len(groups) == 0 {
|
||||
groups = runtimeconfig.GroupFromEnv(m.env)
|
||||
}
|
||||
snap, err := buildSnapshot(groups, m.env)
|
||||
snap, err := buildSnapshot(groups, m.env, m.log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -162,10 +162,10 @@ func (m *RuntimeLLM) load() *runtimeChainSnapshot {
|
||||
// without a base URL/model yields a nil chain (no model configured), surfaced as
|
||||
// ErrNoModel by the adapter methods. The Router keeps the env vision model so a
|
||||
// dedicated vision model survives a reload that only changes the vendor group.
|
||||
func buildSnapshot(groups []runtimeconfig.Group, env config.LLMConfig) (*runtimeChainSnapshot, error) {
|
||||
func buildSnapshot(groups []runtimeconfig.Group, env config.LLMConfig, log *slog.Logger) (*runtimeChainSnapshot, error) {
|
||||
active := groups[0]
|
||||
cfg := active.ToLLMConfig()
|
||||
chain, err := NewChatChain(cfg)
|
||||
chain, err := NewChatChainWithLog(cfg, log)
|
||||
if err != nil && !errors.Is(err, ErrNoModel) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/persona/loader"
|
||||
)
|
||||
|
||||
// TestPersonaUpsertRequest_ThinkingRoundTripsThroughYAML pins the admin persona
|
||||
// write path for the optional `thinking` block: the hand-written DTO maps into
|
||||
// the loader struct, yaml.Marshal emits the documented keys, and the reload of
|
||||
// that YAML yields the same values — i.e. the field really round-trips instead of
|
||||
// being dropped by an un-whitelisted DTO.
|
||||
func TestPersonaUpsertRequest_ThinkingRoundTripsThroughYAML(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
show := false
|
||||
req := personaUpsertRequest{
|
||||
ID: "xilian", Name: "昔涟", Role: "r", SystemPrompt: "s",
|
||||
Thinking: &personaThinkingRequest{BudgetTokens: 4096, Effort: " medium ", ShowToUser: &show, Mode: " on "},
|
||||
}
|
||||
p := personaFromRequest(req)
|
||||
if err := p.ValidateThinking(); err != nil {
|
||||
t.Fatalf("ValidateThinking() error: %v", err)
|
||||
}
|
||||
data, err := yaml.Marshal(p)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal: %v", err)
|
||||
}
|
||||
back := &loader.Persona{}
|
||||
if err := yaml.Unmarshal(data, back); err != nil {
|
||||
t.Fatalf("Unmarshal: %v", err)
|
||||
}
|
||||
if back.Thinking.BudgetTokens != 4096 || back.Thinking.Mode != loader.ThinkingModeOn || back.Thinking.Effort != "medium" {
|
||||
t.Fatalf("thinking = %+v, want 4096/on/medium", back.Thinking)
|
||||
}
|
||||
if back.Thinking.ShowToUser == nil || *back.Thinking.ShowToUser {
|
||||
t.Fatalf("showToUser = %v, want an explicit false", back.Thinking.ShowToUser)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPersonaUpsertRequest_ThinkingInvalidRejected asserts an invalid thinking
|
||||
// block is rejected through the same validation the loader uses, so the admin API
|
||||
// cannot persist a mode the runtime would refuse to load.
|
||||
func TestPersonaUpsertRequest_ThinkingInvalidRejected(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
p := personaFromRequest(personaUpsertRequest{
|
||||
ID: "x", Name: "x", Role: "r", Thinking: &personaThinkingRequest{Mode: "always"},
|
||||
})
|
||||
err := p.ValidateThinking()
|
||||
if err == nil {
|
||||
t.Fatal("ValidateThinking() = nil, want an error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "always") {
|
||||
t.Fatalf("error %q does not name the offending mode", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPersonaUpsertRequest_NoThinkingBlockOmitsTheKey asserts a request without a
|
||||
// thinking block produces none in the YAML, so no existing persona file gains a
|
||||
// noise section.
|
||||
func TestPersonaUpsertRequest_NoThinkingBlockOmitsTheKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
data, err := yaml.Marshal(personaFromRequest(personaUpsertRequest{ID: "x", Name: "x", Role: "r", SystemPrompt: "s"}))
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal: %v", err)
|
||||
}
|
||||
if strings.Contains(string(data), "thinking") {
|
||||
t.Fatalf("marshaled persona carries a thinking block:\n%s", data)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyThinkingEdit_PreservesOnOmission is the non-destructive update rule: a
|
||||
// client that omits `thinking` keeps the stored block, an explicit block replaces
|
||||
// it, and an all-default block clears it.
|
||||
func TestApplyThinkingEdit_PreservesOnOmission(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
show := false
|
||||
stored := &loader.Persona{Thinking: loader.ThinkingParams{BudgetTokens: 8192, Mode: loader.ThinkingModeOn, ShowToUser: &show}}
|
||||
|
||||
kept := applyThinkingEdit(nil, stored)
|
||||
if kept.BudgetTokens != 8192 || kept.Mode != loader.ThinkingModeOn || kept.ShowToUser == nil {
|
||||
t.Fatalf("applyThinkingEdit(nil, stored) = %+v, want the stored block", kept)
|
||||
}
|
||||
replaced := applyThinkingEdit(&personaThinkingRequest{BudgetTokens: 1024, Mode: "off"}, stored)
|
||||
if replaced.BudgetTokens != 1024 || replaced.Mode != loader.ThinkingModeOff || replaced.ShowToUser != nil {
|
||||
t.Fatalf("applyThinkingEdit(explicit, stored) = %+v, want the request block", replaced)
|
||||
}
|
||||
cleared := applyThinkingEdit(&personaThinkingRequest{}, stored)
|
||||
if cleared.BudgetTokens != 0 || cleared.Mode != "" || cleared.ShowToUser != nil {
|
||||
t.Fatalf("applyThinkingEdit(empty object, stored) = %+v, want the zero block", cleared)
|
||||
}
|
||||
if created := applyThinkingEdit(nil, nil); created.BudgetTokens != 0 || created.ShowToUser != nil {
|
||||
t.Fatalf("applyThinkingEdit(nil, nil) = %+v, want the zero block (create path)", created)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,19 @@ type personaUpsertRequest struct {
|
||||
Modes []string `json:"modes"`
|
||||
Mode string `json:"mode"`
|
||||
MemoryNS string `json:"memoryNamespace"`
|
||||
// Thinking is the optional reasoning/presentation block (design/01 §2.1). It
|
||||
// is persisted into the persona YAML as-is; omitting it on an update keeps the
|
||||
// stored block (see adminUpdatePersona).
|
||||
Thinking *personaThinkingRequest `json:"thinking,omitempty"`
|
||||
}
|
||||
|
||||
// personaThinkingRequest is the wire form of the persona `thinking` section. The
|
||||
// pointers/naming mirror the YAML so a panel can round-trip it verbatim.
|
||||
type personaThinkingRequest struct {
|
||||
BudgetTokens int `json:"budgetTokens,omitempty"`
|
||||
Effort string `json:"effort,omitempty"`
|
||||
ShowToUser *bool `json:"showToUser,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
}
|
||||
|
||||
// adminCreatePersona registers a new persona in the registry (real runtime
|
||||
@@ -65,6 +78,11 @@ func (s *Server) adminCreatePersona(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p := personaFromRequest(req)
|
||||
if err := p.ValidateThinking(); err != nil {
|
||||
s.auditClaims(r, "persona.create", "error")
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid thinking config: %v", err))
|
||||
return
|
||||
}
|
||||
if err := savePersonaYAML(p); err != nil {
|
||||
s.auditClaims(r, "persona.create", "error")
|
||||
s.log.Error("persona persist", "id", req.ID, "err", err)
|
||||
@@ -112,6 +130,16 @@ func (s *Server) adminUpdatePersona(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
p := personaFromRequest(req)
|
||||
if err := p.ValidateThinking(); err != nil {
|
||||
s.auditClaims(r, "persona.update", "error")
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid thinking config: %v", err))
|
||||
return
|
||||
}
|
||||
// A client that does not know the optional `thinking` block (an older panel, a
|
||||
// script) omits it; keep the stored one instead of silently wiping a
|
||||
// hand-edited config. Sending the object replaces it, and sending it with all
|
||||
// fields default clears it.
|
||||
p.Thinking = applyThinkingEdit(req.Thinking, existingPersona(reg, id))
|
||||
if err := savePersonaYAML(p); err != nil {
|
||||
s.auditClaims(r, "persona.update", "error")
|
||||
s.log.Error("persona persist", "id", id, "err", err)
|
||||
@@ -223,9 +251,46 @@ func personaFromRequest(req personaUpsertRequest) *loader.Persona {
|
||||
Background: req.Background,
|
||||
Values: req.Values,
|
||||
Emotion: loader.EmotionParams{MemoryNamespace: strings.TrimSpace(req.MemoryNS)},
|
||||
Thinking: thinkingFromRequest(req.Thinking),
|
||||
}
|
||||
}
|
||||
|
||||
// thinkingFromRequest maps the wire `thinking` block onto the persona field; a
|
||||
// missing block yields the zero value, which yaml.Marshal omits entirely.
|
||||
func thinkingFromRequest(req *personaThinkingRequest) loader.ThinkingParams {
|
||||
if req == nil {
|
||||
return loader.ThinkingParams{}
|
||||
}
|
||||
return loader.ThinkingParams{
|
||||
BudgetTokens: req.BudgetTokens,
|
||||
Effort: strings.TrimSpace(req.Effort),
|
||||
ShowToUser: req.ShowToUser,
|
||||
Mode: strings.TrimSpace(req.Mode),
|
||||
}
|
||||
}
|
||||
|
||||
// existingPersona returns the stored persona for id, or nil when it is absent.
|
||||
func existingPersona(reg *personareg.Registry, id string) *loader.Persona {
|
||||
if p, ok := reg.Persona(id); ok {
|
||||
return p
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyThinkingEdit returns the `thinking` block an update should persist: the
|
||||
// request's own block when it carries one, otherwise the stored persona's block —
|
||||
// so a client that does not know the optional field can never wipe it. An update
|
||||
// that sends the object replaces the block outright (all-default fields clear it).
|
||||
func applyThinkingEdit(req *personaThinkingRequest, existing *loader.Persona) loader.ThinkingParams {
|
||||
if req != nil {
|
||||
return thinkingFromRequest(req)
|
||||
}
|
||||
if existing != nil {
|
||||
return existing.Thinking
|
||||
}
|
||||
return loader.ThinkingParams{}
|
||||
}
|
||||
|
||||
// characterFromRequest builds the registry.Character bound to the persona.
|
||||
func characterFromRequest(req personaUpsertRequest) *personareg.Character {
|
||||
modes := append([]string(nil), req.Modes...)
|
||||
|
||||
Reference in new issue
Block a user