Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/guides/thinking/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,9 @@ models:
```

> [!NOTE]
> **Temperature and top_p**
> **Temperature, top_p and top_k**
>
> When extended thinking is enabled, Anthropic requires `temperature=1.0`. Docker Agent automatically suppresses any `temperature` or `top_p` settings you have configured — they are silently ignored while thinking is active.
> When extended thinking is enabled, Anthropic requires `temperature=1.0`. Docker Agent automatically suppresses any `temperature`, `top_p` or `top_k` settings you have configured — they are silently ignored while thinking is active.

### Thinking display

Expand Down
7 changes: 4 additions & 3 deletions docs/providers/anthropic/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -482,10 +482,11 @@ Rules checked at startup:
`default` only logs that it has no effect.
- The request must be valid for every listed model, or the API rejects it up
front. A configuration is rejected when a listed fallback (such as a Claude
5.x model) refuses what the request sends: `temperature` or `top_p` (sent
only with thinking off), `top_k`, or token-budget thinking, including an
5.x model) refuses what the request sends: `temperature`, `top_p` or `top_k`
(sent only with thinking off), or token-budget thinking, including an
effort level that an older model without adaptive thinking turns into a
token budget.
token budget. Session titles and `/btw`, which turn thinking off, leave out
`temperature`, `top_p` and `top_k` instead.

Fallback models receive the exact same request as the primary model
(thinking configuration, task budget, beta features, ...), so list only
Expand Down
4 changes: 2 additions & 2 deletions docs/providers/bedrock/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ models:
Docker Agent recognizes these models (including Bedrock-style IDs) and transparently coerces a configured token budget or effort level to adaptive thinking, logging a warning — so `thinking_budget: 32768` on Opus 4.8 won't fail, but `adaptive` or `adaptive/<effort>` is the recommended configuration. On older models that still use token-based thinking (e.g. Haiku 4.5), `adaptive` is forwarded as-is and rejected by Bedrock — use a token count or effort level there instead.

> [!NOTE]
> **Temperature and top_p**
> **Temperature, top_p and top_k**
>
> Bedrock Claude suppresses `temperature` and `top_p` while extended thinking is active — Anthropic requires `temperature=1.0` internally.
> Bedrock Claude suppresses `temperature`, `top_p` and `top_k` while extended thinking is active — Anthropic requires `temperature=1.0` internally.

### Claude 5.x models

Expand Down
2 changes: 1 addition & 1 deletion pkg/model/provider/anthropic/beta_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (c *Client) createBetaStream(
"message_count", len(params.Messages))

// Forward top_k from provider_opts (Anthropic natively supports it)
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !rejectsSampling(c.ModelConfig.Model) {
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !thinkingEnabled && !rejectsSampling(c.ModelConfig.Model) {
params.TopK = param.NewOpt(topK)
slog.DebugContext(ctx, "Anthropic Beta provider_opts: set top_k", "value", topK)
}
Expand Down
5 changes: 3 additions & 2 deletions pkg/model/provider/anthropic/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ func NewClient(ctx context.Context, cfg *latest.ModelConfig, env environment.Pro
return nil, errors.New("environment provider is required")
}

globalOptions := options.Apply(opts...)
cfg = withoutRejectedSampling(cfg, globalOptions.AuxiliaryNoThinking())
if err := validateThinkingOptions(cfg); err != nil {
slog.ErrorContext(ctx, "Anthropic client creation failed", "error", err)
return nil, err
Expand All @@ -70,7 +72,6 @@ func NewClient(ctx context.Context, cfg *latest.ModelConfig, env environment.Pro
slog.ErrorContext(ctx, "Anthropic client creation failed", "error", err)
return nil, err
}
globalOptions := options.Apply(opts...)
if err := validateFallbackHost(cfg, globalOptions.Gateway()); err != nil {
slog.ErrorContext(ctx, "Anthropic client creation failed", "error", err)
return nil, err
Expand Down Expand Up @@ -333,7 +334,7 @@ func (c *Client) CreateChatCompletionStream(
}

// Forward top_k from provider_opts (Anthropic natively supports it)
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !rejectsSampling(c.ModelConfig.Model) {
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !thinkingEnabled && !rejectsSampling(c.ModelConfig.Model) {
params.TopK = param.NewOpt(topK)
slog.DebugContext(ctx, "Anthropic provider_opts: set top_k", "value", topK)
}
Expand Down
26 changes: 20 additions & 6 deletions pkg/model/provider/anthropic/fallbacks.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"log/slog"
"maps"
"net/url"
"os"
"slices"
Expand Down Expand Up @@ -121,6 +122,19 @@ func fallbackTargets(opts map[string]any) []string {
return spec.Models
}

// withoutRejectedSampling drops sampling a listed fallback rejects from a clone
// that turned thinking off (a title, /btw). The config it copies never sent it.
func withoutRejectedSampling(cfg *latest.ModelConfig, auxiliaryNoThinking bool) *latest.ModelConfig {
if !auxiliaryNoThinking || !slices.ContainsFunc(fallbackTargets(cfg.ProviderOpts), rejectsSampling) {
return cfg
}
stripped := *cfg
stripped.Temperature, stripped.TopP = nil, nil
stripped.ProviderOpts = maps.Clone(cfg.ProviderOpts)
delete(stripped.ProviderOpts, "top_k")
return &stripped
}

// validateFallbackSpec checks the rules the API enforces with a 400, so a bad
// config fails at client construction.
func validateFallbackSpec(cfg *latest.ModelConfig) error {
Expand Down Expand Up @@ -164,20 +178,20 @@ type requestShape struct {
sampling, topK, tokenThinking bool
}

// sentRequestShape mirrors the request builder: temperature and top_p only go
// out with thinking off, top_k whenever set, and the thinking budget after
// resolution, which turns an effort level into tokens on models without
// adaptive thinking.
// sentRequestShape mirrors the request builder: temperature, top_p and top_k
// only go out with thinking off, and the thinking budget after resolution,
// which turns an effort level into tokens on models without adaptive thinking.
func sentRequestShape(cfg *latest.ModelConfig) requestShape {
c := &Client{Config: base.Config{ModelConfig: *cfg}}
budget := c.resolveThinkingBudget()
thinking := budget != nil && !budget.IsDisabled()
_, adaptive := anthropicThinkingEffort(budget)
// As in validThinkingTokens, a token budget below the minimum sends no thinking.
thinking := budget != nil && !budget.IsDisabled() && (adaptive || budget.Tokens >= minThinkingTokens)
_, topK := cfg.ProviderOpts["top_k"]
primaryRejects := rejectsSampling(cfg.Model)
return requestShape{
sampling: !thinking && !primaryRejects && (cfg.Temperature != nil || cfg.TopP != nil),
topK: topK && !primaryRejects,
topK: topK && !thinking && !primaryRejects,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[blocking] The top_k with thinking on config in fallbacks_test.go now passes for the main model, but /btw fails before sending a request. pkg/runtime/side_query.go:68 rebuilds the provider with WithNoThinking() and keeps both top_k: 5 and the claude-sonnet-5-5 fallback. On rebuild, this check sees thinking off and rejects the clone because the fallback doesn't accept top_k. Please make the no-thinking auxiliary clone retain the fallback list without sending the incompatible top_k, and add a regression test that constructs the clone and checks its request.

tokenThinking: thinking && !adaptive && budget.Tokens > 0,
}
}
14 changes: 13 additions & 1 deletion pkg/model/provider/anthropic/fallbacks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,10 +184,22 @@ func TestValidateFallbackRequestShape(t *testing.T) {
cfg: latest.ModelConfig{Model: "claude-opus-4-6", ProviderOpts: map[string]any{"top_k": 5}},
wantErr: "sends top_k",
},
// With thinking on, the request builder doesn't send temperature.
// With thinking on, the request builder doesn't send temperature or top_k.
"temperature with thinking on": {
cfg: latest.ModelConfig{Model: "claude-opus-4-6", Temperature: new(0.7), ThinkingBudget: &latest.ThinkingBudget{Effort: "high"}},
},
"top_k with thinking on": {
cfg: latest.ModelConfig{Model: "claude-opus-4-6", ProviderOpts: map[string]any{"top_k": 5}, ThinkingBudget: &latest.ThinkingBudget{Effort: "high"}},
},
// The request builder drops a token budget below 1024 and sends sampling.
"top_k with an invalid budget": {
cfg: latest.ModelConfig{Model: "claude-sonnet-4-6", ProviderOpts: map[string]any{"top_k": 5}, ThinkingBudget: &latest.ThinkingBudget{Tokens: -1}},
wantErr: "sends top_k",
},
"temperature with a budget below the minimum": {
cfg: latest.ModelConfig{Model: "claude-sonnet-4-6", Temperature: new(0.7), ThinkingBudget: &latest.ThinkingBudget{Tokens: 512}},
wantErr: "sends temperature or top_p",
},
// Haiku 4.5 has no adaptive thinking: its effort level goes out as a
// token budget, which a Claude 5.x fallback refuses.
"effort sent as tokens": {
Expand Down
34 changes: 34 additions & 0 deletions pkg/model/provider/anthropic/features_integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,40 @@ func TestDisabledThinking(t *testing.T) {
})
}

// Like temperature and top_p, top_k is rejected alongside thinking.
func TestTopKOnlyWithThinkingOff(t *testing.T) {
t.Parallel()

for name, tc := range map[string]struct{ beta, thinking bool }{
"standard, thinking off": {},
"standard, thinking on": {thinking: true},
"beta, thinking off": {beta: true},
"beta, thinking on": {beta: true, thinking: true},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
cfg := latest.ModelConfig{
Provider: "anthropic", Model: "claude-sonnet-4-6",
ProviderOpts: samplingOpts(map[string]any{"interleaved_thinking": tc.beta}),
}
if tc.thinking {
cfg.ThinkingBudget = &latest.ThinkingBudget{Tokens: 2048}
}
srv := newScriptedServer(t, textReply("msg_1", "ok"))
chatTurn(t, newScriptedClient(srv, cfg), []chat.Message{user("hello")}, nil)

req := srv.request(t, 0)
assert.Equal(t, tc.beta, slices.Contains(req.betas, anthropic.AnthropicBetaInterleavedThinking2025_05_14), "Beta API")
assert.Equal(t, tc.thinking, req.thinking() != nil)
if tc.thinking {
assert.NotContains(t, req.body, "top_k")
} else {
assert.InDelta(t, 5, req.body["top_k"], 0)
}
})
}
}

func TestSonnet5_DefaultsOmitSamplingAndThinking(t *testing.T) {
t.Parallel()

Expand Down
5 changes: 4 additions & 1 deletion pkg/model/provider/anthropic/thinking.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,14 @@ func (c *Client) interleavedThinkingEnabled() bool {
}
}

// minThinkingTokens is the smallest thinking budget Anthropic accepts.
const minThinkingTokens = 1024

// validThinkingTokens validates that the token budget is within the
// acceptable range for Anthropic (>= 1024 and < maxTokens).
// Returns (tokens, true) if valid, or (0, false) with a warning log if not.
func validThinkingTokens(tokens, maxTokens int64) (int64, bool) {
if tokens < 1024 {
if tokens < minThinkingTokens {
slog.Warn("Anthropic thinking_budget below minimum (1024), ignoring", "tokens", tokens)
return 0, false
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/model/provider/bedrock/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ func (c *Client) buildAdditionalModelRequestFields() document.Interface {
claude5, isClaude5 := modelinfo.LookupClaude5(c.ModelConfig.Model)

// Forward top_k from provider_opts (Anthropic on Bedrock supports it)
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !isClaude5 {
if topK, ok := providerutil.GetProviderOptInt64(c.ModelConfig.ProviderOpts, "top_k"); ok && !isClaude5 && !c.isThinkingEnabled() {
fields["top_k"] = topK
slog.Debug("Bedrock provider_opts: set top_k", "value", topK)
}
Expand Down
23 changes: 23 additions & 0 deletions pkg/model/provider/bedrock/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -922,6 +922,29 @@ func TestBuildInferenceConfig_SetsTempTopPWhenThinkingNotConfigured(t *testing.T
assert.InDelta(t, 0.9, *cfg.TopP, 0.01)
}

func TestBuildAdditionalModelRequestFields_TopKOnlyWithThinkingOff(t *testing.T) {
t.Parallel()

for name, budget := range map[string]*latest.ThinkingBudget{
"thinking off": nil,
"thinking on": {Tokens: 16384},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
client := bedrockThinkingClient("global.anthropic.claude-sonnet-4-6", budget)
client.ModelConfig.ProviderOpts = map[string]any{"top_k": 5}

fields := decodeRequestFields(t, client.buildAdditionalModelRequestFields())
if budget == nil {
assert.InDelta(t, 5, fields["top_k"], 0)
} else {
assert.Contains(t, fields, "thinking")
assert.NotContains(t, fields, "top_k")
}
})
}
}

func TestBuildInferenceConfig_SetsTempTopPWhenThinkingBudgetInvalid(t *testing.T) {
t.Parallel()

Expand Down
4 changes: 4 additions & 0 deletions pkg/model/provider/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,10 @@ func mergeCloneOptions(cfg base.Config, opts []options.Opt) (latest.ModelConfig,
} else if baseOptions.MaxTokensInheritable() && baseOptions.MaxTokens() != 0 {
mergedOpts = append(mergedOpts, options.WithAuxiliaryMaxTokens(baseOptions.MaxTokens()))
}
// Tell providers the clone, not the configuration, turned thinking off.
if requested.NoThinking() {
mergedOpts = append(mergedOpts, options.WithAuxiliaryNoThinking())
}

// Snapshot overrides too: option setters can carry caller-owned maps.
merged := options.Apply(mergedOpts...)
Expand Down
71 changes: 71 additions & 0 deletions pkg/model/provider/clone_thinking_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,74 @@ func TestCloneDirectClaudeRetainsExplicitCapOnZero(t *testing.T) {
}
request(original, 8192)
}

// /btw and title clones turn thinking off: they keep their fallbacks and leave
// out sampling a fallback rejects. A configured none still fails at startup.
func TestCloneWithoutThinkingKeepsFallbacks(t *testing.T) {
t.Parallel()
env := environment.NewMapEnvProvider(map[string]string{"ANTHROPIC_API_KEY": "fake"})
for name, tc := range map[string]struct {
temperature *float64
topK int
fallback string
sent bool
}{
"top_k": {topK: 5, fallback: "claude-sonnet-5-5"},
"temperature": {temperature: new(0.7), fallback: "claude-sonnet-5-5"},
"fallback accepts sampling": {temperature: new(0.7), topK: 5, fallback: "claude-sonnet-4-6", sent: true},
} {
t.Run(name, func(t *testing.T) {
t.Parallel()
cfg := &latest.ModelConfig{Provider: "anthropic", Model: "claude-opus-4-6", Temperature: tc.temperature, ThinkingBudget: &latest.ThinkingBudget{Effort: "high"}, ProviderOpts: map[string]any{"fallbacks": []any{tc.fallback}}}
if tc.topK != 0 {
cfg.ProviderOpts["top_k"] = tc.topK
}
var body map[string]any
wrapper := options.WithHTTPTransportWrapper(func(http.RoundTripper) http.RoundTripper {
return thinkingRoundTripper(func(req *http.Request) (*http.Response, error) {
body = nil
require.NoError(t, json.NewDecoder(req.Body).Decode(&body))
return &http.Response{StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": {"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"error":{"type":"invalid_request_error","message":"offline capture"}}`)), Request: req}, nil
})
})
request := func(p Provider) {
t.Helper()
stream, err := p.CreateChatCompletionStream(t.Context(), []chat.Message{{Role: chat.MessageRoleUser, Content: "hello"}}, nil)
if err == nil {
_, err = stream.Recv()
stream.Close()
}
require.Error(t, err)
assert.Equal(t, []any{map[string]any{"model": tc.fallback}}, body["fallbacks"])
}
original, err := fullTestRegistry().New(t.Context(), cfg, env, wrapper)
require.NoError(t, err)
request(original)
assert.Contains(t, body, "thinking")
assert.NotContains(t, body, "temperature")
assert.NotContains(t, body, "top_k")
for purpose, opts := range map[string][]options.Opt{
"btw": {options.WithStructuredOutput(nil), options.WithNoThinking(), options.WithMaxTokens(2048), options.WithTextOnly(), options.WithDisableAutoPull()},
"title": {options.WithStructuredOutput(nil), options.WithMaxTokens(128), options.WithNoThinking(), options.WithGeneratingTitle()},
} {
clone, err := Clone(t.Context(), original, opts...)
require.NoError(t, err, purpose)
request(clone)
assert.NotContains(t, body, "thinking", purpose)
if tc.sent {
assert.InDelta(t, 0.7, body["temperature"], 0, purpose)
assert.InDelta(t, float64(5), body["top_k"], 0, purpose)
} else {
assert.NotContains(t, body, "temperature", purpose)
assert.NotContains(t, body, "top_k", purpose)
}
}
})
}
t.Run("configured thinking off still fails", func(t *testing.T) {
t.Parallel()
cfg := &latest.ModelConfig{Provider: "anthropic", Model: "claude-opus-4-6", ThinkingBudget: &latest.ThinkingBudget{Effort: "none"}, ProviderOpts: map[string]any{"top_k": 5, "fallbacks": []any{"claude-sonnet-5-5"}}}
_, err := fullTestRegistry().New(t.Context(), cfg, env)
require.ErrorContains(t, err, `sends top_k, which fallback "claude-sonnet-5-5" rejects`)
})
}
10 changes: 8 additions & 2 deletions pkg/model/provider/clone_vertex_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,12 @@ func TestCloneVertexNativeDispatch(t *testing.T) {
body, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Contains(t, string(body), `"anthropic_version":"vertex-2023-10-16"`)
assert.Contains(t, string(body), `"top_k":9007199254740993`)
// The original thinks, so only the clone sends top_k.
if wireCalls == 1 {
assert.NotContains(t, string(body), `"top_k"`)
} else {
assert.Contains(t, string(body), `"top_k":9007199254740993`)
}
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")), Request: req}, nil
})
})
Expand Down Expand Up @@ -127,16 +132,17 @@ func TestCloneVertexNativeDispatch(t *testing.T) {
assert.Empty(t, req.Header.Get("X-Api-Key"))
body, err := io.ReadAll(req.Body)
require.NoError(t, err)
assert.Contains(t, string(body), `"top_k":9007199254740993`)
var payload map[string]any
require.NoError(t, json.Unmarshal(body, &payload))
assert.Equal(t, "vertex-2023-10-16", payload["anthropic_version"])
assert.NotContains(t, payload, "model")
if httpclient.SessionIDFromContext(req.Context()) == "clone-session" {
assert.NotContains(t, payload, "thinking")
assert.InDelta(t, float64(256), payload["max_tokens"], 0)
assert.Contains(t, string(body), `"top_k":9007199254740993`)
} else {
assert.Contains(t, payload, "thinking")
assert.NotContains(t, payload, "top_k")
}
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")), Request: req}, nil
})
Expand Down
Loading