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

+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 {