feat: expose configurable reasoning effort

This commit is contained in:
Jason Xu committed 2026-09-21 14:34:00 +08:00
1 parent e5f4e3a583
commit 683b7e9af0
10 files changed
+684 -36

No files matched your search

+35
View File
@@ -231,6 +231,41 @@ See [config.example.json](config.example.json) for a complete starting configura
| `proxyfile` | Optional; relative paths resolve beside the configuration file. |
| `models.refresh_seconds` | `300`; minimum 1. |
| `models.protocols` | `{}`; per-model native protocol overrides. |
| `reasoning.effort` | Empty (off); `minimal`, `low`, `medium`, `high`, `xhigh`, `max`, or `none`. |
| `reasoning.effort_by_model` | `{}`; per-model overrides of `reasoning.effort`. |
### Forced thinking level
`reasoning.effort` sets the thinking level used upstream when a request does not
state one of its own, and `reasoning.effort_by_model` overrides it for the model
IDs it names. It applies to all three protocols, in either direction of
conversion, and matters most for cross-protocol traffic: an Anthropic
`thinking.budget_tokens` can only be approximated by the Chat and Responses
surfaces, so a forced level reaches a rung that the budget alone cannot express.
```json
{
"reasoning": {
"effort": "high",
"effort_by_model": { "claude-opus-5": "max" }
}
}
```
A level a client states explicitly always wins, so this only replaces a level
nobody asked for: an absent one, or one derived from `thinking.budget_tokens`.
Use `"none"` to remove reasoning from requests that do not ask for it.
Levels are reported faithfully in both directions. An explicit
`output_config.effort` survives conversion instead of being shadowed by a
`thinking` block, `budget_tokens` keeps its rung (`8192` is `high`, `32000` is
`xhigh`, so the two stay distinguishable), and the Responses target carries the
level as `reasoning.effort` rather than dropping it.
The WebUI Configuration Center exposes the same default and per-model fields.
The management API returns them as `reasoning` from `GET /api/config` and accepts
the object in `PUT /api/config`; clients that omit the field keep the existing
value, while sending an empty object clears it.
Proxy entries accept `direct`, `http://`, `https://`, `socks5://`, and `socks5h://`, including URL credentials. The inline list is merged with `proxyfile` and deduplicated in order.
+30
View File
@@ -231,6 +231,36 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K
| `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 |
| `models.refresh_seconds` | `300`;最小为 1。 |
| `models.protocols` | `{}`;按模型 ID 覆盖原生协议。 |
| `reasoning.effort` | 空(关闭);可选 `minimal`、`low`、`medium`、`high`、`xhigh`、`max`、`none`。 |
| `reasoning.effort_by_model` | `{}`;按模型 ID 覆盖 `reasoning.effort`。 |
### 强制思考强度
`reasoning.effort` 在请求自身没有指定思考强度时,指定发往上游的强度;
`reasoning.effort_by_model` 按模型 ID 覆盖它。它对三种协议、两个转换方向都生效,
对跨协议请求尤其重要:Anthropic 的 `thinking.budget_tokens` 只能被 Chat 与
Responses 近似表达,而强制指定的强度可以到达单独靠预算表达不出的档位。
```json
{
"reasoning": {
"effort": "high",
"effort_by_model": { "claude-opus-5": "max" }
}
}
```
客户端显式指定的强度始终优先,因此它只替换无人指定的强度:完全未设置,
或由 `thinking.budget_tokens` 推断出来的强度。设为 `"none"` 可为未请求思考的
请求移除思考配置。
两个方向的强度都会如实保留:显式的 `output_config.effort` 不会再被 `thinking`
块遮蔽,`budget_tokens` 保持其档位(`8192` 为 `high`,`32000` 为 `xhigh`,
两者可区分),发往 Responses 时强度会以 `reasoning.effort` 形式传递而不再丢失。
WebUI 的配置中心也提供默认强度和按模型覆盖。管理 API 的 `GET /api/config`
会返回 `reasoning`,`PUT /api/config` 接受同名对象;省略该字段会保留现有值,
发送空对象则会清除它。
代理支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`,URL 可包含认证信息。配置内代理先加载,再追加 `proxyfile` 内容,并按首次出现的顺序去重。
+13 -6
View File
@@ -1,12 +1,17 @@
{
"listen": "127.0.0.1:8080",
"server_keys": ["change-this-local-key"],
"zen_keys": ["sk-your-zen-key"],
"server_keys": [
"change-this-local-key"
],
"zen_keys": [
"sk-your-zen-key"
],
"go_keys": [],
"anonymous": false,
"prefer": "go",
"proxies": [
"direct"
],
"proxyfile": "",
"proxies": ["direct"],
"upstream": {
"zen": "https://opencode.ai/zen",
"go": "https://opencode.ai/zen/go"
@@ -37,7 +42,9 @@
"enabled": true,
"listen": "0.0.0.0:8081",
"username": "admin",
"password": "change-this-admin-password",
"password_hash": "$argon2id$v=19$m=65536,t=3,p=2$ogomnqeWe2qgf/CdcRNHdw$ZPR9Pfv2uVCJXa6SRr1PqNINZGtkmKk68uXL7quJFNk",
"session_ttl_minutes": 720
}
},
"prefer": "go",
"reasoning": {}
}
+12 -3
View File
@@ -108,6 +108,7 @@ type ConfigView struct {
Performance config.PerformanceConfig `json:"performance"`
Logging config.LoggingConfig `json:"logging"`
Prefer config.Tier `json:"prefer"`
Reasoning config.ReasoningConfig `json:"reasoning"`
WebUI WebUIView `json:"webui"`
Effective EffectiveView `json:"effective"`
Restart []string `json:"restart_required_fields,omitempty"`
@@ -145,7 +146,10 @@ type ConfigUpdate struct {
Performance config.PerformanceConfig `json:"performance"`
Logging config.LoggingConfig `json:"logging"`
Prefer config.Tier `json:"prefer"`
WebUI WebUIView `json:"webui"`
// A pointer distinguishes an omitted field (legacy clients should keep the
// current reasoning configuration) from an explicit empty object (clear it).
Reasoning *config.ReasoningConfig `json:"reasoning,omitempty"`
WebUI WebUIView `json:"webui"`
}
func (a *Server) handleGetConfig(w http.ResponseWriter, _ *http.Request) {
@@ -180,10 +184,15 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
writeAdminError(w, http.StatusBadRequest, "invalid_proxies", err.Error())
return
}
reasoning := current.Reasoning
if update.Reasoning != nil {
reasoning = *update.Reasoning
}
candidate := config.Config{
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile,
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
Reasoning: reasoning,
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
}
result, err := a.manager.Apply(candidate, true)
if err != nil {
@@ -308,7 +317,7 @@ func (a *Server) configView() ConfigView {
return ConfigView{
Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous,
Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models,
Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer,
Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning,
WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes},
Effective: EffectiveView{Listen: effective.API, WebUIListen: effective.WebUI, WebUIEnabled: effective.WebUIEnabled},
Restart: restart,
+83
View File
@@ -30,10 +30,28 @@ type Config struct {
Logging LoggingConfig `json:"logging"`
WebUI WebUIConfig `json:"webui"`
Prefer Tier `json:"prefer"`
// Reasoning configures a forced thinking level. Both fields are optional
// and empty by default, so an existing configuration keeps the client's own
// level untouched.
Reasoning ReasoningConfig `json:"reasoning"`
effectiveProxies []string
}
// ReasoningConfig forces a thinking level for requests that do not state one.
//
// Effort is the default for every model; EffortByModel overrides it for the
// model IDs it names. A level a client sends explicitly (Anthropic's
// output_config.effort / top-level effort, or Chat's reasoning_effort) always
// wins, so a forced level only replaces a value that would otherwise have been
// derived from thinking.budget_tokens or left unset.
type ReasoningConfig struct {
// omitempty keeps a saved configuration free of the fields the operator
// never set, matching how the rest of the optional surface is persisted.
Effort string `json:"effort,omitempty"`
EffortByModel map[string]string `json:"effort_by_model,omitempty"`
}
type UpstreamConfig struct {
Zen string `json:"zen"`
Go string `json:"go"`
@@ -218,9 +236,67 @@ func Normalize(path string, cfg Config) (Config, error) {
return Config{}, fmt.Errorf("models.protocols contains invalid mapping %q: %q", model, protocol)
}
}
if err := normalizeReasoning(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
// normalizeReasoning validates and canonicalizes the forced thinking level.
//
// Levels are stored lowercased so the hot path can compare them without
// allocating. An empty value means "not forced", which is the default and keeps
// the feature absent for existing configurations.
func normalizeReasoning(cfg *Config) error {
cfg.Reasoning.Effort = strings.ToLower(strings.TrimSpace(cfg.Reasoning.Effort))
if err := validateEffort("reasoning.effort", cfg.Reasoning.Effort); err != nil {
return err
}
if cfg.Reasoning.EffortByModel == nil {
return nil
}
// An empty map is the same as an absent one, and writing nil back keeps a
// saved configuration free of a field the user never set.
if len(cfg.Reasoning.EffortByModel) == 0 {
cfg.Reasoning.EffortByModel = nil
return nil
}
normalized := make(map[string]string, len(cfg.Reasoning.EffortByModel))
for model, effort := range cfg.Reasoning.EffortByModel {
key := strings.TrimSpace(model)
if key == "" {
return errors.New("reasoning.effort_by_model must not contain an empty model ID")
}
level := strings.ToLower(strings.TrimSpace(effort))
if err := validateEffort(fmt.Sprintf("reasoning.effort_by_model[%q]", key), level); err != nil {
return err
}
normalized[key] = level
}
cfg.Reasoning.EffortByModel = normalized
return nil
}
// validateEffort accepts the levels the OpenAI and Anthropic surfaces define
// plus an empty string, which means "not forced".
func validateEffort(name, value string) error {
switch value {
case "", "minimal", "low", "medium", "high", "xhigh", "max", "none":
return nil
default:
return fmt.Errorf("%s must be one of minimal, low, medium, high, xhigh, max, none, or empty to disable the override", name)
}
}
// ForcedEffort returns the level the operator forced for a model, or an empty
// string when none applies. A stored level is already lowercase.
func (cfg Config) ForcedEffort(model string) string {
if effort, ok := cfg.Reasoning.EffortByModel[model]; ok {
return effort
}
return cfg.Reasoning.Effort
}
// RuntimeProxies returns the resolved proxy list, including proxyfile entries.
// Config.Proxies intentionally remains the list stored in config.json so a
// save never duplicates values loaded from proxyfile.
@@ -253,5 +329,12 @@ func Clone(cfg Config) Config {
}
cfg.Models.Protocols = protocols
}
if cfg.Reasoning.EffortByModel != nil {
efforts := make(map[string]string, len(cfg.Reasoning.EffortByModel))
for model, effort := range cfg.Reasoning.EffortByModel {
efforts[model] = effort
}
cfg.Reasoning.EffortByModel = efforts
}
return cfg
}
+3
View File
@@ -283,6 +283,9 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp
}
return nil, fmt.Errorf("prepare %s upstream request: %w", tier, err)
}
if effort := g.cfg.ForcedEffort(jsonutil.StringAt(upstreamPayload, "model")); effort != "" {
wire.ForcedEffort(protocol, upstreamPayload, effort)
}
encoded, err := json.Marshal(upstreamPayload)
if err != nil {
return nil, errors.New("request contains unsupported JSON values")
+227 -21
View File
@@ -190,9 +190,18 @@ func responsesTextFormat(format any) any {
}
}
// reasoningEffort projects a bridge-level reasoning value onto the OpenAI Chat
// "reasoning_effort" field.
//
// Precedence matters: a level the client stated explicitly (the "effort" field,
// whether or not it arrived next to a thinking block) wins over anything
// inferred from a thinking budget. Before this, an Anthropic request carrying
// both thinking.budget_tokens and output_config.effort threw the explicit
// effort away and reported the budget bucket instead, so a client asking for
// "max" was served as "high".
func reasoningEffort(value any) any {
if object, ok := value.(map[string]any); ok {
if effort := object["effort"]; effort != nil {
if effort, ok := explicitEffort(object); ok {
return effort
}
switch jsonutil.StringAt(object, "type") {
@@ -204,45 +213,242 @@ func reasoningEffort(value any) any {
return object["type"]
}
}
if effort, ok := normalizeEffortValue(value); ok {
return effort
}
return value
}
// explicitEffort reports the effort a client stated verbatim in a reasoning
// object and whether the object carried one at all. A stated effort outranks a
// budget, including inside a thinking block that also has budget_tokens:
// budget 2048 plus effort "max" is a request for "max", not for "low".
//
// The second return is ok, not "effort != nil": the stated value nil means the
// client named "none"/"disabled" explicitly, which must clear an inferred level
// rather than fall through to it.
func explicitEffort(object map[string]any) (any, bool) {
for _, key := range []string{"effort", "reasoning_effort"} {
if value, exists := object[key]; exists {
if effort, ok := normalizeEffortValue(value); ok {
return effort, true
}
}
}
return nil, false
}
// normalizeEffortValue validates an effort a client stated explicitly. A
// non-empty string is passed through verbatim (case preserved) so unsupported
// levels are not silently rewritten or dropped; only "none"/"disabled" mean
// "no reasoning" and clear the value. Everything else, nil included, reports
// ok=false so the caller can fall back to a budget-derived level.
func normalizeEffortValue(value any) (any, bool) {
text, ok := value.(string)
if !ok {
return nil, false
}
switch strings.ToLower(strings.TrimSpace(text)) {
case "none", "disabled":
// Explicitly no reasoning: clear any inferred level instead of
// resurrecting one from a budget.
return nil, true
case "":
return nil, false
}
return value, true
}
// anthropicThinking maps a bridge-level reasoning value back onto the Anthropic
// "thinking" block plus the "output_config" that carries the effort natively.
//
// The budget reproduced here keeps the Anthropic payload self-consistent and
// mirrors what the inverse direction (effortForThinkingBudget) reads back, so
// the two are inverse on every rung. A budget the client originally named is
// restored verbatim rather than re-derived from the level, so an Anthropic ->
// Chat -> Anthropic round trip does not rewrite 32000 into an 8192 rung.
//
// The emitted number is a float64 because that is the shape a decoded JSON
// number has, which keeps converted payloads indistinguishable from the ones
// that came in through a same-protocol passthrough.
func anthropicThinking(value any) (any, map[string]any) {
if value == nil {
return nil, nil
}
budget := 0
if object, ok := value.(map[string]any); ok {
kind := jsonutil.StringAt(object, "type")
if kind == "enabled" || kind == "adaptive" || kind == "disabled" {
return value, nil
// A budget is what makes the round trip lossless, so it is read before
// the effort: a value that reached the bridge as a thinking block still
// names the budget the client sent, and re-deriving one from the level
// would fold 32000 back down to the 16384 rung.
budget = jsonutil.IntAt(object, "budget_tokens")
if effort, stated := explicitEffort(object); stated {
// "none"/"disabled" clears the reasoning configuration entirely.
if effort == nil {
return nil, nil
}
return thinkingFor(effort, budget), map[string]any{"effort": effort}
}
value = jsonutil.FirstAny(object["effort"], object["type"])
if kind == "disabled" {
return nil, nil
}
// A level carried in "type" (Chat's {"reasoning":{"type":"high"}}), or a
// one-sided {"type":"enabled"} whose only control is its budget.
if effort, stated := normalizeEffortValue(object["type"]); stated {
if effort == nil {
return nil, nil
}
return thinkingFor(effort, budget), map[string]any{"effort": effort}
}
if budget > 0 {
return thinkingFor(effortForThinkingBudget(budget), budget),
map[string]any{"effort": effortForThinkingBudget(budget)}
}
value = object["type"]
}
effort, _ := value.(string)
effort = strings.ToLower(strings.TrimSpace(effort))
if effort == "" || effort == "none" || effort == "disabled" {
effort, ok := normalizeEffortValue(value)
if !ok {
if number, isNumber := numericValue(value); isNumber {
// A reasoning value that only carries a budget: keep the budget and
// publish the level it maps to, so no rung is invented.
if number <= 0 {
return nil, nil
}
return thinkingFor(effortForThinkingBudget(number), number),
map[string]any{"effort": effortForThinkingBudget(number)}
}
// Not an effort string (for example a bool): nothing to say about
// reasoning, so stay silent rather than inventing a level.
return nil, nil
}
budget := 4096
switch effort {
case "minimal", "low":
budget = 1024
case "medium":
budget = 4096
case "high", "xhigh", "max":
budget = 8192
if effort == nil {
// "none"/"disabled".
return nil, nil
}
return map[string]any{"type": "enabled", "budget_tokens": budget}, map[string]any{"effort": effort}
return thinkingFor(effort, budget), map[string]any{"effort": effort}
}
func effortForThinkingBudget(budget int) string {
if budget <= 0 || budget >= 8192 {
return "high"
// thinkingFor builds the Anthropic "thinking" block for an effort, reusing the
// budget the client named when there is one and synthesizing the rung's
// lower bound otherwise.
func thinkingFor(effort any, budget int) map[string]any {
if budget <= 0 {
budget = budgetForEffort(effort)
}
if budget <= 2048 {
return map[string]any{"type": "enabled", "budget_tokens": float64(budget)}
}
// reasoningBudget reports the thinking budget a bridge-level reasoning value
// names, or 0 when the value carries none.
func reasoningBudget(value any) int {
object, ok := value.(map[string]any)
if !ok {
return 0
}
if budget := jsonutil.IntAt(object, "budget_tokens"); budget > 0 {
return budget
}
if _, ok := explicitEffort(object); !ok {
return 0
}
// An effort states a level, not a budget. A Chat client that sends only
// {"reasoning_effort":"high"} has no budget to carry.
return numericValueOrZero(object["reasoning_budget_tokens"])
}
// withReasoningBudget attaches a budget to a bridge-level reasoning value,
// keeping any effort already present alongside it.
func withReasoningBudget(value any, budget int) any {
if budget <= 0 {
return value
}
switch typed := value.(type) {
case map[string]any:
merged := make(map[string]any, len(typed)+1)
for key, existing := range typed {
merged[key] = existing
}
merged["budget_tokens"] = budget
return merged
default:
return map[string]any{"budget_tokens": budget, "effort": value}
}
}
// numericValue reads a JSON number out of a decoded body, which reports every
// number as float64.
func numericValue(value any) (int, bool) {
switch number := value.(type) {
case float64:
return int(number), true
case int:
return number, true
case int64:
return int(number), true
default:
return 0, false
}
}
func numericValueOrZero(value any) int {
number, _ := numericValue(value)
return number
}
// budgetForEffort is the inverse of effortForThinkingBudget: the smallest
// lower-bound budget that maps back to the same rung. Only "high" and above
// need a real number, since Anthropic requires budget_tokens to be at least
// 1024 and a top-of-range budget already means "max".
func budgetForEffort(value any) int {
text, _ := value.(string)
switch strings.ToLower(strings.TrimSpace(text)) {
case "minimal", "low":
return 1024
case "medium":
return 4096
case "high":
return 8192
case "xhigh":
return 16384
case "max":
return 32768
default:
return 4096
}
}
// effortForThinkingBudget buckets an Anthropic thinking budget onto an OpenAI
// reasoning level. The rungs are ordered and pairwise distinct so that a
// budget a client chose deliberately stays distinguishable: before this,
// everything at or above 8192 collapsed to "high" and the ladder had no rung
// above it, so 32000 and 8192 were indistinguishable and an Anthropic -> Chat
// -> Anthropic round trip rewrote 32000 into 8192.
//
// A missing budget keeps the historical "high": thinking:{type:"adaptive"}
// with no budget_tokens is the common shape, and it must not silently change
// level. An explicit "max"/"xhigh" effort is how a client asks for a rung
// above "high", and that path does not consult the budget.
func effortForThinkingBudget(budget int) string {
switch {
case budget <= 0:
return "high"
case budget >= 32768:
return "max"
case budget >= 16384:
return "xhigh"
case budget > 8192:
// 8193..16383 sits above the old "high" boundary; folding it into
// "high" would report a larger budget as the same level.
return "high"
case budget >= 8192:
// The threshold itself keeps its historical bucket.
return "high"
case budget > 2048:
return "medium"
default:
return "low"
}
return "medium"
}
func bridgeBlocksText(blocks []bridgeBlock) string {
+238 -6
View File
@@ -23,6 +23,127 @@ func PrepareRequest(from, to Protocol, input map[string]any, upstreamURL string)
return output, nil
}
// ForcedEffort applies an operator-configured thinking level to a prepared
// upstream body, so a client can be served at a fixed level without the client
// cooperating.
//
// A level the client stated explicitly always wins. That is what the "forced"
// level is for: replacing a level nobody actually asked for, either because the
// request said nothing about reasoning or because the conversion had to derive
// one from thinking.budget_tokens. It is applied to the finished upstream body
// rather than to the bridge value because the same-protocol path never goes
// through the bridge, and only there can the client's own body be seen.
func ForcedEffort(protocol Protocol, body map[string]any, effort string) {
if body == nil {
return
}
effort = strings.ToLower(strings.TrimSpace(effort))
if !validForcedEffort(effort) {
return
}
disable := effort == "none"
switch protocol {
case Chat:
if clientEffortExplicit(protocol, body) {
return
}
if disable {
delete(body, "reasoning_effort")
return
}
body["reasoning_effort"] = effort
case Anthropic:
if clientEffortExplicit(protocol, body) {
return
}
applyAnthropicForcedEffort(body, effort, disable)
case Responses:
if clientEffortExplicit(protocol, body) {
return
}
if disable {
delete(body, "reasoning")
return
}
reasoning, _ := body["reasoning"].(map[string]any)
if reasoning == nil {
reasoning = map[string]any{}
body["reasoning"] = reasoning
}
reasoning["effort"] = effort
}
}
// clientEffortExplicit reports whether an upstream body already carries a level
// the client stated, as opposed to one the gateway derived from a budget.
//
// The shapes differ per protocol, and each one mirrors how that protocol
// expressed the level natively: Anthropic states it in output_config.effort (or
// a top-level effort), Chat in a bare reasoning_effort string, and Responses in
// reasoning.effort. Anything else in those slots is a structural value the
// conversion produced, which a forced level is allowed to replace.
func clientEffortExplicit(protocol Protocol, body map[string]any) bool {
switch protocol {
case Chat:
_, ok := body["reasoning_effort"].(string)
return ok
case Anthropic:
if effort, ok := jsonutil.AnyAt(body, "output_config", "effort").(string); ok && strings.TrimSpace(effort) != "" {
return true
}
effort, ok := body["effort"].(string)
return ok && strings.TrimSpace(effort) != ""
case Responses:
_, ok := jsonutil.AnyAt(body, "reasoning", "effort").(string)
return ok
default:
return false
}
}
// applyAnthropicForcedEffort writes a forced level into an Anthropic body and
// keeps the thinking block and max_tokens consistent with it.
//
// Anthropic represents a level as output_config.effort, but also requires a
// thinking block to carry a budget and requires max_tokens to exceed that
// budget. Forcing a level therefore has to move all three together, or the
// upstream rejects the request it was just told to run at a higher level.
func applyAnthropicForcedEffort(body map[string]any, effort string, disable bool) {
if disable {
delete(body, "thinking")
delete(body, "output_config")
return
}
if outputConfig, _ := body["output_config"].(map[string]any); outputConfig == nil {
body["output_config"] = map[string]any{"effort": effort}
} else {
outputConfig["effort"] = effort
}
budget := budgetForEffort(effort)
if thinking, ok := body["thinking"].(map[string]any); ok {
thinking["type"] = "enabled"
thinking["budget_tokens"] = float64(budget)
} else {
body["thinking"] = map[string]any{"type": "enabled", "budget_tokens": float64(budget)}
}
// max_tokens must stay strictly greater than the thinking budget, otherwise
// Anthropic rejects the payload regardless of the requested effort.
if current := jsonutil.IntAt(body, "max_tokens"); current > 0 && current <= budget {
body["max_tokens"] = budget + 4096
}
}
// validForcedEffort accepts the levels the configuration can force. "none" is
// the escape hatch that removes reasoning again.
func validForcedEffort(effort string) bool {
switch effort {
case "minimal", "low", "medium", "high", "xhigh", "max", "none":
return true
default:
return false
}
}
// normalizeToolReasoningHistory applies only to endpoints that are known to
// require reasoning replay, or to requests that explicitly enable reasoning.
// Normalizing the target shape makes the behavior independent of the client
@@ -193,6 +314,35 @@ func anthropicContentHasType(content []any, kind string) bool {
return false
}
// anthropicReasoning decodes the reasoning controls of an Anthropic Messages
// request into a single bridge-level value.
//
// An effort the client states explicitly outranks a thinking block's budget.
// Choosing input["thinking"] first (as this used to) shadowed
// output_config.effort and a top-level effort entirely, so `thinking:
// {adaptive}` plus `output_config: {effort: "max"}` decoded as the thinking
// block and was reported downstream as the budget bucket "high".
func anthropicReasoning(input map[string]any) any {
stated := jsonutil.FirstAny(jsonutil.AnyAt(input, "output_config", "effort"), input["effort"])
if effort, ok := normalizeEffortValue(stated); ok {
// The explicit effort survives next to the thinking block's budget so
// nothing the client said is lost on the way to the bridge.
if effort == nil {
return nil
}
if thinking, ok := input["thinking"].(map[string]any); ok {
merged := make(map[string]any, len(thinking)+1)
for key, value := range thinking {
merged[key] = value
}
merged["effort"] = effort
return merged
}
return effort
}
return input["thinking"]
}
func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) {
request := bridgeRequest{
Model: jsonutil.StringAt(input, "model"),
@@ -218,6 +368,12 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
}
if role == "assistant" {
blocks = append(decodeChatReasoning(message), blocks...)
// A budget the gateway carried out on the assistant message is
// read back next to the effort, so both directions agree on the
// level the client originally named.
if budget := jsonutil.IntAt(message, "reasoning_budget_tokens"); budget > 0 {
request.Reasoning = withReasoningBudget(request.Reasoning, budget)
}
}
for j, rawCall := range jsonutil.SliceAt(message, "tool_calls") {
call, ok := rawCall.(map[string]any)
@@ -352,7 +508,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
case Anthropic:
request.MaxTokens = input["max_tokens"]
request.Stop = input["stop_sequences"]
request.Reasoning = jsonutil.FirstAny(input["thinking"], jsonutil.AnyAt(input, "output_config", "effort"), input["effort"])
request.Reasoning = anthropicReasoning(input)
blocks, err := decodeAnthropicBlocksChecked(input["system"])
if err != nil {
return request, fmt.Errorf("system: %w", err)
@@ -505,6 +661,21 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
pendingResults := make(map[string]bridgeBlock)
var pendingOrder []string
var deferred [][]bridgeBlock
// Anthropic's reasoning controls belong to a whole conversation, but Chat
// carries a single reasoning_effort for the request. The budget the client
// named is emitted once, on the first assistant message, so that decoding
// this Chat body back into Anthropic can restore the level exactly instead
// of re-deriving it from a bucket (32000 used to come back as 8192).
budgetCarried := false
carryBudget := func(encoded map[string]any) {
if budgetCarried {
return
}
if budget := reasoningBudget(request.Reasoning); budget > 0 {
encoded["reasoning_budget_tokens"] = budget
budgetCarried = true
}
}
flushDeferred := func() {
for _, blocks := range deferred {
if len(blocks) > 0 {
@@ -513,6 +684,24 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
}
deferred = nil
}
// A conversation can end before any assistant turn exists to carry the
// budget. Attaching it to an empty assistant message keeps it on the wire
// without inventing visible output; Chat clients treat the empty turn as an
// assistant prefill.
carryBudgetOnly := func() {
if budgetCarried {
return
}
if budget := reasoningBudget(request.Reasoning); budget <= 0 {
return
}
encoded := map[string]any{"role": "assistant", "content": nil}
carryBudget(encoded)
if encoded["reasoning_budget_tokens"] == nil {
return
}
messages = append(messages, encoded)
}
for i, message := range request.Messages {
var content, reasoning, calls, results []bridgeBlock
@@ -536,6 +725,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
return nil, fmt.Errorf("messages[%d]: assistant message contains tool results", i)
}
encoded := map[string]any{"role": "assistant", "content": nil}
carryBudget(encoded)
if value, ok := bridgeReasoningText(reasoning); ok {
encoded["reasoning_content"] = value
}
@@ -566,6 +756,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
}
if len(content) > 0 || len(reasoning) > 0 || len(calls) > 0 {
messages = append(messages, encoded)
budgetCarried = true
}
continue
}
@@ -608,6 +799,7 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) {
return nil, fmt.Errorf("tool calls are missing results for %s", strings.Join(missingToolIDs(pendingOrder, pending), ", "))
}
flushDeferred()
carryBudgetOnly()
output["messages"] = messages
if len(request.Tools) > 0 {
@@ -657,6 +849,49 @@ func missingToolIDs(order []string, pending map[string]bool) []string {
return missing
}
// responsesReasoning builds the Responses "reasoning" object.
//
// A bare effort string, or a thinking-style block that carries budget_tokens
// but no effort, is projected onto "reasoning.effort". Copying such a block
// through verbatim (the old behavior) forwarded {"type":"adaptive"} and dropped
// the effort completely, so a client asking for "max" reached the upstream with
// no reasoning configuration at all.
func responsesReasoning(value any) any {
if object, ok := value.(map[string]any); ok {
if jsonutil.StringAt(object, "type") == "disabled" {
return object
}
// "effort" is authoritative here for the same reason as in
// encodeChatRequest: it either came from the client verbatim or was
// derived from the budget by reasoningEffort.
if effort := reasoningEffort(object); effort != nil {
switch typed := effort.(type) {
case string:
return map[string]any{"effort": typed}
case map[string]any:
return typed
default:
return map[string]any{"effort": typed}
}
}
return object
}
switch typed := value.(type) {
case string:
if effort, ok := normalizeEffortValue(typed); ok {
if effort == nil {
return nil
}
return map[string]any{"effort": effort}
}
return map[string]any{"effort": typed}
case map[string]any:
return typed
default:
return value
}
}
func encodeResponsesRequest(request bridgeRequest) map[string]any {
output := map[string]any{"model": request.Model, "stream": request.Stream}
jsonutil.Put(output, "temperature", request.Temperature)
@@ -668,11 +903,8 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any {
output["instructions"] = bridgeBlocksText(request.System)
}
if request.Reasoning != nil {
switch value := request.Reasoning.(type) {
case string:
output["reasoning"] = map[string]any{"effort": value}
default:
output["reasoning"] = value
if reasoning := responsesReasoning(request.Reasoning); reasoning != nil {
output["reasoning"] = reasoning
}
}
if format := responsesTextFormat(request.ResponseFormat); format != nil {
+7
View File
@@ -128,6 +128,9 @@ function fillConfig(value) {
$("#c-timeout").value = value.retry.timeout_seconds;
$("#c-refresh").value = value.models.refresh_seconds;
$("#c-protocols").value = JSON.stringify(value.models.protocols || {}, null, 2);
const reasoning = value.reasoning || {};
$("#c-reasoning-effort").value = reasoning.effort || "";
$("#c-reasoning-by-model").value = JSON.stringify(reasoning.effort_by_model || {}, null, 2);
$("#c-idle").value = value.performance.max_idle_conns;
$("#c-idle-host").value = value.performance.max_idle_conns_per_host;
$("#c-max-host").value = value.performance.max_conns_per_host;
@@ -191,6 +194,10 @@ $("#config-form").addEventListener("submit", async (event) => {
refresh_seconds: number("#c-refresh"),
protocols: JSON.parse($("#c-protocols").value || "{}"),
},
reasoning: {
effort: $("#c-reasoning-effort").value,
effort_by_model: JSON.parse($("#c-reasoning-by-model").value || "{}"),
},
performance: {
max_idle_conns: number("#c-idle"),
max_idle_conns_per_host: number("#c-idle-host"),
+36
View File
@@ -545,6 +545,42 @@
</div>
</div>
</div>
<div class="section">
<div class="section-head">
<div>
<h2>Thinking 强度</h2>
<div class="section-caption">
仅在客户端没有明确指定时生效;按模型覆盖默认值。选择“关闭”会移除未明确请求的 reasoning。
</div>
</div>
</div>
<div class="form-grid">
<div class="field">
<label>默认强度</label
><select id="c-reasoning-effort">
<option value="">跟随客户端</option>
<option value="minimal">minimal</option>
<option value="low">low</option>
<option value="medium">medium</option>
<option value="high">high</option>
<option value="xhigh">xhigh</option>
<option value="max">max</option>
<option value="none">关闭</option>
</select>
</div>
<div class="field full">
<label>按模型覆盖(JSON)</label
><textarea
id="c-reasoning-by-model"
spellcheck="false"
placeholder='{"model-id":"high"}'
></textarea>
<div class="section-caption">
值可为 minimal、low、medium、high、xhigh、max 或 none;空对象表示不覆盖。
</div>
</div>
</div>
</div>
<div class="section">
<div class="section-head">
<div>