diff --git a/docs/guides/thinking/index.md b/docs/guides/thinking/index.md index 74e6c42682..334c1bcf8e 100644 --- a/docs/guides/thinking/index.md +++ b/docs/guides/thinking/index.md @@ -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 diff --git a/docs/providers/anthropic/index.md b/docs/providers/anthropic/index.md index c4ef4a3ef4..0efd75bf33 100644 --- a/docs/providers/anthropic/index.md +++ b/docs/providers/anthropic/index.md @@ -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 diff --git a/docs/providers/bedrock/index.md b/docs/providers/bedrock/index.md index 60f1d951e3..9910e37ccc 100644 --- a/docs/providers/bedrock/index.md +++ b/docs/providers/bedrock/index.md @@ -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/` 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 diff --git a/pkg/model/provider/anthropic/beta_client.go b/pkg/model/provider/anthropic/beta_client.go index c55284a179..6705c790e0 100644 --- a/pkg/model/provider/anthropic/beta_client.go +++ b/pkg/model/provider/anthropic/beta_client.go @@ -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) } diff --git a/pkg/model/provider/anthropic/client.go b/pkg/model/provider/anthropic/client.go index 0ed8ca2cdb..824dcbc8f4 100644 --- a/pkg/model/provider/anthropic/client.go +++ b/pkg/model/provider/anthropic/client.go @@ -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 @@ -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 @@ -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) } diff --git a/pkg/model/provider/anthropic/fallbacks.go b/pkg/model/provider/anthropic/fallbacks.go index 691c6f20b7..8effcdfe66 100644 --- a/pkg/model/provider/anthropic/fallbacks.go +++ b/pkg/model/provider/anthropic/fallbacks.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "log/slog" + "maps" "net/url" "os" "slices" @@ -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 { @@ -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, tokenThinking: thinking && !adaptive && budget.Tokens > 0, } } diff --git a/pkg/model/provider/anthropic/fallbacks_test.go b/pkg/model/provider/anthropic/fallbacks_test.go index e22e7d926a..6f3caa4e29 100644 --- a/pkg/model/provider/anthropic/fallbacks_test.go +++ b/pkg/model/provider/anthropic/fallbacks_test.go @@ -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": { diff --git a/pkg/model/provider/anthropic/features_integration_test.go b/pkg/model/provider/anthropic/features_integration_test.go index ccd6ee3f51..187fb48ec5 100644 --- a/pkg/model/provider/anthropic/features_integration_test.go +++ b/pkg/model/provider/anthropic/features_integration_test.go @@ -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() diff --git a/pkg/model/provider/anthropic/thinking.go b/pkg/model/provider/anthropic/thinking.go index c79ac397cf..af66588e6c 100644 --- a/pkg/model/provider/anthropic/thinking.go +++ b/pkg/model/provider/anthropic/thinking.go @@ -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 } diff --git a/pkg/model/provider/bedrock/client.go b/pkg/model/provider/bedrock/client.go index 5a1def479d..1d96dbade3 100644 --- a/pkg/model/provider/bedrock/client.go +++ b/pkg/model/provider/bedrock/client.go @@ -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) } diff --git a/pkg/model/provider/bedrock/client_test.go b/pkg/model/provider/bedrock/client_test.go index ae4a97f36e..abdd801ea0 100644 --- a/pkg/model/provider/bedrock/client_test.go +++ b/pkg/model/provider/bedrock/client_test.go @@ -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() diff --git a/pkg/model/provider/clone.go b/pkg/model/provider/clone.go index 825bb9f98a..bc7178278b 100644 --- a/pkg/model/provider/clone.go +++ b/pkg/model/provider/clone.go @@ -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...) diff --git a/pkg/model/provider/clone_thinking_test.go b/pkg/model/provider/clone_thinking_test.go index 4c37b57133..9b9fec2596 100644 --- a/pkg/model/provider/clone_thinking_test.go +++ b/pkg/model/provider/clone_thinking_test.go @@ -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`) + }) +} diff --git a/pkg/model/provider/clone_vertex_test.go b/pkg/model/provider/clone_vertex_test.go index c8df9b36b4..f2d0226bae 100644 --- a/pkg/model/provider/clone_vertex_test.go +++ b/pkg/model/provider/clone_vertex_test.go @@ -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 }) }) @@ -127,7 +132,6 @@ 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"]) @@ -135,8 +139,10 @@ func TestCloneVertexNativeDispatch(t *testing.T) { 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 }) diff --git a/pkg/model/provider/options/options.go b/pkg/model/provider/options/options.go index 7380007562..5e24ef120d 100644 --- a/pkg/model/provider/options/options.go +++ b/pkg/model/provider/options/options.go @@ -24,6 +24,7 @@ type ModelOptions struct { compacting bool textOnly bool noThinking bool + auxiliaryNoThinking bool disableAutoPull bool maxTokens int64 maxTokensInheritable bool @@ -78,6 +79,12 @@ func (c *ModelOptions) NoThinking() bool { return c.noThinking } +// AuxiliaryNoThinking reports whether a clone turned thinking off for a +// one-shot request, unlike a configured thinking_budget none. +func (c *ModelOptions) AuxiliaryNoThinking() bool { + return c.auxiliaryNoThinking +} + // DisableAutoPull reports whether providers must not download missing models // during client construction. DMR honors it by checking availability through // the read-only models API instead of running `docker model pull`. @@ -224,6 +231,14 @@ func WithNoThinking() Opt { } } +// WithAuxiliaryNoThinking turns thinking off for a clone's one-shot request. +func WithAuxiliaryNoThinking() Opt { + return func(cfg *ModelOptions) { + cfg.noThinking = true + cfg.auxiliaryNoThinking = true + } +} + // WithDisableAutoPull prevents providers from downloading missing models // during client construction. func WithDisableAutoPull() Opt { @@ -321,7 +336,11 @@ func FromModelOptions(m ModelOptions) []Opt { out = append(out, WithCompacting()) } if m.noThinking { - out = append(out, WithNoThinking()) + if m.auxiliaryNoThinking { + out = append(out, WithAuxiliaryNoThinking()) + } else { + out = append(out, WithNoThinking()) + } } if m.disableAutoPull { out = append(out, WithDisableAutoPull()) diff --git a/pkg/model/provider/options/options_test.go b/pkg/model/provider/options/options_test.go index 6e727deeef..99f60d056e 100644 --- a/pkg/model/provider/options/options_test.go +++ b/pkg/model/provider/options/options_test.go @@ -240,3 +240,19 @@ func TestMaxTokensPropagationAndRoundTrip(t *testing.T) { }) } } + +func TestWithAuxiliaryNoThinking_RoundTrips(t *testing.T) { + t.Parallel() + + src := Apply(WithAuxiliaryNoThinking()) + require.True(t, src.NoThinking()) + require.True(t, src.AuxiliaryNoThinking()) + + dst := Apply(FromModelOptions(src)...) + assert.True(t, dst.NoThinking()) + assert.True(t, dst.AuxiliaryNoThinking()) + + configured := Apply(FromModelOptions(Apply(WithNoThinking()))...) + assert.True(t, configured.NoThinking()) + assert.False(t, configured.AuxiliaryNoThinking()) +} diff --git a/pkg/model/provider/providerutil/provider_opts.go b/pkg/model/provider/providerutil/provider_opts.go index 934e0b97bf..aa95b3d1bb 100644 --- a/pkg/model/provider/providerutil/provider_opts.go +++ b/pkg/model/provider/providerutil/provider_opts.go @@ -8,7 +8,7 @@ import ( ) // GetProviderOptFloat64 extracts a float64 value from provider opts. -// YAML may parse numbers as float64 or int, so this handles both. +// YAML decodes a positive integer as uint64 and a negative one as int64. func GetProviderOptFloat64(opts map[string]any, key string) (float64, bool) { v, ok := opts[key] if !ok { @@ -23,6 +23,8 @@ func GetProviderOptFloat64(opts map[string]any, key string) (float64, bool) { return float64(n), true case int64: return float64(n), true + case uint64: + return float64(n), true default: slog.Debug("provider_opts type mismatch, ignoring", "key", key, @@ -34,7 +36,7 @@ func GetProviderOptFloat64(opts map[string]any, key string) (float64, bool) { } // GetProviderOptInt64 extracts an int64 value from provider opts. -// YAML may parse numbers as float64 or int, so this handles both. +// YAML decodes a positive integer as uint64 and JSON decodes it as float64. func GetProviderOptInt64(opts map[string]any, key string) (int64, bool) { v, ok := opts[key] if !ok { @@ -45,6 +47,13 @@ func GetProviderOptInt64(opts map[string]any, key string) (int64, bool) { return int64(n), true case int64: return n, true + case uint64: + if n <= math.MaxInt64 { + return int64(n), true + } + slog.Debug("provider_opts: uint64 value overflows int64", + "key", key, "value", v) + return 0, false case float64: if n == math.Trunc(n) && n >= math.MinInt64 && n <= math.MaxInt64 { return int64(n), true diff --git a/pkg/model/provider/providerutil/provider_opts_test.go b/pkg/model/provider/providerutil/provider_opts_test.go index 1b6063dd82..e709f346f8 100644 --- a/pkg/model/provider/providerutil/provider_opts_test.go +++ b/pkg/model/provider/providerutil/provider_opts_test.go @@ -1,9 +1,14 @@ package providerutil import ( + "math" "testing" + "github.com/goccy/go-yaml" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/docker/docker-agent/pkg/config/latest" ) func TestGetProviderOptFloat64(t *testing.T) { @@ -20,6 +25,7 @@ func TestGetProviderOptFloat64(t *testing.T) { {"float64 value", map[string]any{"top_k": 40.0}, "top_k", 40.0, true}, {"int value", map[string]any{"top_k": 40}, "top_k", 40.0, true}, {"int64 value", map[string]any{"top_k": int64(40)}, "top_k", 40.0, true}, + {"uint64 value", map[string]any{"top_k": uint64(40)}, "top_k", 40.0, true}, {"float32 value", map[string]any{"top_k": float32(40.5)}, "top_k", float64(float32(40.5)), true}, {"string value", map[string]any{"top_k": "40"}, "top_k", 0, false}, } @@ -103,6 +109,9 @@ func TestGetProviderOptInt64(t *testing.T) { {"missing key", map[string]any{}, "seed", 0, false}, {"int value", map[string]any{"seed": 42}, "seed", 42, true}, {"int64 value", map[string]any{"seed": int64(42)}, "seed", 42, true}, + {"uint64 value", map[string]any{"seed": uint64(42)}, "seed", 42, true}, + {"uint64 max int64", map[string]any{"seed": uint64(math.MaxInt64)}, "seed", math.MaxInt64, true}, + {"uint64 overflow", map[string]any{"seed": uint64(math.MaxInt64) + 1}, "seed", 0, false}, {"float64 whole number", map[string]any{"seed": 42.0}, "seed", 42, true}, {"float64 fractional", map[string]any{"seed": 42.5}, "seed", 0, false}, {"string value", map[string]any{"seed": "42"}, "seed", 0, false}, @@ -119,6 +128,29 @@ func TestGetProviderOptInt64(t *testing.T) { } } +func TestNumericProviderOptsFromYAML(t *testing.T) { + t.Parallel() + var cfg latest.ModelConfig + require.NoError(t, yaml.Unmarshal([]byte(`provider: openai +model: m +provider_opts: + top_k: 40 + seed: -7 +`), &cfg)) + + topK, ok := GetProviderOptInt64(cfg.ProviderOpts, "top_k") + require.True(t, ok) + assert.Equal(t, int64(40), topK) + + seed, ok := GetProviderOptInt64(cfg.ProviderOpts, "seed") + require.True(t, ok) + assert.Equal(t, int64(-7), seed) + + topKFloat, ok := GetProviderOptFloat64(cfg.ProviderOpts, "top_k") + require.True(t, ok) + assert.InDelta(t, 40.0, topKFloat, 0) +} + func TestHasProviderOpt(t *testing.T) { t.Parallel() for value, want := range map[any]bool{"default": true, "": false, 1: true} {