From 242f5150acce28dcf042f14e64695cc51e198cf7 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 10:43:37 +0100 Subject: [PATCH 01/12] spec(tla): TemperatureOmission for issue #242 provider temperature assembly TLC on unfixed code: Fixed passes (12 states). LegacyDefault, LegacyTruthy and NullPasses fail OmitWhenUnset/ExplicitZeroKept on nullish/zero input (7 states each) - counterexamples reproduce the reported bug shapes. --- .../tla/TemperatureOmission.LegacyDefault.cfg | 4 ++ .../tla/TemperatureOmission.LegacyTruthy.cfg | 4 ++ .../tla/TemperatureOmission.NullPasses.cfg | 4 ++ docs/architecture/tla/TemperatureOmission.cfg | 4 ++ docs/architecture/tla/TemperatureOmission.tla | 59 +++++++++++++++++++ 5 files changed, 75 insertions(+) create mode 100644 docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.NullPasses.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.tla diff --git a/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg new file mode 100644 index 00000000000..2ff70e52951 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "LegacyDefault" +SPECIFICATION Spec +INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg new file mode 100644 index 00000000000..e87ebce3b97 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "LegacyTruthy" +SPECIFICATION Spec +INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.NullPasses.cfg b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg new file mode 100644 index 00000000000..839a6a05684 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "NullPasses" +SPECIFICATION Spec +INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.cfg b/docs/architecture/tla/TemperatureOmission.cfg new file mode 100644 index 00000000000..c18bc954625 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "Fixed" +SPECIFICATION Spec +INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla new file mode 100644 index 00000000000..cc10cf4b24a --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -0,0 +1,59 @@ +---- MODULE TemperatureOmission ---- +\* Source: TemperatureControl.onChange stores null when "use custom temperature" is +\* off (modelTemperature is nullish). A number, zero included, is a custom value. +\* Sinks: createStream in BaseOpenAiCompatibleProvider; createMessage and +\* completePrompt in LiteLlmHandler, NativeOllamaHandler, OpenAiNativeHandler, +\* MistralHandler, LmStudioHandler, BedrockHandler, VercelAiGatewayHandler, +\* ZooGatewayHandler, KenariHandler, NanoGptHandler, FriendliHandler, ZaiHandler, +\* GeminiHandler. Each writes (or omits) one temperature field in the request body. +\* Exception: a reasoning format that requires temperature (DeepSeek reasoner in +\* openai.ts PR 247, ollama useR1Format) sends its default when no custom value is set. +\* Failure: the user turns custom temperature off and a provider still writes a +\* temperature field (often 0), or overwrites an explicit 0, or writes null. +\* Invariant: no temperature field when the value is nullish and the model is not a +\* reasoner format. An explicit 0 and any custom number are sent unchanged. +\* Expect: LegacyDefault, LegacyTruthy and NullPasses fail on unset or zero input. +\* Fixed holds. The provider constants are oracles. +\* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours. +\* Result: see Result lines below. Null results are data. +\* Gate: Fixed must pass. LegacyDefault, LegacyTruthy and NullPasses must fail. +\* Property test: src/api/providers/__tests__/temperature-omission.spec.ts. +\* Not modeled: supportsTemperature capability gates, maxTokens and message fields. + +EXTENDS TLC +CONSTANT Variant +VARIABLES input, phase, sent + +Inputs == [setting : {"nullish", "zero", "custom"}, reasoner : BOOLEAN] + +\* Assembly maps the source value to the field written into one request body. +\* Fixed omits the field for a nullish value, except for a reasoner format. +\* Each Variant models one unfixed assembly shape seen in the provider files. +AssembleValue(s, r) == + IF Variant = "LegacyDefault" /\ s = "nullish" THEN "default" + ELSE IF Variant = "LegacyTruthy" /\ s \in {"nullish", "zero"} THEN "default" + ELSE IF Variant = "NullPasses" /\ s = "nullish" THEN "null" + ELSE IF r /\ s = "nullish" THEN "default" + ELSE IF s = "nullish" THEN "absent" + ELSE s + +Init == /\ input \in Inputs + /\ phase = "source" + /\ sent = "absent" + +Assemble == /\ phase = "source" + /\ sent' = AssembleValue(input.setting, input.reasoner) + /\ phase' = "assembled" + /\ UNCHANGED input + +Next == Assemble +Spec == Init /\ [][Next]_<> + +\* I1: unset custom temperature sends no temperature field (F1, F3). +OmitWhenUnset == phase = "assembled" /\ input.setting = "nullish" /\ ~input.reasoner + => sent = "absent" +\* I2: an explicit 0 is sent as 0 (F2). +ExplicitZeroKept == phase = "assembled" /\ input.setting = "zero" => sent = "zero" +\* I3: a custom number is sent unchanged. +CustomKept == phase = "assembled" /\ input.setting = "custom" => sent = "custom" +==== From 1508ea47993e2c43831e91b146d063c6d968b140 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 13:35:54 +0100 Subject: [PATCH 02/12] fix(providers): omit temperature when custom temperature is disabled (#242) --- docs/architecture/tla/TemperatureOmission.tla | 3 +- .../base-openai-compatible-provider.spec.ts | 3 +- src/api/providers/__tests__/fireworks.spec.ts | 24 +- src/api/providers/__tests__/friendli.spec.ts | 3 +- src/api/providers/__tests__/gemini.spec.ts | 7 - src/api/providers/__tests__/kenari.spec.ts | 5 +- src/api/providers/__tests__/lmstudio.spec.ts | 3 +- .../providers/__tests__/native-ollama.spec.ts | 9 +- .../providers/__tests__/openai-native.spec.ts | 4 +- src/api/providers/__tests__/sambanova.spec.ts | 3 +- .../__tests__/temperature-omission.spec.ts | 707 ++++++++++++++++++ .../__tests__/vercel-ai-gateway.spec.ts | 19 +- src/api/providers/__tests__/zai.spec.ts | 8 +- .../providers/__tests__/zoo-gateway.spec.ts | 16 +- .../base-openai-compatible-provider.ts | 9 +- src/api/providers/baseten.ts | 1 - src/api/providers/bedrock.ts | 3 +- src/api/providers/fireworks.ts | 1 - src/api/providers/friendli.ts | 6 +- src/api/providers/gemini.ts | 14 +- src/api/providers/kenari.ts | 11 +- src/api/providers/lite-llm.ts | 16 +- src/api/providers/lm-studio.ts | 14 +- src/api/providers/mistral.ts | 13 +- src/api/providers/nanogpt.ts | 4 +- src/api/providers/native-ollama.ts | 10 +- src/api/providers/openai-native.ts | 13 +- src/api/providers/sambanova.ts | 1 - src/api/providers/vercel-ai-gateway.ts | 15 +- src/api/providers/zai.ts | 10 +- src/api/providers/zoo-gateway.ts | 11 +- 31 files changed, 829 insertions(+), 137 deletions(-) create mode 100644 src/api/providers/__tests__/temperature-omission.spec.ts diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index cc10cf4b24a..ca078fe285a 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -15,7 +15,8 @@ \* Expect: LegacyDefault, LegacyTruthy and NullPasses fail on unset or zero input. \* Fixed holds. The provider constants are oracles. \* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours. -\* Result: see Result lines below. Null results are data. +\* Result: Fixed holds in 12 states. LegacyDefault, LegacyTruthy and +\* NullPasses each fail in 7 states. No false alarm was retained. \* Gate: Fixed must pass. LegacyDefault, LegacyTruthy and NullPasses must fail. \* Property test: src/api/providers/__tests__/temperature-omission.spec.ts. \* Not modeled: supportsTemperature capability gates, maxTokens and message fields. diff --git a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts index 1ffd63aa12a..555e38d5fc0 100644 --- a/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts +++ b/src/api/providers/__tests__/base-openai-compatible-provider.spec.ts @@ -272,13 +272,14 @@ describe("BaseOpenAiCompatibleProvider", () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: "test-model", - temperature: 0, messages: expect.arrayContaining([{ role: "system", content: systemPrompt }]), stream: true, stream_options: { include_usage: true }, }), undefined, ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) it("should yield usage data from stream", async () => { diff --git a/src/api/providers/__tests__/fireworks.spec.ts b/src/api/providers/__tests__/fireworks.spec.ts index 480f965894d..56fc5a82264 100644 --- a/src/api/providers/__tests__/fireworks.spec.ts +++ b/src/api/providers/__tests__/fireworks.spec.ts @@ -526,16 +526,17 @@ describe("FireworksHandler", () => { expect.objectContaining({ model: modelId, max_tokens: modelInfo.maxTokens, - temperature: 0.5, messages: expect.arrayContaining([{ role: "system", content: systemPrompt }]), stream: true, stream_options: { include_usage: true }, }), undefined, ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) - it("should use provider default temperature of 0.5 for models without defaultTemperature", async () => { + it("should omit temperature for models without a custom value (#242)", async () => { const modelId: FireworksModelId = "accounts/fireworks/models/kimi-k2-instruct" const handlerWithModel = new FireworksHandler({ apiModelId: modelId, @@ -547,15 +548,11 @@ describe("FireworksHandler", () => { const messageGenerator = handlerWithModel.createMessage("system", []) await messageGenerator.next() - expect(mockCreate).toHaveBeenCalledWith( - expect.objectContaining({ - temperature: 0.5, - }), - undefined, - ) + expect(mockCreate).toHaveBeenCalledTimes(1) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) - it("should use model defaultTemperature (1.0) over provider default (0.5) for kimi-k2-thinking", async () => { + it("should omit temperature for kimi-k2-thinking when no custom value is set (#242)", async () => { const modelId: FireworksModelId = "accounts/fireworks/models/kimi-k2-thinking" const handlerWithModel = new FireworksHandler({ apiModelId: modelId, @@ -567,13 +564,8 @@ describe("FireworksHandler", () => { const messageGenerator = handlerWithModel.createMessage("system", []) await messageGenerator.next() - // Model's defaultTemperature (1.0) should take precedence over provider's default (0.5) - expect(mockCreate).toHaveBeenCalledWith( - expect.objectContaining({ - temperature: 1.0, - }), - undefined, - ) + expect(mockCreate).toHaveBeenCalledTimes(1) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) it("should use user-specified temperature over model and provider defaults", async () => { diff --git a/src/api/providers/__tests__/friendli.spec.ts b/src/api/providers/__tests__/friendli.spec.ts index 1ff1b1475ba..97502a533fb 100644 --- a/src/api/providers/__tests__/friendli.spec.ts +++ b/src/api/providers/__tests__/friendli.spec.ts @@ -554,13 +554,14 @@ describe("FriendliHandler", () => { expect.objectContaining({ model: modelId, max_tokens: modelInfo.maxTokens, - temperature: 0.6, messages: expect.arrayContaining([{ role: "system", content: systemPrompt }]), stream: true, stream_options: { include_usage: true }, }), undefined, ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) it("should use user-specified temperature over provider default", async () => { diff --git a/src/api/providers/__tests__/gemini.spec.ts b/src/api/providers/__tests__/gemini.spec.ts index 9a2ed7d3c21..4db426d71b7 100644 --- a/src/api/providers/__tests__/gemini.spec.ts +++ b/src/api/providers/__tests__/gemini.spec.ts @@ -298,7 +298,6 @@ describe("GeminiHandler", () => { expect.objectContaining({ model: GEMINI_MODEL_NAME, config: expect.objectContaining({ - temperature: 1, systemInstruction: systemPrompt, }), }), @@ -415,7 +414,6 @@ describe("GeminiHandler", () => { contents: [{ role: "user", parts: [{ text: "Test prompt" }] }], config: { httpOptions: undefined, - temperature: 1, }, }) }) @@ -451,7 +449,6 @@ describe("GeminiHandler", () => { config: { abortSignal: controller.signal, httpOptions: undefined, - temperature: 1, }, }) }) @@ -481,7 +478,6 @@ describe("GeminiHandler", () => { contents: [{ role: "user", parts: [{ text: "test prompt" }] }], config: { httpOptions: undefined, - temperature: 1, }, }) }) @@ -498,7 +494,6 @@ describe("GeminiHandler", () => { config: { abortSignal: controller.signal, httpOptions: { timeout: 10000 }, - temperature: 1, }, }) }) @@ -513,7 +508,6 @@ describe("GeminiHandler", () => { contents: [{ role: "user", parts: [{ text: "test prompt" }] }], config: { httpOptions: { timeout: 5000 }, - temperature: 1, }, }) }) @@ -528,7 +522,6 @@ describe("GeminiHandler", () => { contents: [{ role: "user", parts: [{ text: "test prompt" }] }], config: { httpOptions: undefined, - temperature: 1, }, }) }) diff --git a/src/api/providers/__tests__/kenari.spec.ts b/src/api/providers/__tests__/kenari.spec.ts index 0ba360a0694..526db937982 100644 --- a/src/api/providers/__tests__/kenari.spec.ts +++ b/src/api/providers/__tests__/kenari.spec.ts @@ -257,9 +257,9 @@ describe("KenariHandler", () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: "openai/o3-mini", - temperature: undefined, }), ) + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) it("sends an explicitly configured model temperature", async () => { @@ -313,9 +313,10 @@ describe("KenariHandler", () => { stream: true, stream_options: { include_usage: true }, max_completion_tokens: 32768, - temperature: expect.any(Number), }), ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) }) diff --git a/src/api/providers/__tests__/lmstudio.spec.ts b/src/api/providers/__tests__/lmstudio.spec.ts index f2901cc7d48..74c26a57f71 100644 --- a/src/api/providers/__tests__/lmstudio.spec.ts +++ b/src/api/providers/__tests__/lmstudio.spec.ts @@ -302,11 +302,12 @@ describe("LmStudioHandler", () => { { model: mockOptions.lmStudioModelId, messages: [{ role: "user", content: "Test prompt" }], - temperature: 0, stream: false, }, undefined, // no abort signal or timeout: no request options reach the SDK ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) it("should handle API errors", async () => { diff --git a/src/api/providers/__tests__/native-ollama.spec.ts b/src/api/providers/__tests__/native-ollama.spec.ts index 3f2a5cba4ac..02e743c01fa 100644 --- a/src/api/providers/__tests__/native-ollama.spec.ts +++ b/src/api/providers/__tests__/native-ollama.spec.ts @@ -784,9 +784,8 @@ describe("NativeOllamaHandler", () => { model: "llama2", messages: [{ role: "user", content: "Tell me a joke" }], stream: false, - options: { - temperature: 0, - }, + // No custom temperature: options must omit the field (#242). + options: {}, }) expect(result).toBe("This is the response") }) @@ -849,7 +848,7 @@ describe("NativeOllamaHandler", () => { model: "llama2", messages: [{ role: "user", content: "Test prompt" }], stream: false, - options: { temperature: 0 }, + options: {}, }), ) expect(mockChat).toHaveBeenCalledTimes(1) @@ -868,7 +867,7 @@ describe("NativeOllamaHandler", () => { model: "llama2", messages: [{ role: "user", content: "Test prompt" }], stream: false, - options: { temperature: 0 }, + options: {}, }), ) }) diff --git a/src/api/providers/__tests__/openai-native.spec.ts b/src/api/providers/__tests__/openai-native.spec.ts index fa32c85dd94..666848bfa1b 100644 --- a/src/api/providers/__tests__/openai-native.spec.ts +++ b/src/api/providers/__tests__/openai-native.spec.ts @@ -2749,7 +2749,9 @@ describe("OpenAiNativeHandler", () => { const parsedBody = JSON.parse(body) expect(parsedBody.model).toBe("gpt-5.3-chat-latest") expect(parsedBody.max_output_tokens).toBe(16_384) - expect(parsedBody.temperature).toBe(0) + // No custom temperature: the request must omit the field (#242). + expect(parsedBody.temperature).toBeUndefined() + expect("temperature" in parsedBody).toBe(false) expect(parsedBody.reasoning?.effort).toBeUndefined() expect(parsedBody.text?.verbosity).toBeUndefined() diff --git a/src/api/providers/__tests__/sambanova.spec.ts b/src/api/providers/__tests__/sambanova.spec.ts index 2a19d5659c4..f51be70fb32 100644 --- a/src/api/providers/__tests__/sambanova.spec.ts +++ b/src/api/providers/__tests__/sambanova.spec.ts @@ -115,12 +115,13 @@ describe("SambaNovaHandler", () => { expect.objectContaining({ model: modelId, max_tokens: modelInfo.maxTokens, - temperature: 0.7, messages: expect.arrayContaining([{ role: "system", content: systemPrompt }]), stream: true, stream_options: { include_usage: true }, }), undefined, ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) }) diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts new file mode 100644 index 00000000000..d624d6cc341 --- /dev/null +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -0,0 +1,707 @@ +// npx vitest run src/api/providers/__tests__/temperature-omission.spec.ts +// +// Property tests for the TemperatureOmission.tla invariants (issue #242). +// I1: modelTemperature is nullish => the request body has no temperature field. +// I2: modelTemperature is 0 => the body temperature is 0. +// I3: modelTemperature is c => the body temperature is c. +// The DeepSeek reasoner / ollama R1-format exception is deliberate (PR #247) +// and is kept out of these assertions. + +vitest.mock("vscode", () => ({ + window: { + showErrorMessage: vitest.fn(async () => undefined), + env: { openExternal: vitest.fn(async () => true), uriScheme: "vscode", appName: "VS Code" }, + }, + Uri: { parse: (value: string) => ({ toString: () => value }) }, + workspace: { + getConfiguration: () => ({ + get: (_key: string, defaultValue?: unknown) => defaultValue, + }), + }, +})) + +vitest.mock("../../../i18n", () => ({ + t: (key: string) => key, +})) + +vitest.mock("@roo-code/telemetry", () => ({ + TelemetryService: { + instance: { + captureException: vitest.fn(), + }, + }, +})) + +vitest.mock("delay", () => ({ + default: vitest.fn(() => Promise.resolve()), +})) + +import OpenAI from "openai" + +import { + BEDROCK_DEFAULT_TEMPERATURE, + geminiDefaultModelId, + kenariDefaultModelId, + nanoGptDefaultModelId, + vercelAiGatewayDefaultModelId, + zooGatewayDefaultModelId, +} from "@roo-code/types" + +import { AwsBedrockHandler } from "../bedrock" +import { FireworksHandler } from "../fireworks" +import { FriendliHandler } from "../friendli" +import { GeminiHandler } from "../gemini" +import { KenariHandler } from "../kenari" +import { LiteLLMHandler } from "../lite-llm" +import { LmStudioHandler } from "../lm-studio" +import { MistralHandler } from "../mistral" +import { NanoGptHandler } from "../nanogpt" +import { NativeOllamaHandler } from "../native-ollama" +import { OpenAiNativeHandler } from "../openai-native" +import { VercelAiGatewayHandler } from "../vercel-ai-gateway" +import { ZAiHandler } from "../zai" +import { ZooGatewayHandler } from "../zoo-gateway" +import { getOllamaModels } from "../fetchers/ollama" +import type { ApiHandlerOptions } from "../../../shared/api" +import type { GoogleGenAI } from "@google/genai" +import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" + +// One shared catalog serves every handler that resolves models via modelCache. +const MODEL_CATALOG = vitest.hoisted(() => ({ + "claude-3-7-sonnet-20250219": { + maxTokens: 8192, + contextWindow: 200000, + supportsImages: false, + supportsPromptCache: false, + description: "LiteLLM default", + }, + "anthropic/claude-sonnet-4": { + maxTokens: 64000, + contextWindow: 200000, + supportsImages: true, + supportsPromptCache: true, + description: "Gateway default", + }, + "glm-5-2": { + maxTokens: 32768, + contextWindow: 1048576, + supportsImages: false, + supportsPromptCache: false, + description: "GLM 5.2", + }, + "openai/gpt-5.6-sol": { + maxTokens: 32768, + contextWindow: 400000, + supportsImages: false, + supportsPromptCache: false, + description: "NanoGpt default", + }, +})) + +const MODEL_CATALOG_FETCH_TIMEOUT_MS = vitest.hoisted(() => 10_000) + +vitest.mock("../fetchers/modelCache", () => ({ + getModels: vitest.fn().mockImplementation(() => Promise.resolve(MODEL_CATALOG)), + refreshModels: vitest.fn().mockImplementation(() => Promise.resolve(MODEL_CATALOG)), + getModelsFromCache: vitest.fn().mockReturnValue(undefined), + MODEL_CATALOG_FETCH_TIMEOUT_MS, +})) + +// OpenAI SDK mock shared by every chat-completions handler plus openai-native. +const mockCreate = vitest.fn() +const mockResponsesCreate = vitest.fn() + +vitest.mock("openai") +;(OpenAI as unknown as { mockImplementation: (impl: () => unknown) => void }).mockImplementation(function () { + return { + chat: { + completions: { + create: mockCreate, + }, + }, + responses: { + create: mockResponsesCreate, + }, + } +}) + +// Mistral SDK mock. +const mockMistralStream = vitest.fn() +const mockMistralComplete = vitest.fn() + +vitest.mock("@mistralai/mistralai", () => ({ + Mistral: vitest.fn().mockImplementation(function () { + return { + chat: { + stream: mockMistralStream, + complete: mockMistralComplete, + }, + } + }), +})) + +// Ollama SDK mock (mirrors native-ollama.spec.ts). +const mockChat = vitest.fn() +const mockIsProxyEnabled = vi.hoisted(() => vitest.fn(() => false)) +vitest.mock("../../../utils/networkProxy", async (importOriginal) => { + const actual = (await importOriginal()) as typeof import("../../../utils/networkProxy") + return { + ...actual, + isProxyEnabled: mockIsProxyEnabled, + } +}) + +const mockedOllama = vi.hoisted(() => ({ + OllamaMock: vitest.fn(), +})) + +vitest.mock("ollama", () => { + const { OllamaMock } = mockedOllama + return { + Ollama: OllamaMock.mockImplementation(function (options?: { host?: string }) { + const instanceAbort = vitest.fn() + return { + chat: mockChat, + abort: instanceAbort, + _host: options?.host ?? "http://localhost:11434", + _instanceAbort: instanceAbort, + } + }), + Message: vitest.fn(), + } +}) + +vitest.mock("../fetchers/ollama", async (importOriginal) => { + const actual = (await importOriginal()) as typeof import("../fetchers/ollama") + return { + ...actual, + getOllamaModels: vitest.fn(), + } +}) + +const mockGetOllamaModels = vitest.mocked(getOllamaModels) + +const userMessage = [{ role: "user" as const, content: "Hello" }] + +// Standard streaming completion chunks for the OpenAI chat-completions shape. +// LiteLLM calls create(...).withResponse(); other handlers iterate the stream. +const makeCompletionStream = () => { + const stream = asyncStreamFrom([ + { choices: [{ delta: { content: "Test response" }, index: 0 }], usage: null }, + { + choices: [{ delta: {}, index: 0 }], + usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }, + }, + ]) + type CompletionStream = ReturnType & { + withResponse: () => Promise<{ + data: ReturnType + response: { headers: Map } + }> + } + const streamWithResponse = stream as CompletionStream + streamWithResponse.withResponse = async () => ({ data: stream, response: { headers: new Map() } }) + return streamWithResponse +} + +const nonStreamingCompletion = { choices: [{ message: { content: "ok" } }] } + +beforeEach(() => { + mockCreate.mockClear() + // Return the stream synchronously: LiteLLM calls create(...).withResponse() + // directly on the returned value (the real SDK returns an APIPromise). + mockCreate.mockImplementation(() => makeCompletionStream()) + mockResponsesCreate.mockClear() + mockResponsesCreate.mockImplementation(async () => + asyncStreamFrom([ + { type: "response.output_text.delta", delta: "Test response" }, + { type: "response.completed", response: { usage: { input_tokens: 10, output_tokens: 5 } } }, + ]), + ) + mockMistralStream.mockClear() + mockMistralStream.mockImplementation(async () => + asyncStreamFrom([ + { data: { choices: [{ delta: { content: "Test response" }, index: 0 }] } }, + { data: { choices: [{ delta: {}, index: 0 }], usage: { prompt_tokens: 10, completion_tokens: 5 } } }, + ]), + ) + mockMistralComplete.mockClear() + mockMistralComplete.mockResolvedValue({ choices: [{ message: { content: "ok" } }] }) + mockChat.mockClear() + mockChat.mockImplementation(async function* () { + yield { message: { content: "Test response" }, eval_count: 2, prompt_eval_count: 10 } + }) + mockGetOllamaModels.mockResolvedValue({ + llama2: { + contextWindow: 4096, + maxTokens: 4096, + supportsImages: false, + supportsPromptCache: false, + }, + }) +}) + +describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { + describe("FireworksHandler (base-openai-compatible createStream)", () => { + const make = (options: Partial = {}) => + new FireworksHandler({ fireworksApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + }) + + describe("LiteLLMHandler", () => { + const make = (options: Partial = {}) => + new LiteLLMHandler({ litellmApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I1: omits temperature when custom temperature is null", async () => { + await collectStream(make({ modelTemperature: null }).createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make().completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("NativeOllamaHandler", () => { + const make = (options: Partial = {}) => + new NativeOllamaHandler({ + apiModelId: "llama2", + ollamaModelId: "llama2", + ollamaBaseUrl: "http://localhost:11434", + ...options, + }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockChat.mock.calls[0][0].options).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockChat.mock.calls[0][0].options.temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockChat.mock.calls[0][0].options.temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockChat.mockResolvedValueOnce({ message: { content: "ok" } }) + await make().completePrompt("hello") + expect("temperature" in mockChat.mock.calls[0][0].options).toBe(false) + }) + + it("I2 (completePrompt): sends an explicit custom temperature of 0", async () => { + mockChat.mockResolvedValueOnce({ message: { content: "ok" } }) + await make({ modelTemperature: 0 }).completePrompt("hello") + expect(mockChat.mock.calls[0][0].options.temperature).toBe(0) + }) + }) + + describe("OpenAiNativeHandler", () => { + const systemPrompt = "You are a helpful assistant." + const make = (options: Partial = {}) => + new OpenAiNativeHandler({ + apiModelId: "gpt-5.3-chat-latest", + openAiNativeApiKey: "test-key", + ...options, + }) + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + const model = handler.getModel() + const body = handler["buildRequestBody"](model, [], systemPrompt, undefined, undefined, { + taskId: "test-task", + }) + expect("temperature" in body).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + const handler = make({ modelTemperature: 0 }) + const model = handler.getModel() + const body = handler["buildRequestBody"](model, [], systemPrompt, undefined, undefined, { + taskId: "test-task", + }) + expect(body.temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + const model = handler.getModel() + const body = handler["buildRequestBody"](model, [], systemPrompt, undefined, undefined, { + taskId: "test-task", + }) + expect(body.temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockResponsesCreate.mockResolvedValueOnce({ + output: [{ type: "message", content: [{ type: "output_text", text: "ok" }] }], + }) + await make().completePrompt("hello") + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) + }) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockResponsesCreate.mockResolvedValueOnce({ + output: [{ type: "message", content: [{ type: "output_text", text: "ok" }] }], + }) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + }) + + describe("MistralHandler", () => { + const make = (options: Partial = {}) => + new MistralHandler({ mistralApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockMistralStream.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockMistralStream.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockMistralStream.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + await make().completePrompt("hello") + expect("temperature" in mockMistralComplete.mock.calls[0][0]).toBe(false) + }) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockMistralComplete.mock.calls[0][0].temperature).toBe(0.7) + }) + }) + + describe("LmStudioHandler", () => { + const make = (options: Partial = {}) => + new LmStudioHandler({ + lmStudioModelId: "llama2", + lmStudioBaseUrl: "http://localhost:1234", + ...options, + }) + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + vitest.spyOn(handler, "countTokens").mockResolvedValue(1) + await collectStream(handler.createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + const handler = make({ modelTemperature: 0 }) + vitest.spyOn(handler, "countTokens").mockResolvedValue(1) + await collectStream(handler.createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + vitest.spyOn(handler, "countTokens").mockResolvedValue(1) + await collectStream(handler.createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make().completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("AwsBedrockHandler", () => { + const make = (options: Partial = {}) => + new AwsBedrockHandler({ + apiModelId: "anthropic.claude-3-5-sonnet-20241022-v2:0", + awsAccessKey: "test-access-key", + awsSecretKey: "test-secret-key", + awsRegion: "us-east-1", + ...options, + }) + + it("I2: keeps an explicit custom temperature of 0 (no constructor clobber)", () => { + expect(make({ modelTemperature: 0 }).getModel().temperature).toBe(0) + }) + + it("unset keeps the getModelParams default (out of scope for #242)", () => { + expect(make().getModel().temperature).toBe(BEDROCK_DEFAULT_TEMPERATURE) + }) + }) + + describe("VercelAiGatewayHandler", () => { + const make = (options: Partial = {}) => + new VercelAiGatewayHandler({ vercelAiGatewayApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + expect(handler.getModel().id).toBe(vercelAiGatewayDefaultModelId) + await collectStream(handler.createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make().completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("ZooGatewayHandler", () => { + const make = (options: Partial = {}) => + new ZooGatewayHandler({ zooSessionToken: "zoo_ext_test_token", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + expect(handler.getModel().id).toBe(zooGatewayDefaultModelId) + await collectStream(handler.createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make().completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("KenariHandler", () => { + const make = (options: Partial = {}) => + new KenariHandler({ kenariApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + expect(handler.getModel().id).toBe(kenariDefaultModelId) + await collectStream(handler.createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make().completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("NanoGptHandler", () => { + const make = (options: Partial = {}) => + new NanoGptHandler({ nanoGptModelId: nanoGptDefaultModelId, ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I1: omits temperature when custom temperature is null", async () => { + await collectStream(make({ modelTemperature: null }).createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is null", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: null }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("FriendliHandler", () => { + const make = (options: Partial = {}) => + new FriendliHandler({ friendliApiKey: "test-key", ...options }) + + it("I1: omits temperature when custom temperature is unset", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + }) + + describe("ZAiHandler", () => { + const make = (options: Partial = {}) => + new ZAiHandler({ zaiApiKey: "test-key", zaiApiLine: "international_coding", ...options }) + + it("I1: omits temperature when custom temperature is unset (non-thinking path)", async () => { + await collectStream(make().createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0 (non-thinking path)", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I1: omits temperature when custom temperature is unset (thinking path)", async () => { + await collectStream(make({ apiModelId: "glm-5.3" }).createMessage("system", userMessage)) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I3: sends a custom temperature unchanged (thinking path)", async () => { + await collectStream( + make({ apiModelId: "glm-5.3", modelTemperature: 0.7 }).createMessage("system", userMessage), + ) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("I1 (completePrompt, thinking path): omits temperature when custom temperature is unset", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ apiModelId: "glm-5.3" }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + }) + + describe("GeminiHandler", () => { + const make = (options: Partial = {}) => + new GeminiHandler({ + apiKey: "test-key", + geminiApiKey: "test-key", + apiModelId: geminiDefaultModelId, + ...options, + }) + + const installClientMock = (handler: GeminiHandler) => { + const mockGenerateContentStream = vitest.fn() + const mockGenerateContent = vitest.fn() + handler["client"] = { + models: { + generateContentStream: mockGenerateContentStream, + generateContent: mockGenerateContent, + }, + } as unknown as GoogleGenAI + mockGenerateContentStream.mockResolvedValue( + asyncStreamFrom([ + { text: "Test response" }, + { usageMetadata: { promptTokenCount: 10, candidatesTokenCount: 5 } }, + ]), + ) + mockGenerateContent.mockResolvedValue({ text: "ok" }) + return { mockGenerateContentStream, mockGenerateContent } + } + + it("I1: omits temperature when custom temperature is unset", async () => { + const handler = make() + const { mockGenerateContentStream } = installClientMock(handler) + await collectStream(handler.createMessage("system", userMessage)) + const call = mockGenerateContentStream.mock.calls[0][0] + expect("temperature" in call.config).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + const handler = make({ modelTemperature: 0 }) + const { mockGenerateContentStream } = installClientMock(handler) + await collectStream(handler.createMessage("system", userMessage)) + const call = mockGenerateContentStream.mock.calls[0][0] + expect(call.config.temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + const { mockGenerateContentStream } = installClientMock(handler) + await collectStream(handler.createMessage("system", userMessage)) + const call = mockGenerateContentStream.mock.calls[0][0] + expect(call.config.temperature).toBe(0.7) + }) + + it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { + const handler = make() + const { mockGenerateContent } = installClientMock(handler) + await handler.completePrompt("hello") + const call = mockGenerateContent.mock.calls[0][0] + expect("temperature" in call.config).toBe(false) + }) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + const { mockGenerateContent } = installClientMock(handler) + await handler.completePrompt("hello") + const call = mockGenerateContent.mock.calls[0][0] + expect(call.config.temperature).toBe(0.7) + }) + }) +}) diff --git a/src/api/providers/__tests__/vercel-ai-gateway.spec.ts b/src/api/providers/__tests__/vercel-ai-gateway.spec.ts index 5bafa25c78a..320332c61c6 100644 --- a/src/api/providers/__tests__/vercel-ai-gateway.spec.ts +++ b/src/api/providers/__tests__/vercel-ai-gateway.spec.ts @@ -16,7 +16,7 @@ import { VercelAiGatewayHandler } from "../vercel-ai-gateway" import { makeApiHandlerOptions } from "../../../test-utils/api" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" import { clearAllMocks } from "../../../test-utils/reset" -import { vercelAiGatewayDefaultModelId, VERCEL_AI_GATEWAY_DEFAULT_TEMPERATURE } from "@roo-code/types" +import { vercelAiGatewayDefaultModelId } from "@roo-code/types" // Mock dependencies vitest.mock("openai") @@ -332,7 +332,7 @@ describe("VercelAiGatewayHandler", () => { ) }) - it("uses default temperature when none provided", async () => { + it("omits temperature when none is provided (#242)", async () => { const handler = new VercelAiGatewayHandler(mockOptions) const systemPrompt = "You are a helpful assistant." @@ -340,11 +340,9 @@ describe("VercelAiGatewayHandler", () => { await handler.createMessage(systemPrompt, messages).next() - expect(mockCreate).toHaveBeenCalledWith( - expect.objectContaining({ - temperature: VERCEL_AI_GATEWAY_DEFAULT_TEMPERATURE, - }), - ) + const call = mockCreate.mock.calls[mockCreate.mock.calls.length - 1][0] + expect(call.temperature).toBeUndefined() + expect("temperature" in call).toBe(false) }) it("omits temperature for Claude Fable 5", async () => { @@ -360,10 +358,10 @@ describe("VercelAiGatewayHandler", () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: "anthropic/claude-fable-5", - temperature: undefined, max_completion_tokens: 128000, }), ) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) it("omits temperature for Claude Fable 5.1", async () => { @@ -379,9 +377,9 @@ describe("VercelAiGatewayHandler", () => { expect(mockCreate).toHaveBeenCalledWith( expect.objectContaining({ model: "anthropic/claude-fable-5.1", - temperature: undefined, }), ) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) it("omits temperature for Claude Sonnet 5", async () => { @@ -775,10 +773,11 @@ describe("VercelAiGatewayHandler", () => { model: "anthropic/claude-sonnet-4", messages: [{ role: "user", content: prompt }], stream: false, - temperature: VERCEL_AI_GATEWAY_DEFAULT_TEMPERATURE, max_completion_tokens: 64000, }), ) + // No custom temperature: the request must omit the field (#242). + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) it("uses custom temperature for completion", async () => { diff --git a/src/api/providers/__tests__/zai.spec.ts b/src/api/providers/__tests__/zai.spec.ts index 0a33e7ad66f..6e2763d3aab 100644 --- a/src/api/providers/__tests__/zai.spec.ts +++ b/src/api/providers/__tests__/zai.spec.ts @@ -10,7 +10,6 @@ import { mainlandZAiDefaultModelId, internationalZAiModels, mainlandZAiModels, - ZAI_DEFAULT_TEMPERATURE, getZAiModels, } from "@roo-code/types" @@ -583,13 +582,14 @@ describe("ZAiHandler", () => { expect.objectContaining({ model: modelId, max_tokens: expectedMaxTokens, - temperature: ZAI_DEFAULT_TEMPERATURE, messages: expect.arrayContaining([{ role: "system", content: systemPrompt }]), stream: true, stream_options: { include_usage: true }, }), undefined, ) + // No custom temperature: the request must omit the field (#242). + expect(mockCreate.mock.calls[0][0]).not.toHaveProperty("temperature") }) }) @@ -730,7 +730,6 @@ describe("ZAiHandler", () => { model: "glm-5.3", thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "max", - temperature: 1, }), ) }) @@ -753,7 +752,6 @@ describe("ZAiHandler", () => { model: "glm-5.3-flash", thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "max", - temperature: 1, }), ) }) @@ -794,7 +792,6 @@ describe("ZAiHandler", () => { expect(mockCreate).toHaveBeenCalledWith({ model: "glm-5.3", messages: [{ role: "user", content: "prompt" }], - temperature: 1, thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "low", }) @@ -814,7 +811,6 @@ describe("ZAiHandler", () => { expect(mockCreate).toHaveBeenCalledWith({ model: "glm-5.3-flash", messages: [{ role: "user", content: "prompt" }], - temperature: 1, thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: "low", }) diff --git a/src/api/providers/__tests__/zoo-gateway.spec.ts b/src/api/providers/__tests__/zoo-gateway.spec.ts index a9beaada1c7..db4f1892d60 100644 --- a/src/api/providers/__tests__/zoo-gateway.spec.ts +++ b/src/api/providers/__tests__/zoo-gateway.spec.ts @@ -29,7 +29,7 @@ vitest.mock("../../../i18n", () => ({ import type { MockInstance } from "vitest" import OpenAI from "openai" -import { zooGatewayDefaultModelId, ZOO_GATEWAY_DEFAULT_TEMPERATURE } from "@roo-code/types" +import { zooGatewayDefaultModelId } from "@roo-code/types" import { ZooGatewayHandler, classifyGatewayApiError, toGatewayStreamError } from "../zoo-gateway" import { ApiHandlerOptions } from "../../../shared/api" @@ -396,17 +396,14 @@ describe("ZooGatewayHandler", () => { ) }) - it("uses the default temperature when none is provided", async () => { + it("omits temperature when none is provided (#242)", async () => { const handler = new ZooGatewayHandler(mockOptions) await handler.createMessage("prompt", [{ role: "user", content: "Hi" }]).next() - expect(mockCreate).toHaveBeenCalledWith( - expect.objectContaining({ - temperature: ZOO_GATEWAY_DEFAULT_TEMPERATURE, - }), - expect.any(Object), - ) + const call = mockCreate.mock.calls[mockCreate.mock.calls.length - 1][0] + expect(call.temperature).toBeUndefined() + expect("temperature" in call).toBe(false) }) it("adds cache breakpoints for supported models", async () => { @@ -525,11 +522,12 @@ describe("ZooGatewayHandler", () => { model: "anthropic/claude-sonnet-4", messages: [{ role: "user", content: "Complete this: Hello" }], stream: false, - temperature: ZOO_GATEWAY_DEFAULT_TEMPERATURE, max_completion_tokens: 64000, }), {}, ) + // No custom temperature: the request must omit the field (#242). + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) it("wraps errors with a Zoo Gateway prefix", async () => { diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index b177726f852..72c25d58226 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -20,7 +20,6 @@ type BaseOpenAiCompatibleProviderOptions = ApiHandlerO baseURL: string defaultProviderModelId: ModelName providerModels: Record - defaultTemperature?: number } export abstract class BaseOpenAiCompatibleProvider @@ -29,7 +28,6 @@ export abstract class BaseOpenAiCompatibleProvider { protected readonly providerName: string protected readonly baseURL: string - protected readonly defaultTemperature: number protected readonly defaultProviderModelId: ModelName protected readonly providerModels: Record @@ -42,7 +40,6 @@ export abstract class BaseOpenAiCompatibleProvider baseURL, defaultProviderModelId, providerModels, - defaultTemperature, ...options }: BaseOpenAiCompatibleProviderOptions) { super() @@ -51,7 +48,6 @@ export abstract class BaseOpenAiCompatibleProvider this.baseURL = baseURL this.defaultProviderModelId = defaultProviderModelId this.providerModels = providerModels - this.defaultTemperature = defaultTemperature ?? 0 this.options = options @@ -84,12 +80,11 @@ export abstract class BaseOpenAiCompatibleProvider format: "openai", }) ?? undefined - const temperature = this.options.modelTemperature ?? info.defaultTemperature ?? this.defaultTemperature - const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { model, max_tokens, - temperature, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)], stream: true, stream_options: { include_usage: true }, diff --git a/src/api/providers/baseten.ts b/src/api/providers/baseten.ts index ca0c2867756..8a9b6c7a12f 100644 --- a/src/api/providers/baseten.ts +++ b/src/api/providers/baseten.ts @@ -12,7 +12,6 @@ export class BasetenHandler extends BaseOpenAiCompatibleProvider apiKey: options.basetenApiKey, defaultProviderModelId: basetenDefaultModelId, providerModels: basetenModels, - defaultTemperature: 0.5, }) } } diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index 2bb083cc7db..45ca068efd8 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -268,7 +268,8 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH if (this.arnInfo.awsUseCrossRegionInference) this.options.awsUseCrossRegionInference = true } - if (!this.options.modelTemperature) { + // An explicit 0 is a real custom value; only fill the default when unset (#242). + if (this.options.modelTemperature == null) { this.options.modelTemperature = BEDROCK_DEFAULT_TEMPERATURE } diff --git a/src/api/providers/fireworks.ts b/src/api/providers/fireworks.ts index db29e7bf3f3..3c47573c931 100644 --- a/src/api/providers/fireworks.ts +++ b/src/api/providers/fireworks.ts @@ -13,7 +13,6 @@ export class FireworksHandler extends BaseOpenAiCompatibleProvider 0 ? { tools } : {}), } @@ -696,7 +696,7 @@ export class GeminiHandler extends BaseProvider implements SingleCompletionHandl try { const supportsTemperature = info.supportsTemperature !== false const temperatureConfig: number | undefined = supportsTemperature - ? (this.options.modelTemperature ?? info.defaultTemperature ?? 1) + ? (this.options.modelTemperature ?? undefined) : info.defaultTemperature const httpOpts: { timeout?: number; baseUrl?: string } = {} if (requestTimeoutMs !== undefined) { @@ -715,7 +715,7 @@ export class GeminiHandler extends BaseProvider implements SingleCompletionHandl const promptConfig: GenerateContentConfig = { httpOptions: Object.keys(httpOpts).length > 0 ? httpOpts : undefined, - temperature: temperatureConfig, + ...(temperatureConfig !== undefined && { temperature: temperatureConfig }), } // @google/genai expects request cancellation on config.abortSignal diff --git a/src/api/providers/kenari.ts b/src/api/providers/kenari.ts index 22ca50c916e..f6e762bd611 100644 --- a/src/api/providers/kenari.ts +++ b/src/api/providers/kenari.ts @@ -4,7 +4,6 @@ import OpenAI from "openai" import { kenariDefaultModelId, kenariDefaultModelInfo, - KENARI_DEFAULT_TEMPERATURE, KENARI_BASE_URL, providerIdentifiers, type ModelRecord, @@ -82,9 +81,9 @@ export class KenariHandler extends RouterProvider implements SingleCompletionHan const body: OpenAI.Chat.ChatCompletionCreateParams = { model: modelId, messages: openAiMessages, - temperature: this.supportsTemperature(modelId) - ? (this.options.modelTemperature ?? KENARI_DEFAULT_TEMPERATURE) - : undefined, + // Only send temperature when the user set a custom value (#242). + ...(this.supportsTemperature(modelId) && + this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), max_completion_tokens: info.maxTokens, stream: true, stream_options: { include_usage: true }, @@ -150,8 +149,8 @@ export class KenariHandler extends RouterProvider implements SingleCompletionHan stream: false, } - if (this.supportsTemperature(modelId)) { - requestOptions.temperature = this.options.modelTemperature ?? KENARI_DEFAULT_TEMPERATURE + if (this.supportsTemperature(modelId) && this.options.modelTemperature != null) { + requestOptions.temperature = this.options.modelTemperature } requestOptions.max_completion_tokens = info.maxTokens diff --git a/src/api/providers/lite-llm.ts b/src/api/providers/lite-llm.ts index babd74f16e3..c4dc56f72d3 100644 --- a/src/api/providers/lite-llm.ts +++ b/src/api/providers/lite-llm.ts @@ -270,8 +270,12 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa requestOptions.max_tokens = maxTokens } - if (info.supportsTemperature !== false && this.supportsTemperature(modelId)) { - requestOptions.temperature = this.options.modelTemperature ?? 0 + if ( + info.supportsTemperature !== false && + this.supportsTemperature(modelId) && + this.options.modelTemperature != null + ) { + requestOptions.temperature = this.options.modelTemperature } // LiteLLM recognizes X--Session-ID for per-conversation request correlation. @@ -485,8 +489,12 @@ export class LiteLLMHandler extends RouterProvider implements SingleCompletionHa ;(requestOptions as { reasoning_effort?: ReasoningEffortExtended }).reasoning_effort = reasoningEffort } - if (info.supportsTemperature !== false && this.supportsTemperature(modelId)) { - requestOptions.temperature = this.options.modelTemperature ?? 0 + if ( + info.supportsTemperature !== false && + this.supportsTemperature(modelId) && + this.options.modelTemperature != null + ) { + requestOptions.temperature = this.options.modelTemperature } // Newer OpenAI models require max_completion_tokens instead of the deprecated max_tokens parameter. diff --git a/src/api/providers/lm-studio.ts b/src/api/providers/lm-studio.ts index 54b0634d5d9..f58a7ab757b 100644 --- a/src/api/providers/lm-studio.ts +++ b/src/api/providers/lm-studio.ts @@ -1,13 +1,7 @@ import { Anthropic } from "@anthropic-ai/sdk" import OpenAI from "openai" -import { - type ModelInfo, - type ModelRecord, - openAiModelInfoSaneDefaults, - LMSTUDIO_DEFAULT_TEMPERATURE, - providerIdentifiers, -} from "@roo-code/types" +import { type ModelInfo, type ModelRecord, openAiModelInfoSaneDefaults, providerIdentifiers } from "@roo-code/types" import type { ApiHandlerOptions, GetModelsOptions } from "../../shared/api" @@ -162,7 +156,8 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan const params: OpenAI.Chat.ChatCompletionCreateParamsStreaming & { draft_model?: string } = { model: this.getModel().id, messages: openAiMessages, - temperature: this.options.modelTemperature ?? LMSTUDIO_DEFAULT_TEMPERATURE, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), stream: true, tools: this.convertToolsForOpenAI(metadata?.tools), tool_choice: metadata?.tool_choice, @@ -347,7 +342,8 @@ export class LmStudioHandler extends BaseProvider implements SingleCompletionHan const params: OpenAI.Chat.ChatCompletionCreateParamsNonStreaming & { draft_model?: string } = { model: this.getModel().id, messages: [{ role: "user", content: prompt }], - temperature: this.options.modelTemperature ?? LMSTUDIO_DEFAULT_TEMPERATURE, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), stream: false, } diff --git a/src/api/providers/mistral.ts b/src/api/providers/mistral.ts index 27673895c54..107825d8d3d 100644 --- a/src/api/providers/mistral.ts +++ b/src/api/providers/mistral.ts @@ -113,21 +113,21 @@ export class MistralHandler extends BaseProvider implements SingleCompletionHand messages: Anthropic.Messages.MessageParam[], metadata?: ApiHandlerCreateMessageMetadata, ): ApiStream { - const { id: model, info, maxTokens, temperature } = this.getModel() + const { id: model, info, maxTokens } = this.getModel() // Build request options const requestOptions: { model: string messages: ReturnType maxTokens: number - temperature: number tools?: MistralTool[] toolChoice?: "auto" | "none" | "any" | "required" | { type: "function"; function: { name: string } } } = { model, messages: [{ role: "system", content: systemPrompt }, ...convertToMistralMessages(messages)], maxTokens: maxTokens ?? info.maxTokens, - temperature, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), } requestOptions.tools = this.convertToolsForMistral(metadata?.tools ?? []) @@ -274,7 +274,7 @@ export class MistralHandler extends BaseProvider implements SingleCompletionHand // Fast-fail if the request was already aborted before building. throwIfAborted(options?.abortSignal) - const { id: model, temperature } = this.getModel() + const { id: model } = this.getModel() const callerAbortSignal = options?.abortSignal // Build a single signal that combines the external abort with the per-request // timeout (timeoutMs <= 0 disables the timeout; see mergeAbortSignalAndTimeout). @@ -291,7 +291,10 @@ export class MistralHandler extends BaseProvider implements SingleCompletionHand { model, messages: [{ role: "user", content: prompt }], - temperature, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { + temperature: this.options.modelTemperature, + }), }, Object.keys(requestOptions).length > 0 ? requestOptions : undefined, ) diff --git a/src/api/providers/nanogpt.ts b/src/api/providers/nanogpt.ts index 4fe1c7b49a0..e95c47e9702 100644 --- a/src/api/providers/nanogpt.ts +++ b/src/api/providers/nanogpt.ts @@ -157,7 +157,7 @@ export class NanoGptHandler extends RouterProvider implements SingleCompletionHa } if ( - this.options.modelTemperature !== undefined && + this.options.modelTemperature != null && info.supportsTemperature !== false && this.supportsTemperature(canonicalModelId) ) { @@ -212,7 +212,7 @@ export class NanoGptHandler extends RouterProvider implements SingleCompletionHa } if ( - this.options.modelTemperature !== undefined && + this.options.modelTemperature != null && info.supportsTemperature !== false && this.supportsTemperature(canonicalModelId) ) { diff --git a/src/api/providers/native-ollama.ts b/src/api/providers/native-ollama.ts index 690e89cd037..e7bb5a66602 100644 --- a/src/api/providers/native-ollama.ts +++ b/src/api/providers/native-ollama.ts @@ -25,7 +25,7 @@ import type { } from "../index" interface OllamaChatOptions { - temperature: number + temperature?: number num_ctx?: number } @@ -438,8 +438,12 @@ export class NativeOllamaHandler extends BaseProvider implements SingleCompletio private buildChatRequestOptions( useR1Format: boolean, ): [OllamaChatOptions, boolean | "high" | "medium" | "low" | undefined] { - const chatOptions: OllamaChatOptions = { - temperature: this.options.modelTemperature ?? (useR1Format ? DEEP_SEEK_DEFAULT_TEMPERATURE : 0), + const chatOptions: OllamaChatOptions = {} + // R1-format models require temperature; send their default when unset (#242). + if (this.options.modelTemperature != null) { + chatOptions.temperature = this.options.modelTemperature + } else if (useR1Format) { + chatOptions.temperature = DEEP_SEEK_DEFAULT_TEMPERATURE } // Only include num_ctx if explicitly set via ollamaNumCtx diff --git a/src/api/providers/openai-native.ts b/src/api/providers/openai-native.ts index 777c614f610..01b5634bdd0 100644 --- a/src/api/providers/openai-native.ts +++ b/src/api/providers/openai-native.ts @@ -414,10 +414,9 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio }, } : {}), - // Only include temperature if the model supports it - ...(model.info.supportsTemperature !== false && { - temperature: this.options.modelTemperature ?? OPENAI_NATIVE_DEFAULT_TEMPERATURE, - }), + // Only include temperature if the model supports it and the user set one (#242). + ...(model.info.supportsTemperature !== false && + this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), // Explicitly include the calculated max output tokens. // Use the per-request reserved output computed by Roo (params.maxTokens from getModelParams). ...(model.maxTokens ? { max_output_tokens: model.maxTokens } : {}), @@ -1882,9 +1881,9 @@ export class OpenAiNativeHandler extends BaseProvider implements SingleCompletio } } - // Only include temperature if the model supports it - if (model.info.supportsTemperature !== false) { - requestBody.temperature = this.options.modelTemperature ?? OPENAI_NATIVE_DEFAULT_TEMPERATURE + // Only include temperature if the model supports it and the user set one (#242). + if (model.info.supportsTemperature !== false && this.options.modelTemperature != null) { + requestBody.temperature = this.options.modelTemperature } // Include max_output_tokens if available diff --git a/src/api/providers/sambanova.ts b/src/api/providers/sambanova.ts index a15bc125776..fd4b78935d6 100644 --- a/src/api/providers/sambanova.ts +++ b/src/api/providers/sambanova.ts @@ -13,7 +13,6 @@ export class SambaNovaHandler extends BaseOpenAiCompatibleProvider { apiKey: options.zaiApiKey ?? NOT_PROVIDED, defaultProviderModelId: defaultModelId, providerModels: models, - defaultTemperature: ZAI_DEFAULT_TEMPERATURE, }) } @@ -93,15 +91,14 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { }) ?? undefined) - const temperature = this.options.modelTemperature ?? info.defaultTemperature ?? this.defaultTemperature - // Use Z.ai format to preserve reasoning_content and merge post-tool text into tool messages const convertedMessages = convertToZAiFormat(messages, { mergeToolResultText: true }) const params: ZAiChatCompletionParams = { model, max_tokens, - temperature, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), messages: [{ role: "system", content: systemPrompt }, ...convertedMessages], stream: true, stream_options: { include_usage: true }, @@ -153,7 +150,8 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { const params: ZAiChatCompletionParams = { model, messages: [{ role: "user", content: prompt }], - temperature: this.options.modelTemperature ?? info.defaultTemperature ?? this.defaultTemperature, + // Only send temperature when the user set a custom value (#242). + ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), thinking: { type: "enabled", clear_thinking: false }, reasoning_effort: reasoningEffort, } diff --git a/src/api/providers/zoo-gateway.ts b/src/api/providers/zoo-gateway.ts index 2171c49dda8..5a5c320d318 100644 --- a/src/api/providers/zoo-gateway.ts +++ b/src/api/providers/zoo-gateway.ts @@ -5,7 +5,6 @@ import OpenAI from "openai" import { zooGatewayDefaultModelId, zooGatewayDefaultModelInfo, - ZOO_GATEWAY_DEFAULT_TEMPERATURE, VERCEL_AI_GATEWAY_PROMPT_CACHING_MODELS, providerIdentifiers, type ModelRecord, @@ -236,9 +235,9 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio const body: OpenAI.Chat.ChatCompletionCreateParams = { model: modelId, messages: openAiMessages, - temperature: this.supportsTemperature(modelId) - ? (this.options.modelTemperature ?? ZOO_GATEWAY_DEFAULT_TEMPERATURE) - : undefined, + // Only send temperature when the user set a custom value (#242). + ...(this.supportsTemperature(modelId) && + this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), max_completion_tokens: info.maxTokens, stream: true, stream_options: { include_usage: true }, @@ -339,8 +338,8 @@ export class ZooGatewayHandler extends RouterProvider implements SingleCompletio stream: false, } - if (this.supportsTemperature(modelId)) { - requestOptions.temperature = this.options.modelTemperature ?? ZOO_GATEWAY_DEFAULT_TEMPERATURE + if (this.supportsTemperature(modelId) && this.options.modelTemperature != null) { + requestOptions.temperature = this.options.modelTemperature } requestOptions.max_completion_tokens = info.maxTokens From 00a3431ea74b044e7b630754ca9cddc22e1c7e51 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 13:58:17 +0100 Subject: [PATCH 03/12] test(providers): address PR 2650 review round 1 (#242) - tla: remove Bedrock from TemperatureOmission sinks; it retains a default instead of omitting, so the omission invariant does not apply - kenari: set modelTemperature in both unsupported-model fixtures so the supportsTemperature gate is actually exercised - temperature-omission: run every omission case with both undefined and null; use glm-4.5 for the ZAi non-thinking path (glm-4.7 routes to thinking) and assert the absence of thinking --- docs/architecture/tla/TemperatureOmission.tla | 8 +- src/api/providers/__tests__/kenari.spec.ts | 15 +- .../__tests__/temperature-omission.spec.ts | 241 ++++++++++-------- 3 files changed, 160 insertions(+), 104 deletions(-) diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index ca078fe285a..0d02629abf0 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -3,11 +3,17 @@ \* off (modelTemperature is nullish). A number, zero included, is a custom value. \* Sinks: createStream in BaseOpenAiCompatibleProvider; createMessage and \* completePrompt in LiteLlmHandler, NativeOllamaHandler, OpenAiNativeHandler, -\* MistralHandler, LmStudioHandler, BedrockHandler, VercelAiGatewayHandler, +\* MistralHandler, LmStudioHandler, VercelAiGatewayHandler, \* ZooGatewayHandler, KenariHandler, NanoGptHandler, FriendliHandler, ZaiHandler, \* GeminiHandler. Each writes (or omits) one temperature field in the request body. \* Exception: a reasoning format that requires temperature (DeepSeek reasoner in \* openai.ts PR 247, ollama useR1Format) sends its default when no custom value is set. +\* Not covered: AwsBedrockHandler. Its constructor replaces a nullish setting with +\* a retained default, and its non-adaptive request paths send that default. An +\* explicit 0 is kept; nothing is omitted, so no omission invariant applies to it. +\* Review ratchet: PR 2650 round 1 (comment 4658152524) removed Bedrock from the +\* sink list. The first version claimed Bedrock as an omission sink; the omission +\* invariant holds only for the providers that implement omission. \* Failure: the user turns custom temperature off and a provider still writes a \* temperature field (often 0), or overwrites an explicit 0, or writes null. \* Invariant: no temperature field when the value is nullish and the model is not a diff --git a/src/api/providers/__tests__/kenari.spec.ts b/src/api/providers/__tests__/kenari.spec.ts index 526db937982..04f296d0898 100644 --- a/src/api/providers/__tests__/kenari.spec.ts +++ b/src/api/providers/__tests__/kenari.spec.ts @@ -251,7 +251,13 @@ describe("KenariHandler", () => { }, }) - const handler = new KenariHandler({ kenariApiKey: "test-key", kenariModelId: "openai/o3-mini" }) + // A custom value is set on purpose: with modelTemperature unset, these + // tests would pass even if the supportsTemperature gate were removed. + const handler = new KenariHandler({ + kenariApiKey: "test-key", + kenariModelId: "openai/o3-mini", + modelTemperature: 0.7, + }) await collectStream(handler.createMessage("sys", [{ role: "user", content: "Hi" }])) expect(mockCreate).toHaveBeenCalledWith( @@ -364,7 +370,12 @@ describe("KenariHandler", () => { }) mockCreate.mockResolvedValue({ choices: [{ message: { content: "ok" } }] }) - const handler = new KenariHandler({ kenariApiKey: "test-key", kenariModelId: "openai/o3-mini" }) + // Custom value set on purpose (see the streaming counterpart above). + const handler = new KenariHandler({ + kenariApiKey: "test-key", + kenariModelId: "openai/o3-mini", + modelTemperature: 0.7, + }) expect(await handler.completePrompt("ping")).toBe("ok") const callArgs = mockCreate.mock.calls[0][0] diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts index d624d6cc341..cf492a57ab5 100644 --- a/src/api/providers/__tests__/temperature-omission.spec.ts +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -246,8 +246,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { const make = (options: Partial = {}) => new FireworksHandler({ fireworksApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) @@ -266,13 +266,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { const make = (options: Partial = {}) => new LiteLLMHandler({ litellmApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) - - it("I1: omits temperature when custom temperature is null", async () => { - await collectStream(make({ modelTemperature: null }).createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) @@ -286,11 +281,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make().completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("NativeOllamaHandler", () => { @@ -302,8 +300,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { ...options, }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockChat.mock.calls[0][0].options).toBe(false) }) @@ -317,11 +315,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockChat.mock.calls[0][0].options.temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockChat.mockResolvedValueOnce({ message: { content: "ok" } }) - await make().completePrompt("hello") - expect("temperature" in mockChat.mock.calls[0][0].options).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockChat.mockResolvedValueOnce({ message: { content: "ok" } }) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockChat.mock.calls[0][0].options).toBe(false) + }, + ) it("I2 (completePrompt): sends an explicit custom temperature of 0", async () => { mockChat.mockResolvedValueOnce({ message: { content: "ok" } }) @@ -339,8 +340,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { ...options, }) - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) const model = handler.getModel() const body = handler["buildRequestBody"](model, [], systemPrompt, undefined, undefined, { taskId: "test-task", @@ -366,13 +367,16 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(body.temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockResponsesCreate.mockResolvedValueOnce({ - output: [{ type: "message", content: [{ type: "output_text", text: "ok" }] }], - }) - await make().completePrompt("hello") - expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockResponsesCreate.mockResolvedValueOnce({ + output: [{ type: "message", content: [{ type: "output_text", text: "ok" }] }], + }) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) + }, + ) it("I3 (completePrompt): sends a custom temperature unchanged", async () => { mockResponsesCreate.mockResolvedValueOnce({ @@ -387,8 +391,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { const make = (options: Partial = {}) => new MistralHandler({ mistralApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockMistralStream.mock.calls[0][0]).toBe(false) }) @@ -402,10 +406,13 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockMistralStream.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - await make().completePrompt("hello") - expect("temperature" in mockMistralComplete.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockMistralComplete.mock.calls[0][0]).toBe(false) + }, + ) it("I3 (completePrompt): sends a custom temperature unchanged", async () => { await make({ modelTemperature: 0.7 }).completePrompt("hello") @@ -421,8 +428,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { ...options, }) - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) vitest.spyOn(handler, "countTokens").mockResolvedValue(1) await collectStream(handler.createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) @@ -442,11 +449,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make().completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("AwsBedrockHandler", () => { @@ -472,8 +482,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { const make = (options: Partial = {}) => new VercelAiGatewayHandler({ vercelAiGatewayApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) expect(handler.getModel().id).toBe(vercelAiGatewayDefaultModelId) await collectStream(handler.createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) @@ -489,19 +499,22 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make().completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("ZooGatewayHandler", () => { const make = (options: Partial = {}) => new ZooGatewayHandler({ zooSessionToken: "zoo_ext_test_token", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) expect(handler.getModel().id).toBe(zooGatewayDefaultModelId) await collectStream(handler.createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) @@ -517,19 +530,22 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make().completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("KenariHandler", () => { const make = (options: Partial = {}) => new KenariHandler({ kenariApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) expect(handler.getModel().id).toBe(kenariDefaultModelId) await collectStream(handler.createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) @@ -545,24 +561,22 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make().completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("NanoGptHandler", () => { const make = (options: Partial = {}) => new NanoGptHandler({ nanoGptModelId: nanoGptDefaultModelId, ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) - - it("I1: omits temperature when custom temperature is null", async () => { - await collectStream(make({ modelTemperature: null }).createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) @@ -576,19 +590,22 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is null", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make({ modelTemperature: null }).completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("FriendliHandler", () => { const make = (options: Partial = {}) => new FriendliHandler({ friendliApiKey: "test-key", ...options }) - it("I1: omits temperature when custom temperature is unset", async () => { - await collectStream(make().createMessage("system", userMessage)) + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }) @@ -607,20 +624,36 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { const make = (options: Partial = {}) => new ZAiHandler({ zaiApiKey: "test-key", zaiApiLine: "international_coding", ...options }) - it("I1: omits temperature when custom temperature is unset (non-thinking path)", async () => { - await collectStream(make().createMessage("system", userMessage)) - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1: omits temperature when custom temperature is %s (non-thinking path)", + async (modelTemperature) => { + // glm-4.5 declares no supportsReasoningEffort, so the handler takes the + // plain delegation path; the glm-4.7 default would route to thinking. + const handler = make({ apiModelId: "glm-4.5", modelTemperature }) + expect(handler.getModel().id).toBe("glm-4.5") + await collectStream(handler.createMessage("system", userMessage)) + expect("thinking" in mockCreate.mock.calls[0][0]).toBe(false) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) it("I2: sends an explicit custom temperature of 0 (non-thinking path)", async () => { - await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + const handler = make({ apiModelId: "glm-4.5", modelTemperature: 0 }) + expect(handler.getModel().id).toBe("glm-4.5") + await collectStream(handler.createMessage("system", userMessage)) + expect("thinking" in mockCreate.mock.calls[0][0]).toBe(false) expect(mockCreate.mock.calls[0][0].temperature).toBe(0) }) - it("I1: omits temperature when custom temperature is unset (thinking path)", async () => { - await collectStream(make({ apiModelId: "glm-5.3" }).createMessage("system", userMessage)) - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1: omits temperature when custom temperature is %s (thinking path)", + async (modelTemperature) => { + await collectStream( + make({ apiModelId: "glm-5.3", modelTemperature }).createMessage("system", userMessage), + ) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) it("I3: sends a custom temperature unchanged (thinking path)", async () => { await collectStream( @@ -629,11 +662,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) }) - it("I1 (completePrompt, thinking path): omits temperature when custom temperature is unset", async () => { - mockCreate.mockResolvedValueOnce(nonStreamingCompletion) - await make({ apiModelId: "glm-5.3" }).completePrompt("hello") - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt, thinking path): omits temperature when custom temperature is %s", + async (modelTemperature) => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ apiModelId: "glm-5.3", modelTemperature }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("GeminiHandler", () => { @@ -664,8 +700,8 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { return { mockGenerateContentStream, mockGenerateContent } } - it("I1: omits temperature when custom temperature is unset", async () => { - const handler = make() + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + const handler = make({ modelTemperature }) const { mockGenerateContentStream } = installClientMock(handler) await collectStream(handler.createMessage("system", userMessage)) const call = mockGenerateContentStream.mock.calls[0][0] @@ -688,13 +724,16 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect(call.config.temperature).toBe(0.7) }) - it("I1 (completePrompt): omits temperature when custom temperature is unset", async () => { - const handler = make() - const { mockGenerateContent } = installClientMock(handler) - await handler.completePrompt("hello") - const call = mockGenerateContent.mock.calls[0][0] - expect("temperature" in call.config).toBe(false) - }) + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + const handler = make({ modelTemperature }) + const { mockGenerateContent } = installClientMock(handler) + await handler.completePrompt("hello") + const call = mockGenerateContent.mock.calls[0][0] + expect("temperature" in call.config).toBe(false) + }, + ) it("I3 (completePrompt): sends a custom temperature unchanged", async () => { const handler = make({ modelTemperature: 0.7 }) From 3cb0e79f404d8d9adbb13e7cdfcb5febd4cbd3cb Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 14:31:50 +0100 Subject: [PATCH 04/12] test(vertex): expect temperature omission in completePrompt (#242) The windows platform-unit-test leg failed on 00a3431ea because vertex.spec.ts still asserted config.temperature: 1 after 1508ea479 made GeminiHandler.completePrompt omit temperature when no custom temperature is set. Drop the stale expectation, mirroring the gemini.spec.ts treatment in 1508ea479. The claude-sonnet-4-5@20250929 model id in the CI diff is Vertex's own default fallback (gemini-1.5-pro-001 is not in the vertexModels catalog) and matches expect.any(String); it is not cross-test state pollution. --- src/api/providers/__tests__/vertex.spec.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/api/providers/__tests__/vertex.spec.ts b/src/api/providers/__tests__/vertex.spec.ts index 32be5f6bfef..fb2c9999161 100644 --- a/src/api/providers/__tests__/vertex.spec.ts +++ b/src/api/providers/__tests__/vertex.spec.ts @@ -121,9 +121,9 @@ describe("VertexHandler", () => { expect.objectContaining({ model: expect.any(String), contents: [{ role: "user", parts: [{ text: "Test prompt" }] }], - config: expect.objectContaining({ - temperature: 1, - }), + // #242: temperature is omitted when no custom temperature is set, + // so the server default applies. + config: expect.objectContaining({}), }), ) }) @@ -161,7 +161,7 @@ describe("VertexHandler", () => { config: expect.objectContaining({ abortSignal: controller.signal, httpOptions: undefined, - temperature: 1, + // #242: temperature is omitted when no custom temperature is set. }), }), ) From 449d6486f30e09613dfdc9a8aa62aecd709dc7c2 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 14:35:31 +0100 Subject: [PATCH 05/12] fix(bedrock): omit temperature on non-adaptive requests when custom temperature is off (#242) CodeRabbit round-2 (thread 4658222935) blocked the linked issue: Bedrock still sent BEDROCK_DEFAULT_TEMPERATURE (0.3) for non-adaptive requests when no custom temperature was set, unlike the other providers fixed in 1508ea479. - Constructor no longer replaces a nullish modelTemperature with the retained default; the setting keeps its nullish state. - createMessage and completePrompt build inferenceConfig with the temperature key only when an explicit custom value exists; unset or null omits the key so the Bedrock service default applies. - The adaptive-thinking paths (4.7+/5 models) keep their unconditional omission; unchanged. - getModel still reports the service default as a UI/cost hint via getModelParams defaultTemperature. Tests: temperature-omission.spec.ts now covers Bedrock createMessage and completePrompt (I1 omit via it.each [undefined, null], I2 explicit 0, I3 custom unchanged, adaptive-path-unchanged assertions) plus the getModel hint. bedrock.spec.ts retained-default expectations updated to the omission behavior; the two Opus 4.6 accept-path guards now pass an explicit custom value. --- src/api/providers/__tests__/bedrock.spec.ts | 25 +++-- .../__tests__/temperature-omission.spec.ts | 91 ++++++++++++++++++- src/api/providers/bedrock.ts | 21 +++-- 3 files changed, 120 insertions(+), 17 deletions(-) diff --git a/src/api/providers/__tests__/bedrock.spec.ts b/src/api/providers/__tests__/bedrock.spec.ts index b5d241537c0..d9c4ff21e8e 100644 --- a/src/api/providers/__tests__/bedrock.spec.ts +++ b/src/api/providers/__tests__/bedrock.spec.ts @@ -2047,6 +2047,9 @@ describe("AwsBedrockHandler", () => { awsSecretKey: "test-secret-key", awsRegion: "us-east-1", enableReasoningEffort: true, + // #242: only an explicit custom temperature reaches the request; + // an unset value omits the key (covered in temperature-omission.spec.ts). + modelTemperature: 0.5, }) const generator = opus46Handler.createMessage("System prompt", messages) @@ -2058,8 +2061,8 @@ describe("AwsBedrockHandler", () => { // 4.6 still uses the budget_tokens-based thinking format. expect(commandArg.additionalModelRequestFields?.thinking?.type).toBe("enabled") expect(commandArg.additionalModelRequestFields?.thinking?.budget_tokens).toBeGreaterThan(0) - // 4.6 still accepts temperature. - expect(commandArg.inferenceConfig?.temperature).toBeDefined() + // 4.6 still accepts temperature; the custom value flows unchanged. + expect(commandArg.inferenceConfig?.temperature).toBe(0.5) }) it("should detect adaptive-thinking models via cross-region inference prefix (us.anthropic.claude-opus-4-8)", async () => { @@ -2136,7 +2139,8 @@ describe("AwsBedrockHandler", () => { it("completePrompt should still send temperature for older Claude Opus 4.6 (non-stream path)", async () => { // 4.6 and earlier still accept sampling parameters, so completePrompt must - // continue to send temperature for them. + // keep sending an explicit custom temperature for them. #242: an unset + // value omits the key (covered in temperature-omission.spec.ts). const mockConverseCommand = vi.mocked(ConverseCommand) const opus46Handler = new AwsBedrockHandler({ @@ -2144,6 +2148,7 @@ describe("AwsBedrockHandler", () => { awsAccessKey: "test-access-key", awsSecretKey: "test-secret-key", awsRegion: "us-east-1", + modelTemperature: 0.5, }) await opus46Handler.completePrompt("Test prompt") @@ -2151,8 +2156,8 @@ describe("AwsBedrockHandler", () => { expect(mockConverseCommand).toHaveBeenCalled() const commandArg = mockConverseCommand.mock.calls[0][0] as any - // 4.6 must still receive temperature. - expect(commandArg.inferenceConfig?.temperature).toBeDefined() + // 4.6 must still receive the explicit custom temperature. + expect(commandArg.inferenceConfig?.temperature).toBe(0.5) }) describe("custom ARN base model", () => { @@ -2215,11 +2220,13 @@ describe("AwsBedrockHandler", () => { createCustomArnHandler({ awsCustomArnBaseModelId: "anthropic.claude-sonnet-4-5-20250929-v1:0", enableReasoningEffort: true, + // #242: only an explicit custom temperature reaches the request. + modelTemperature: 0.5, }), ) expect(input).toMatchObject({ additionalModelRequestFields: { thinking: { type: "enabled" } } }) - expect(input.inferenceConfig?.temperature).toBeDefined() + expect(input.inferenceConfig?.temperature).toBe(0.5) }) it("sends no Anthropic fields for a non-Anthropic base model", async () => { @@ -2234,7 +2241,8 @@ describe("AwsBedrockHandler", () => { const input = await sendFirstRequest(handler) expect(input.modelId).toBe(appProfileArn) expect(input.additionalModelRequestFields).toBeUndefined() - expect(input.inferenceConfig?.temperature).toBeDefined() + // #242: no custom temperature set, so the key is omitted. + expect(input.inferenceConfig?.temperature).toBeUndefined() }) it("uses the generic fallback with user limits when the model is not listed", () => { @@ -2304,7 +2312,8 @@ describe("AwsBedrockHandler", () => { const input = await sendFirstRequest(handler) expect(input.modelId).toBe(profileArn) expect(input.additionalModelRequestFields).toBeUndefined() - expect(input.inferenceConfig?.temperature).toBeDefined() + // #242: no custom temperature set, so the key is omitted. + expect(input.inferenceConfig?.temperature).toBeUndefined() }) it("keeps the named model for a foundation-model ARN even with an explicit Other choice", () => { diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts index cf492a57ab5..fcb9efdcd77 100644 --- a/src/api/providers/__tests__/temperature-omission.spec.ts +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -36,6 +36,7 @@ vitest.mock("delay", () => ({ default: vitest.fn(() => Promise.resolve()), })) +import { ConverseCommand, ConverseStreamCommand } from "@aws-sdk/client-bedrock-runtime" import OpenAI from "openai" import { @@ -140,6 +141,20 @@ vitest.mock("@mistralai/mistralai", () => ({ }), })) +// AWS Bedrock SDK mock (mirrors bedrock.spec.ts). send resolves an empty +// stream so createMessage/completePrompt finish without parsing real chunks. +vitest.mock("@aws-sdk/client-bedrock-runtime", () => { + const mockSend = vitest.fn().mockResolvedValue({ stream: [] }) + const mockConverseStreamCommand = vitest.fn() + return { + BedrockRuntimeClient: vitest.fn().mockImplementation(function () { + return { send: mockSend } + }), + ConverseStreamCommand: mockConverseStreamCommand, + ConverseCommand: vitest.fn(), + } +}) + // Ollama SDK mock (mirrors native-ollama.spec.ts). const mockChat = vitest.fn() const mockIsProxyEnabled = vi.hoisted(() => vitest.fn(() => false)) @@ -181,6 +196,10 @@ vitest.mock("../fetchers/ollama", async (importOriginal) => { const mockGetOllamaModels = vitest.mocked(getOllamaModels) +// Bedrock command constructors (mocked module above). +const mockConverseStream = vitest.mocked(ConverseStreamCommand) +const mockConverse = vitest.mocked(ConverseCommand) + const userMessage = [{ role: "user" as const, content: "Hello" }] // Standard streaming completion chunks for the OpenAI chat-completions shape. @@ -208,6 +227,8 @@ const nonStreamingCompletion = { choices: [{ message: { content: "ok" } }] } beforeEach(() => { mockCreate.mockClear() + mockConverseStream.mockClear() + mockConverse.mockClear() // Return the stream synchronously: LiteLLM calls create(...).withResponse() // directly on the returned value (the real SDK returns an APIPromise). mockCreate.mockImplementation(() => makeCompletionStream()) @@ -469,11 +490,77 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { ...options, }) - it("I2: keeps an explicit custom temperature of 0 (no constructor clobber)", () => { + it.each([undefined, null])( + "I1 (createMessage): omits temperature when custom temperature is %s", + async (modelTemperature) => { + const handler = make({ modelTemperature }) + await collectStream(handler.createMessage("system", userMessage)) + expect(mockConverseStream).toHaveBeenCalled() + const { inferenceConfig } = mockConverseStream.mock.calls[0][0] + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }, + ) + + it("I2 (createMessage): sends an explicit custom temperature of 0", async () => { + const handler = make({ modelTemperature: 0 }) + await collectStream(handler.createMessage("system", userMessage)) + const { inferenceConfig } = mockConverseStream.mock.calls[0][0] + expect(inferenceConfig?.temperature).toBe(0) + }) + + it("I3 (createMessage): sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + await collectStream(handler.createMessage("system", userMessage)) + const { inferenceConfig } = mockConverseStream.mock.calls[0][0] + expect(inferenceConfig?.temperature).toBe(0.7) + }) + + it.each([undefined, null])( + "I1 (completePrompt): omits temperature when custom temperature is %s", + async (modelTemperature) => { + const handler = make({ modelTemperature }) + await handler.completePrompt("hello") + expect(mockConverse).toHaveBeenCalled() + const { inferenceConfig } = mockConverse.mock.calls[0][0] + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }, + ) + + it("I2 (completePrompt): sends an explicit custom temperature of 0", async () => { + const handler = make({ modelTemperature: 0 }) + await handler.completePrompt("hello") + const { inferenceConfig } = mockConverse.mock.calls[0][0] + expect(inferenceConfig?.temperature).toBe(0) + }) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + const handler = make({ modelTemperature: 0.7 }) + await handler.completePrompt("hello") + const { inferenceConfig } = mockConverse.mock.calls[0][0] + expect(inferenceConfig?.temperature).toBe(0.7) + }) + + it("adaptive path (createMessage): omits temperature even when a custom value is set", async () => { + const handler = make({ apiModelId: "anthropic.claude-opus-4-8", modelTemperature: 0.7 }) + await collectStream(handler.createMessage("system", userMessage)) + const { inferenceConfig } = mockConverseStream.mock.calls[0][0] + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }) + + it("adaptive path (completePrompt): omits temperature even when a custom value is set", async () => { + const handler = make({ apiModelId: "anthropic.claude-opus-4-8", modelTemperature: 0.7 }) + await handler.completePrompt("hello") + const { inferenceConfig } = mockConverse.mock.calls[0][0] + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }) + + it("I2 (getModel): keeps an explicit custom temperature of 0 (no constructor clobber)", () => { expect(make({ modelTemperature: 0 }).getModel().temperature).toBe(0) }) - it("unset keeps the getModelParams default (out of scope for #242)", () => { + it("getModel keeps the service-default hint when unset; requests omit it (#242)", () => { + // getModel reports the Bedrock service default as a UI/cost hint; + // the request paths above omit the key when no custom value is set. expect(make().getModel().temperature).toBe(BEDROCK_DEFAULT_TEMPERATURE) }) }) diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index 45ca068efd8..b2c9001b898 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -268,10 +268,9 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH if (this.arnInfo.awsUseCrossRegionInference) this.options.awsUseCrossRegionInference = true } - // An explicit 0 is a real custom value; only fill the default when unset (#242). - if (this.options.modelTemperature == null) { - this.options.modelTemperature = BEDROCK_DEFAULT_TEMPERATURE - } + // #242: keep modelTemperature nullish when no custom temperature is set. + // The non-adaptive request paths omit the key so the Bedrock service + // default applies; getModel still reports the service default as a hint. this.costModelConfig = this.getModel() @@ -511,10 +510,14 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH const inferenceConfig: BedrockInferenceConfig = { maxTokens: modelConfig.maxTokens || (modelConfig.info.maxTokens as number), // Claude 4.7+ (including 4.8) removed sampling parameters entirely — - // sending temperature causes a 400 error. + // sending temperature causes a 400 error. #242: the non-adaptive path + // sends only the user's custom value and omits the key when unset so + // the service default applies. ...(isAdaptiveThinkingModel ? {} - : { temperature: modelConfig.temperature ?? (this.options.modelTemperature as number) }), + : this.options.modelTemperature == null + ? {} + : { temperature: this.options.modelTemperature }), } // Check if 1M context is enabled for supported Claude 4 models @@ -896,9 +899,13 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH // Claude 4.7+ (including 4.8) removed sampling parameters entirely — // sending temperature causes a 400 error. Guard the non-stream path the // same way createMessage does so completePrompt also works for these models. + // #242: the non-adaptive path sends only the user's custom value and + // omits the key when unset so the service default applies. ...(this.isAdaptiveThinkingModel(modelConfig.id) ? {} - : { temperature: modelConfig.temperature ?? (this.options.modelTemperature as number) }), + : this.options.modelTemperature == null + ? {} + : { temperature: this.options.modelTemperature }), } // For completePrompt, use a unique conversation ID based on the prompt From 626050d1d6f472b544a210a4157188f9a1d8f86e Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 14:36:26 +0100 Subject: [PATCH 06/12] spec(tla): re-cover Bedrock as a temperature-omission sink with a retained-default divergence mode (#242) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round 1 removed Bedrock from the TemperatureOmission sink list as not covered. Round 2 (thread 4658222935) restored it after the code fix: both non-adaptive Bedrock request paths now omit the temperature key when the setting is nullish. - Header: sinks list includes AwsBedrockHandler non-adaptive paths; ratchet lines cite comment 4658222935; expect/gate/result lines cover the new variant. - New divergence mode BedrockRetainedDefault models the pre-fix shape (constructor clobber plus non-adaptive send of the default). It must fail OmitWhenUnset; TLC confirms it fails in 7 states while Fixed holds in 12. - Adaptive-thinking paths stay outside the spec as a capability gate. Gate: ./check.sh TemperatureOmission — Fixed passes (12 states), LegacyDefault/LegacyTruthy/NullPasses/BedrockRetainedDefault all fail (7 states each). --- ...eratureOmission.BedrockRetainedDefault.cfg | 4 +++ docs/architecture/tla/TemperatureOmission.tla | 32 ++++++++++++------- 2 files changed, 24 insertions(+), 12 deletions(-) create mode 100644 docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg diff --git a/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg new file mode 100644 index 00000000000..bb66c8799df --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "BedrockRetainedDefault" +SPECIFICATION Spec +INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index 0d02629abf0..49c31c0f372 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -5,27 +5,32 @@ \* completePrompt in LiteLlmHandler, NativeOllamaHandler, OpenAiNativeHandler, \* MistralHandler, LmStudioHandler, VercelAiGatewayHandler, \* ZooGatewayHandler, KenariHandler, NanoGptHandler, FriendliHandler, ZaiHandler, -\* GeminiHandler. Each writes (or omits) one temperature field in the request body. +\* GeminiHandler, and the two non-adaptive paths of AwsBedrockHandler. Each +\* writes (or omits) one temperature field in the request body. \* Exception: a reasoning format that requires temperature (DeepSeek reasoner in \* openai.ts PR 247, ollama useR1Format) sends its default when no custom value is set. -\* Not covered: AwsBedrockHandler. Its constructor replaces a nullish setting with -\* a retained default, and its non-adaptive request paths send that default. An -\* explicit 0 is kept; nothing is omitted, so no omission invariant applies to it. \* Review ratchet: PR 2650 round 1 (comment 4658152524) removed Bedrock from the -\* sink list. The first version claimed Bedrock as an omission sink; the omission -\* invariant holds only for the providers that implement omission. +\* sink list as not covered, because the constructor retained a default. Round 2 +\* (comment 4658222935) restored Bedrock as an omission sink after the fix: the +\* constructor keeps a nullish setting nullish and both non-adaptive request +\* paths omit the key. The adaptive-thinking paths omit unconditionally and stay +\* outside this spec as a capability gate. \* Failure: the user turns custom temperature off and a provider still writes a \* temperature field (often 0), or overwrites an explicit 0, or writes null. \* Invariant: no temperature field when the value is nullish and the model is not a \* reasoner format. An explicit 0 and any custom number are sent unchanged. -\* Expect: LegacyDefault, LegacyTruthy and NullPasses fail on unset or zero input. -\* Fixed holds. The provider constants are oracles. +\* Expect: LegacyDefault, LegacyTruthy, NullPasses and BedrockRetainedDefault +\* fail on unset or zero input. Fixed holds. The provider constants are oracles. +\* BedrockRetainedDefault reproduces the pre-fix Bedrock shape (constructor +\* clobber plus a non-adaptive send of the default) that round 2 removed. \* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours. -\* Result: Fixed holds in 12 states. LegacyDefault, LegacyTruthy and -\* NullPasses each fail in 7 states. No false alarm was retained. -\* Gate: Fixed must pass. LegacyDefault, LegacyTruthy and NullPasses must fail. +\* Result: Fixed holds in 12 states. LegacyDefault, LegacyTruthy, NullPasses and +\* BedrockRetainedDefault each fail in 7 states. No false alarm was retained. +\* Gate: Fixed must pass. LegacyDefault, LegacyTruthy, NullPasses and +\* BedrockRetainedDefault must fail. \* Property test: src/api/providers/__tests__/temperature-omission.spec.ts. -\* Not modeled: supportsTemperature capability gates, maxTokens and message fields. +\* Not modeled: supportsTemperature capability gates, Bedrock adaptive-thinking +\* paths, maxTokens and message fields. EXTENDS TLC CONSTANT Variant @@ -36,10 +41,13 @@ Inputs == [setting : {"nullish", "zero", "custom"}, reasoner : BOOLEAN] \* Assembly maps the source value to the field written into one request body. \* Fixed omits the field for a nullish value, except for a reasoner format. \* Each Variant models one unfixed assembly shape seen in the provider files. +\* BedrockRetainedDefault is the pre-fix Bedrock shape: the constructor +\* clobbered a nullish setting and the non-adaptive paths sent the default. AssembleValue(s, r) == IF Variant = "LegacyDefault" /\ s = "nullish" THEN "default" ELSE IF Variant = "LegacyTruthy" /\ s \in {"nullish", "zero"} THEN "default" ELSE IF Variant = "NullPasses" /\ s = "nullish" THEN "null" + ELSE IF Variant = "BedrockRetainedDefault" /\ s = "nullish" THEN "default" ELSE IF r /\ s = "nullish" THEN "default" ELSE IF s = "nullish" THEN "absent" ELSE s From f29c88b4e4e91817e8f1aa7e5f0619b9c0a8aa3e Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 15:02:33 +0100 Subject: [PATCH 07/12] test(ollama): pin R1-format default temperature in buildChatRequestOptions (#242) CodeRabbit round-2 Regression Evidence (review 6012424292) asked for a focused native-ollama.spec.ts test at the lowest valid layer for buildChatRequestOptions: deepseek-r1 with modelTemperature unset sends DEEP_SEEK_DEFAULT_TEMPERATURE, an explicit 0 or custom value wins, and completePrompt shares the same contract. - createMessage: it.each [undefined, null] expects options.temperature === DEEP_SEEK_DEFAULT_TEMPERATURE (key present), plus explicit 0 and custom 0.7 cases. - completePrompt: same unset/null expectation plus explicit 0. --- .../providers/__tests__/native-ollama.spec.ts | 119 ++++++++++++++++++ 1 file changed, 119 insertions(+) diff --git a/src/api/providers/__tests__/native-ollama.spec.ts b/src/api/providers/__tests__/native-ollama.spec.ts index 02e743c01fa..dae1a513a04 100644 --- a/src/api/providers/__tests__/native-ollama.spec.ts +++ b/src/api/providers/__tests__/native-ollama.spec.ts @@ -1,6 +1,7 @@ // pnpm exec vitest run api/providers/__tests__/native-ollama.spec.ts import { Anthropic } from "@anthropic-ai/sdk" +import { DEEP_SEEK_DEFAULT_TEMPERATURE } from "@roo-code/types" import { NativeOllamaHandler } from "../native-ollama" import { ApiHandlerOptions } from "../../../shared/api" @@ -367,6 +368,74 @@ describe("NativeOllamaHandler", () => { expect(results.some((r) => r.type === "text")).toBe(true) }) + describe("R1-format temperature (#242)", () => { + // R1-format models require a temperature; buildChatRequestOptions + // sends DEEP_SEEK_DEFAULT_TEMPERATURE when no custom value is set. + const makeR1 = (modelTemperature: number | null | undefined) => { + const options: ApiHandlerOptions = { + apiModelId: "deepseek-r1", + ollamaModelId: "deepseek-r1", + ollamaBaseUrl: "http://localhost:11434", + } + if (modelTemperature !== undefined) { + options.modelTemperature = modelTemperature + } + return new NativeOllamaHandler(options) + } + + it.each([undefined, null])( + "sends DEEP_SEEK_DEFAULT_TEMPERATURE when modelTemperature is %s", + async (modelTemperature) => { + handler = makeR1(modelTemperature) + + mockChat.mockImplementation(async function* () { + yield { message: { content: "ok" } } + }) + + await collectStream(handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])) + + const chatOptions = (mockChat.mock.calls[0][0] as Record).options as Record< + string, + unknown + > + expect("temperature" in chatOptions).toBe(true) + expect(chatOptions.temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + }, + ) + + it("sends an explicit custom temperature of 0 for deepseek-r1", async () => { + handler = makeR1(0) + + mockChat.mockImplementation(async function* () { + yield { message: { content: "ok" } } + }) + + await collectStream(handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])) + + const chatOptions = (mockChat.mock.calls[0][0] as Record).options as Record< + string, + unknown + > + expect(chatOptions.temperature).toBe(0) + }) + + it("sends a custom temperature unchanged for deepseek-r1", async () => { + handler = makeR1(0.7) + + mockChat.mockImplementation(async function* () { + yield { message: { content: "ok" } } + }) + + await collectStream(handler.createMessage("System", [{ role: "user" as const, content: "Hi" }])) + + const chatOptions = (mockChat.mock.calls[0][0] as Record).options as Record< + string, + unknown + > + expect(chatOptions.temperature).toBe(0.7) + }) + }) + it("should surface Ollama's native message.thinking field as reasoning", async () => { mockChat.mockImplementation(async function* () { yield { message: { content: "", thinking: "Reasoning step one" } } @@ -790,6 +859,56 @@ describe("NativeOllamaHandler", () => { expect(result).toBe("This is the response") }) + it.each([undefined, null])( + "completePrompt sends DEEP_SEEK_DEFAULT_TEMPERATURE for deepseek-r1 when modelTemperature is %s", + async (modelTemperature) => { + const options: ApiHandlerOptions = { + apiModelId: "deepseek-r1", + ollamaModelId: "deepseek-r1", + ollamaBaseUrl: "http://localhost:11434", + } + if (modelTemperature !== undefined) { + options.modelTemperature = modelTemperature + } + handler = new NativeOllamaHandler(options) + + mockChat.mockResolvedValue({ + message: { content: "ok" }, + }) + + await handler.completePrompt("Test prompt") + + const chatOptions = (mockChat.mock.calls[0][0] as Record).options as Record< + string, + unknown + > + expect("temperature" in chatOptions).toBe(true) + expect(chatOptions.temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + }, + ) + + it("completePrompt sends an explicit custom temperature of 0 for deepseek-r1", async () => { + const options: ApiHandlerOptions = { + apiModelId: "deepseek-r1", + ollamaModelId: "deepseek-r1", + ollamaBaseUrl: "http://localhost:11434", + modelTemperature: 0, + } + handler = new NativeOllamaHandler(options) + + mockChat.mockResolvedValue({ + message: { content: "ok" }, + }) + + await handler.completePrompt("Test prompt") + + const chatOptions = (mockChat.mock.calls[0][0] as Record).options as Record< + string, + unknown + > + expect(chatOptions.temperature).toBe(0) + }) + it("should not include num_ctx in completePrompt by default", async () => { mockChat.mockResolvedValue({ message: { content: "Response" }, From e7d98f8440ae251fc243dcdeaa07601d778c41c8 Mon Sep 17 00:00:00 2001 From: Phil Date: Sun, 22 Nov 2026 16:09:57 +0100 Subject: [PATCH 08/12] test(providers): pin exact temperature absence in vertex completePrompt and cover the omitted completePrompt arms (#242) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Round 3 review fixes on PR 2650: - vertex.spec.ts: both completePrompt tests now inspect the captured config and assert it has no temperature property; the subset objectContaining matchers alone accepted a config still carrying temperature (CodeRabbit 4658434316). - temperature-omission.spec.ts: add positive (I3) completePrompt arms for LiteLLM, LmStudio, VercelAiGateway, ZooGateway, Kenari, NanoGpt and ZAi, plus capability-gate arms (info.supportsTemperature false, RouterProvider supportsTemperature false) for LiteLLM, VercelAiGateway, ZooGateway, Kenari, NanoGpt and OpenAiNative — covering the nine changed lines codecov flagged (7080405454) and killing all fifteen surviving mutants on head f29c88b4e (verified by applying each mutant locally and watching the new tests fail). - TemperatureOmission.tla: round-3 ratchet note; findings classified as covered (TLC gate re-run: base passes, all four variants fail). --- docs/architecture/tla/TemperatureOmission.tla | 9 ++ .../__tests__/temperature-omission.spec.ts | 126 ++++++++++++++++++ src/api/providers/__tests__/vertex.spec.ts | 15 ++- 3 files changed, 147 insertions(+), 3 deletions(-) diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index 49c31c0f372..ac32134e4dd 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -15,6 +15,15 @@ \* constructor keeps a nullish setting nullish and both non-adaptive request \* paths omit the key. The adaptive-thinking paths omit unconditionally and stay \* outside this spec as a capability gate. +\* Round 3 (inline 4658434316, codecov 7080405454, mutation report on +\* f29c88b4e): three test-layer findings. The vertex completePrompt matchers +\* accepted a config that still carried temperature. Nine changed lines in six +\* sinks lacked focused completePrompt coverage. Fifteen mutants survived on the +\* changed guards. Covered: the invariant above already models every sink, so +\* the fixes land in the property-test file. The vertex exact-assertion fix and +\* the positive and capability-gate completePrompt arms are those tests. The +\* supportsTemperature gates stay a recorded gap (Not modeled below), pinned by +\* direct unit tests. \* Failure: the user turns custom temperature off and a provider still writes a \* temperature field (often 0), or overwrites an explicit 0, or writes null. \* Invariant: no temperature field when the value is nullish and the model is not a diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts index fcb9efdcd77..15ec0c6f4f4 100644 --- a/src/api/providers/__tests__/temperature-omission.spec.ts +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -97,6 +97,32 @@ const MODEL_CATALOG = vitest.hoisted(() => ({ supportsPromptCache: false, description: "NanoGpt default", }, + // Capability-gate fixtures for the router providers (#242): a catalog model + // whose info disables temperature, and an id that RouterProvider's + // supportsTemperature rejects (the o3-mini prefix rule). + "openai/gpt-6.1-terra": { + maxTokens: 32768, + contextWindow: 400000, + supportsImages: false, + supportsPromptCache: false, + supportsTemperature: false, + description: "Temperature disabled in model info", + }, + "openai/o3-mini-test": { + maxTokens: 4096, + contextWindow: 200000, + supportsImages: false, + supportsPromptCache: false, + description: "supportsTemperature(modelId) is false", + }, + "litellm-no-temp": { + maxTokens: 8192, + contextWindow: 200000, + supportsImages: false, + supportsPromptCache: false, + supportsTemperature: false, + description: "LiteLLM model with temperature disabled in info", + }, })) const MODEL_CATALOG_FETCH_TIMEOUT_MS = vitest.hoisted(() => 10_000) @@ -310,6 +336,24 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("completePrompt omits temperature when the model info disables it", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ litellmModelId: "litellm-no-temp", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("completePrompt omits temperature when supportsTemperature(modelId) is false", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ litellmModelId: "openai/o3-mini-test", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) }) describe("NativeOllamaHandler", () => { @@ -406,6 +450,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { await make({ modelTemperature: 0.7 }).completePrompt("hello") expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0.7) }) + + it("completePrompt omits temperature when the model info disables it", async () => { + mockResponsesCreate.mockResolvedValueOnce({ + output: [{ type: "message", content: [{ type: "output_text", text: "ok" }] }], + }) + await make({ apiModelId: "gpt-6.1-terra", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) + }) }) describe("MistralHandler", () => { @@ -478,6 +530,12 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) }) describe("AwsBedrockHandler", () => { @@ -594,6 +652,26 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("completePrompt omits temperature when the model info disables it", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ vercelAiGatewayModelId: "openai/gpt-6.1-terra", modelTemperature: 0.7 }).completePrompt( + "hello", + ) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("completePrompt omits temperature when supportsTemperature(modelId) is false", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ vercelAiGatewayModelId: "openai/o3-mini-test", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) }) describe("ZooGatewayHandler", () => { @@ -625,6 +703,18 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("completePrompt omits temperature when supportsTemperature(modelId) is false", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ zooGatewayModelId: "openai/o3-mini-test", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) }) describe("KenariHandler", () => { @@ -656,6 +746,18 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("completePrompt omits temperature when supportsTemperature(modelId) is false", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ kenariModelId: "openai/o3-mini-test", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) }) describe("NanoGptHandler", () => { @@ -685,6 +787,24 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("completePrompt omits temperature when the model info disables it", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ nanoGptModelId: "litellm-no-temp", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("completePrompt omits temperature when supportsTemperature(modelId) is false", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ nanoGptModelId: "openai/o3-mini-test", modelTemperature: 0.7 }).completePrompt("hello") + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) }) describe("FriendliHandler", () => { @@ -757,6 +877,12 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) }, ) + + it("I3 (completePrompt, thinking path): sends a custom temperature unchanged", async () => { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + await make({ apiModelId: "glm-5.3", modelTemperature: 0.7 }).completePrompt("hello") + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) }) describe("GeminiHandler", () => { diff --git a/src/api/providers/__tests__/vertex.spec.ts b/src/api/providers/__tests__/vertex.spec.ts index fb2c9999161..bb995a4c7df 100644 --- a/src/api/providers/__tests__/vertex.spec.ts +++ b/src/api/providers/__tests__/vertex.spec.ts @@ -121,11 +121,15 @@ describe("VertexHandler", () => { expect.objectContaining({ model: expect.any(String), contents: [{ role: "user", parts: [{ text: "Test prompt" }] }], - // #242: temperature is omitted when no custom temperature is set, - // so the server default applies. config: expect.objectContaining({}), }), ) + + // #242: objectContaining checks a subset, so a config that still + // carries a temperature key would pass the matcher above. Inspect + // the captured config and pin the exact contract. + const capturedConfig = vi.mocked(handler["client"].models.generateContent).mock.calls[0][0].config + expect(capturedConfig).not.toHaveProperty("temperature") }) it("should handle API errors for Gemini", async () => { @@ -161,10 +165,15 @@ describe("VertexHandler", () => { config: expect.objectContaining({ abortSignal: controller.signal, httpOptions: undefined, - // #242: temperature is omitted when no custom temperature is set. }), }), ) + + // #242: the abort-signal subset matcher above would also accept a + // config that still carries a temperature key. Pin the exact + // contract on the captured config. + const capturedConfig = vi.mocked(handler["client"].models.generateContent).mock.calls[0][0].config + expect(capturedConfig).not.toHaveProperty("temperature") }) it("should work without options (backward compatible)", async () => { From f5c87532d8a2f71d31e43cbf29f1d1630a04956e Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 01:40:47 +0100 Subject: [PATCH 09/12] fix(providers): omit temperature for reasoning-budget models and extend omission to openai, xai, deepseek (#2650 round) PR 2650 review round 4 (edelauna, thread 4688025467 on bedrock.ts + review body "also address this in Openai, XAI, and deepseek"). bedrock.ts: the #242 omission line sent the raw modelTemperature while a budget_tokens thinking request was on. Before #2650 the path sent the getModelParams result, which forces 1.0 for a reasoning-budget model; Anthropic rejects a temperature change under extended thinking, so the raw value is a 400. createMessage now omits the key whenever thinkingEnabled (adaptive branch unchanged). completePrompt sends no thinking field and is unchanged. Decision: omit rather than send 1.0 (the service fixes the value under thinking; an omitted key cannot be rejected; same shape as the adaptive branch and the DeepSeek thinking gate). openai.ts: both createMessage stream branches go through one resolveTemperature() helper - omit when unset (deepseek-reasoner keeps its default, supportsTemperature honored), and send the getModel() value for a custom setting so a hybrid reasoning model keeps the 1.0 precedence. The non-streaming branch never wrote the field before (a custom value was dropped there). xai.ts: temperature was always written from getModel() (the 0 fallback when custom temperature was off); now only when modelTemperature != null. deepseek.ts: non-thinking requests wrote DEEP_SEEK_DEFAULT_TEMPERATURE (0) when custom temperature was off; now omitted, legacy deepseek-reasoner alias keeps its default like openai.ts (PR #247 exception), thinking models keep omitting. Spec TemperatureOmission.tla: provider dimension (bedrock/openai/xai/ deepseek, Init constrained to reachable combinations) and thinking dimension; I1-I3 range over every sink; new I4 ReasoningBudgetNeutral; TypeOK. Sabotage cfgs XaiRetainedDefault and DeepSeekRetainedDefault fail I1, OpenAiDropsZero fails I2, OpenAiDropsCustom fails I3, RawUnderThinking fails I4 (each verified against every invariant alone). Fixed passes in 54 states. Ratchet: covered 0 / added 2 / gap 1. Tests: red-verified by stashing the fix (22 fail / 567 pass without it, 589/589 with it). Updated round-2 tests that had pinned the raw value under thinking (bedrock.spec.ts Opus 4.6 / Sonnet 4.5) and the xai/deepseek tests that pinned the 0 default. Gates: test:core 5037/5037, test:api 5281 passed, tsc, eslint, prettier green. --- ...eratureOmission.BedrockRetainedDefault.cfg | 2 +- ...ratureOmission.DeepSeekRetainedDefault.cfg | 4 + .../tla/TemperatureOmission.LegacyDefault.cfg | 2 +- .../tla/TemperatureOmission.LegacyTruthy.cfg | 2 +- .../tla/TemperatureOmission.NullPasses.cfg | 2 +- .../TemperatureOmission.OpenAiDropsCustom.cfg | 4 + .../TemperatureOmission.OpenAiDropsZero.cfg | 4 + .../TemperatureOmission.RawUnderThinking.cfg | 4 + ...TemperatureOmission.XaiRetainedDefault.cfg | 4 + docs/architecture/tla/TemperatureOmission.cfg | 2 +- docs/architecture/tla/TemperatureOmission.tla | 130 ++++++++--- src/api/providers/__tests__/bedrock.spec.ts | 17 +- src/api/providers/__tests__/deepseek.spec.ts | 32 ++- src/api/providers/__tests__/openai.spec.ts | 52 +++++ .../__tests__/temperature-omission.spec.ts | 209 +++++++++++++++++- src/api/providers/__tests__/xai.spec.ts | 28 ++- src/api/providers/bedrock.ts | 12 +- src/api/providers/deepseek.ts | 10 +- src/api/providers/openai.ts | 33 ++- src/api/providers/xai.ts | 8 +- 20 files changed, 497 insertions(+), 64 deletions(-) create mode 100644 docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg diff --git a/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg index bb66c8799df..1e6c42b9c81 100644 --- a/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "BedrockRetainedDefault" SPECIFICATION Spec -INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg new file mode 100644 index 00000000000..8fd4976dda6 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "DeepSeekRetainedDefault" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg index 2ff70e52951..4ce537af6ae 100644 --- a/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "LegacyDefault" SPECIFICATION Spec -INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg index e87ebce3b97..1b6b251f379 100644 --- a/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg +++ b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "LegacyTruthy" SPECIFICATION Spec -INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.NullPasses.cfg b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg index 839a6a05684..262c23d6a57 100644 --- a/docs/architecture/tla/TemperatureOmission.NullPasses.cfg +++ b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "NullPasses" SPECIFICATION Spec -INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg b/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg new file mode 100644 index 00000000000..b1a7694e209 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "OpenAiDropsCustom" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg b/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg new file mode 100644 index 00000000000..b6c65d768fe --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "OpenAiDropsZero" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg b/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg new file mode 100644 index 00000000000..6beabe61099 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "RawUnderThinking" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg new file mode 100644 index 00000000000..1f30eaf2270 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "XaiRetainedDefault" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.cfg b/docs/architecture/tla/TemperatureOmission.cfg index c18bc954625..f2f675b4cdd 100644 --- a/docs/architecture/tla/TemperatureOmission.cfg +++ b/docs/architecture/tla/TemperatureOmission.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "Fixed" SPECIFICATION Spec -INVARIANTS OmitWhenUnset ExplicitZeroKept CustomKept +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index ac32134e4dd..ff95020dd03 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -3,10 +3,10 @@ \* off (modelTemperature is nullish). A number, zero included, is a custom value. \* Sinks: createStream in BaseOpenAiCompatibleProvider; createMessage and \* completePrompt in LiteLlmHandler, NativeOllamaHandler, OpenAiNativeHandler, -\* MistralHandler, LmStudioHandler, VercelAiGatewayHandler, -\* ZooGatewayHandler, KenariHandler, NanoGptHandler, FriendliHandler, ZaiHandler, -\* GeminiHandler, and the two non-adaptive paths of AwsBedrockHandler. Each -\* writes (or omits) one temperature field in the request body. +\* MistralHandler, LmStudioHandler, VercelAiGatewayHandler, ZooGatewayHandler, +\* KenariHandler, NanoGptHandler, FriendliHandler, ZaiHandler, GeminiHandler, and +\* the two non-adaptive paths of AwsBedrockHandler. Each writes (or omits) one +\* temperature field in the request body. \* Exception: a reasoning format that requires temperature (DeepSeek reasoner in \* openai.ts PR 247, ollama useR1Format) sends its default when no custom value is set. \* Review ratchet: PR 2650 round 1 (comment 4658152524) removed Bedrock from the @@ -24,60 +24,126 @@ \* the positive and capability-gate completePrompt arms are those tests. The \* supportsTemperature gates stay a recorded gap (Not modeled below), pinned by \* direct unit tests. +\* Round 4 (edelauna review, thread 4688025467 on bedrock.ts and the review body +\* "also address this in Openai, XAI, and deepseek"): two findings, two added. +\* (a) The Bedrock omission line sent the raw setting while a budget_tokens +\* thinking request was on. Before PR 2650 that path sent the getModelParams +\* result, which forces 1.0 for a reasoning-budget model (model-params.ts; the +\* in-tree note says Anthropic rejects a temperature change under extended +\* thinking). Added: the thinking dimension and invariant I4. I2 and I3 now hold +\* for a non-thinking request only. Decision: the thinking case omits the key +\* (same shape as the adaptive branch and the DeepSeek thinking gate); it does +\* not send 1.0, because the service fixes that value and an omitted key cannot +\* be rejected. OpenAiHandler keeps the getModelParams route: a custom value is +\* its getModel() result, which is the neutral value for a hybrid model. +\* (b) OpenAiHandler, XAIHandler and DeepSeekHandler were not omission sinks. +\* XAI and DeepSeek wrote the default (0) when the setting was nullish, and the +\* non-streaming branch of OpenAiHandler.createMessage never wrote a custom +\* value. Added: the provider dimension; I1, I2 and I3 range over each sink. +\* Covered: 0. Added: 2. Gap: 1 (the supportsTemperature gates below). \* Failure: the user turns custom temperature off and a provider still writes a -\* temperature field (often 0), or overwrites an explicit 0, or writes null. +\* temperature field (often 0), or overwrites an explicit 0, or writes null; or a +\* budget-thinking request carries a non-neutral temperature. \* Invariant: no temperature field when the value is nullish and the model is not a -\* reasoner format. An explicit 0 and any custom number are sent unchanged. -\* Expect: LegacyDefault, LegacyTruthy, NullPasses and BedrockRetainedDefault -\* fail on unset or zero input. Fixed holds. The provider constants are oracles. +\* reasoner format. An explicit 0 and any custom number are sent unchanged on a +\* non-thinking request. A thinking request sends no temperature (Bedrock, DeepSeek) +\* or the neutral value that getModelParams forces (OpenAiHandler), never the setting. +\* Expect: LegacyDefault, LegacyTruthy, NullPasses, BedrockRetainedDefault, +\* XaiRetainedDefault and DeepSeekRetainedDefault fail on unset or zero input; +\* OpenAiDropsZero fails I2, OpenAiDropsCustom fails I3, RawUnderThinking fails +\* I4. Fixed holds. The provider constants are oracles. \* BedrockRetainedDefault reproduces the pre-fix Bedrock shape (constructor \* clobber plus a non-adaptive send of the default) that round 2 removed. -\* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours. -\* Result: Fixed holds in 12 states. LegacyDefault, LegacyTruthy, NullPasses and -\* BedrockRetainedDefault each fail in 7 states. No false alarm was retained. -\* Gate: Fixed must pass. LegacyDefault, LegacyTruthy, NullPasses and -\* BedrockRetainedDefault must fail. +\* XaiRetainedDefault and DeepSeekRetainedDefault reproduce the round-4 pre-fix +\* shapes: an unconditional send of the getModelParams default. OpenAiDropsZero +\* and OpenAiDropsCustom reproduce the non-streaming branch that never wrote the +\* field. RawUnderThinking reproduces the bedrock.ts:520 shape of round 2. +\* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours +\* per round. +\* Result: Fixed holds in 54 states (27 reachable inputs). Every sabotage cfg +\* fails the invariant named above. No false alarm was retained. +\* Gate: Fixed must pass. LegacyDefault, LegacyTruthy, NullPasses, +\* BedrockRetainedDefault, XaiRetainedDefault, DeepSeekRetainedDefault, +\* OpenAiDropsZero, OpenAiDropsCustom and RawUnderThinking must fail. \* Property test: src/api/providers/__tests__/temperature-omission.spec.ts. \* Not modeled: supportsTemperature capability gates, Bedrock adaptive-thinking -\* paths, maxTokens and message fields. +\* paths, maxTokens and message fields. The thinking dimension models +\* AwsBedrockHandler.createMessage only: its completePrompt sends no thinking +\* field, so a custom value stays valid there. OpenAiHandler.completePrompt sends +\* no temperature at all (I1 holds; I2 and I3 are a recorded gap for it). EXTENDS TLC CONSTANT Variant VARIABLES input, phase, sent -Inputs == [setting : {"nullish", "zero", "custom"}, reasoner : BOOLEAN] +Providers == {"bedrock", "openai", "xai", "deepseek"} +Settings == {"nullish", "zero", "custom"} -\* Assembly maps the source value to the field written into one request body. -\* Fixed omits the field for a nullish value, except for a reasoner format. -\* Each Variant models one unfixed assembly shape seen in the provider files. -\* BedrockRetainedDefault is the pre-fix Bedrock shape: the constructor -\* clobbered a nullish setting and the non-adaptive paths sent the default. -AssembleValue(s, r) == - IF Variant = "LegacyDefault" /\ s = "nullish" THEN "default" - ELSE IF Variant = "LegacyTruthy" /\ s \in {"nullish", "zero"} THEN "default" - ELSE IF Variant = "NullPasses" /\ s = "nullish" THEN "null" - ELSE IF Variant = "BedrockRetainedDefault" /\ s = "nullish" THEN "default" - ELSE IF r /\ s = "nullish" THEN "default" +\* Reachable inputs. An R1 reasoner format is an OpenAI-compatible or DeepSeek +\* model id, never a Bedrock or xAI model. A reasoning budget is a Bedrock +\* budget_tokens request, an OpenAI-compatible hybrid model, or a DeepSeek V4 +\* thinking request; xAI has no such model. An R1 reasoner is not a budget model. +Reachable(i) == (i.provider \in {"bedrock", "xai"} => ~i.reasoner) + /\ (i.provider = "xai" => ~i.thinking) + /\ (i.reasoner => ~i.thinking) + +Inputs == {i \in [setting : Settings, reasoner : BOOLEAN, thinking : BOOLEAN, provider : Providers] : Reachable(i)} + +\* The field written into one request body. "neutral" is the 1.0 that +\* getModelParams forces for a reasoning-budget model. +SentValues == {"absent", "null", "default", "zero", "custom", "neutral"} + +\* Fixed is the rule of round 4. A reasoner format keeps its default when the +\* value is nullish. A thinking request omits the field (Bedrock, DeepSeek) or +\* sends the neutral value (OpenAiHandler). Otherwise the setting is sent as is. +FixedValue(s, r, t, p) == + IF r /\ s = "nullish" THEN "default" ELSE IF s = "nullish" THEN "absent" + ELSE IF t /\ p = "openai" THEN "neutral" + ELSE IF t THEN "absent" ELSE s +\* Each Variant models one unfixed assembly shape seen in the provider files. +\* The legacy shapes and the retained-default shapes are scoped to a +\* non-thinking request, so each fails only the invariant the header names. +AssembleValue(s, r, t, p) == + IF Variant = "LegacyDefault" /\ s = "nullish" /\ ~t THEN "default" + ELSE IF Variant = "LegacyTruthy" /\ s \in {"nullish", "zero"} /\ ~t THEN "default" + ELSE IF Variant = "NullPasses" /\ s = "nullish" /\ ~t THEN "null" + ELSE IF Variant = "BedrockRetainedDefault" /\ s = "nullish" /\ p = "bedrock" + THEN (IF t THEN "neutral" ELSE "default") + ELSE IF Variant = "XaiRetainedDefault" /\ s = "nullish" /\ p = "xai" THEN "default" + ELSE IF Variant = "DeepSeekRetainedDefault" /\ s = "nullish" /\ p = "deepseek" /\ ~t /\ ~r + THEN "default" + ELSE IF Variant = "OpenAiDropsZero" /\ s = "zero" /\ p = "openai" /\ ~t THEN "absent" + ELSE IF Variant = "OpenAiDropsCustom" /\ s = "custom" /\ p = "openai" /\ ~t THEN "absent" + ELSE IF Variant = "RawUnderThinking" /\ t /\ s \in {"zero", "custom"} THEN s + ELSE FixedValue(s, r, t, p) + Init == /\ input \in Inputs /\ phase = "source" /\ sent = "absent" Assemble == /\ phase = "source" - /\ sent' = AssembleValue(input.setting, input.reasoner) + /\ sent' = AssembleValue(input.setting, input.reasoner, input.thinking, input.provider) /\ phase' = "assembled" /\ UNCHANGED input Next == Assemble Spec == Init /\ [][Next]_<> -\* I1: unset custom temperature sends no temperature field (F1, F3). +TypeOK == /\ input \in Inputs + /\ phase \in {"source", "assembled"} + /\ sent \in SentValues + +\* I1: unset custom temperature sends no temperature field (F1, F3) in every sink. OmitWhenUnset == phase = "assembled" /\ input.setting = "nullish" /\ ~input.reasoner => sent = "absent" -\* I2: an explicit 0 is sent as 0 (F2). -ExplicitZeroKept == phase = "assembled" /\ input.setting = "zero" => sent = "zero" -\* I3: a custom number is sent unchanged. -CustomKept == phase = "assembled" /\ input.setting = "custom" => sent = "custom" +\* I2: an explicit 0 is sent as 0 on a non-thinking request (F2). +ExplicitZeroKept == phase = "assembled" /\ input.setting = "zero" /\ ~input.thinking => sent = "zero" +\* I3: a custom number is sent unchanged on a non-thinking request. +CustomKept == phase = "assembled" /\ input.setting = "custom" /\ ~input.thinking => sent = "custom" +\* I4: a budget-thinking request never carries the setting; it omits the field +\* or sends the neutral value (round 4, thread 4688025467). +ReasoningBudgetNeutral == phase = "assembled" /\ input.thinking => sent \in {"absent", "neutral"} ==== diff --git a/src/api/providers/__tests__/bedrock.spec.ts b/src/api/providers/__tests__/bedrock.spec.ts index d9c4ff21e8e..e9627c37cd3 100644 --- a/src/api/providers/__tests__/bedrock.spec.ts +++ b/src/api/providers/__tests__/bedrock.spec.ts @@ -2039,16 +2039,17 @@ describe("AwsBedrockHandler", () => { expect(commandArg.inferenceConfig?.temperature).toBeUndefined() }) - it("should still send temperature and budget_tokens thinking for older Claude Opus 4.6", async () => { + it("should send budget_tokens thinking and omit temperature for older Claude Opus 4.6", async () => { // Regression guard: the adaptive-thinking branch must NOT activate for 4.6 or earlier. + // PR 2650 round 4 (thread 4688025467): budget_tokens thinking rejects a + // temperature change, so the request omits the key even when a custom + // value is set; before PR 2650 this path sent the getModelParams 1.0. const opus46Handler = new AwsBedrockHandler({ apiModelId: "anthropic.claude-opus-4-6-v1", awsAccessKey: "test-access-key", awsSecretKey: "test-secret-key", awsRegion: "us-east-1", enableReasoningEffort: true, - // #242: only an explicit custom temperature reaches the request; - // an unset value omits the key (covered in temperature-omission.spec.ts). modelTemperature: 0.5, }) @@ -2061,8 +2062,8 @@ describe("AwsBedrockHandler", () => { // 4.6 still uses the budget_tokens-based thinking format. expect(commandArg.additionalModelRequestFields?.thinking?.type).toBe("enabled") expect(commandArg.additionalModelRequestFields?.thinking?.budget_tokens).toBeGreaterThan(0) - // 4.6 still accepts temperature; the custom value flows unchanged. - expect(commandArg.inferenceConfig?.temperature).toBe(0.5) + // Thinking on: no temperature key at all (not the raw 0.5, not a forced 1.0). + expect("temperature" in (commandArg.inferenceConfig ?? {})).toBe(false) }) it("should detect adaptive-thinking models via cross-region inference prefix (us.anthropic.claude-opus-4-8)", async () => { @@ -2215,18 +2216,18 @@ describe("AwsBedrockHandler", () => { }) }) - it("keeps budget thinking and temperature for a Sonnet 4.5 base model", async () => { + it("keeps budget thinking and omits temperature for a Sonnet 4.5 base model", async () => { const input = await sendFirstRequest( createCustomArnHandler({ awsCustomArnBaseModelId: "anthropic.claude-sonnet-4-5-20250929-v1:0", enableReasoningEffort: true, - // #242: only an explicit custom temperature reaches the request. + // PR 2650 round 4: a custom value is omitted while thinking is on. modelTemperature: 0.5, }), ) expect(input).toMatchObject({ additionalModelRequestFields: { thinking: { type: "enabled" } } }) - expect(input.inferenceConfig?.temperature).toBe(0.5) + expect("temperature" in (input.inferenceConfig ?? {})).toBe(false) }) it("sends no Anthropic fields for a non-Anthropic base model", async () => { diff --git a/src/api/providers/__tests__/deepseek.spec.ts b/src/api/providers/__tests__/deepseek.spec.ts index 3b6c2496c93..55cf6aeb333 100644 --- a/src/api/providers/__tests__/deepseek.spec.ts +++ b/src/api/providers/__tests__/deepseek.spec.ts @@ -411,7 +411,7 @@ describe("DeepSeekHandler", () => { }, ) - it("should use the provider default temperature when reasoning is disabled for the vision alias", async () => { + it("should omit temperature when custom temperature is off and reasoning is disabled for the vision alias (#242)", async () => { const visionHandler = new DeepSeekHandler({ ...mockOptions, apiModelId: "deepseek-v4-flash-vision-exp", @@ -420,14 +420,39 @@ describe("DeepSeekHandler", () => { await collectStream(visionHandler.createMessage(systemPrompt, messages)) + // Before PR 2650 round 4 this sent DEEP_SEEK_DEFAULT_TEMPERATURE (0) — the issue title. expect(mockCreate.mock.calls[0][0]).toMatchObject({ model: "deepseek-v4-flash-vision-exp", thinking: { type: "disabled" }, - temperature: 0, }) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) expect(mockCreate.mock.calls[0][0].reasoning_effort).toBeUndefined() }) + it.each([0, 0.7])( + "should send a custom temperature of %s unchanged when reasoning is disabled (#242 I2/I3)", + async (modelTemperature) => { + const nonThinkingHandler = new DeepSeekHandler({ + ...mockOptions, + enableReasoningEffort: false, + modelTemperature, + }) + + await collectStream(nonThinkingHandler.createMessage(systemPrompt, messages)) + + expect(mockCreate.mock.calls[0][0].temperature).toBe(modelTemperature) + }, + ) + + it("should keep DEEP_SEEK_DEFAULT_TEMPERATURE for the legacy deepseek-reasoner alias when custom temperature is off", async () => { + // The reasoner exception openai.ts keeps from PR #247 applies to the same API here. + const reasonerHandler = new DeepSeekHandler({ ...mockOptions, apiModelId: "deepseek-reasoner" }) + + await collectStream(reasonerHandler.createMessage(systemPrompt, messages)) + + expect(mockCreate.mock.calls[0][0].temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + }) + it("should include usage information", async () => { const chunks: any[] = await collectStream(handler.createMessage(systemPrompt, messages)) @@ -726,7 +751,8 @@ describe("DeepSeekHandler", () => { const callArgs = mockCreate.mock.calls[0][0] expect(callArgs.thinking).toBeUndefined() expect(callArgs.reasoning_effort).toBeUndefined() - expect(callArgs.temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + // #242: custom temperature is off, so the key is omitted instead of the 0 default. + expect("temperature" in callArgs).toBe(false) }) it("should handle tool calls with reasoning_content", async () => { diff --git a/src/api/providers/__tests__/openai.spec.ts b/src/api/providers/__tests__/openai.spec.ts index 1e8daccb5bd..fb0f0e45657 100644 --- a/src/api/providers/__tests__/openai.spec.ts +++ b/src/api/providers/__tests__/openai.spec.ts @@ -647,6 +647,58 @@ describe("OpenAiHandler", () => { expect(callArgs.temperature).toBe(0) }) + // PR 2650 round 4 (edelauna review): the non-streaming branch of createMessage + // applies the same rule as the streaming branch — it never wrote the field before. + it.each([undefined, null])( + "non-streaming createMessage should omit temperature when custom temperature is %s", + async (modelTemperature) => { + // The default mock already answers a non-streaming request with a plain completion. + const nonStreamingHandler = new OpenAiHandler({ + ...mockOptions, + openAiStreamingEnabled: false, + modelTemperature, + }) + await collectStream(nonStreamingHandler.createMessage(systemPrompt, messages)) + expect(mockCreate).toHaveBeenCalled() + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) + + it.each([0, 0.7])( + "non-streaming createMessage should send a custom temperature of %s unchanged", + async (modelTemperature) => { + const nonStreamingHandler = new OpenAiHandler({ + ...mockOptions, + openAiStreamingEnabled: false, + modelTemperature, + }) + await collectStream(nonStreamingHandler.createMessage(systemPrompt, messages)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(modelTemperature) + }, + ) + + it.each([true, false])( + "createMessage (streaming %s) should send the getModel() value 1.0, not the raw setting, for a reasoning-budget model", + async (openAiStreamingEnabled) => { + // model-params.ts forces 1.0 for a hybrid reasoning model; the raw + // setting must not bypass it (the bedrock.ts:520 finding, PR 2650). + const hybridHandler = new OpenAiHandler({ + ...mockOptions, + openAiStreamingEnabled, + enableReasoningEffort: true, + modelTemperature: 0.3, + openAiCustomModelInfo: { + contextWindow: 128_000, + supportsPromptCache: false, + supportsReasoningBudget: true, + }, + }) + expect(hybridHandler.getModel().temperature).toBe(1) + await collectStream(hybridHandler.createMessage(systemPrompt, messages)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(1) + }, + ) + it("should include max_tokens when includeMaxTokens is true", async () => { const optionsWithMaxTokens: ApiHandlerOptions = { ...mockOptions, diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts index 15ec0c6f4f4..3c897b8bc09 100644 --- a/src/api/providers/__tests__/temperature-omission.spec.ts +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -2,8 +2,10 @@ // // Property tests for the TemperatureOmission.tla invariants (issue #242). // I1: modelTemperature is nullish => the request body has no temperature field. -// I2: modelTemperature is 0 => the body temperature is 0. -// I3: modelTemperature is c => the body temperature is c. +// I2: modelTemperature is 0 => the body temperature is 0 (non-thinking request). +// I3: modelTemperature is c => the body temperature is c (non-thinking request). +// I4: a budget-thinking request never carries the setting (omitted, or the neutral +// getModel() value for OpenAiHandler) — PR 2650 round 4, thread 4688025467. // The DeepSeek reasoner / ollama R1-format exception is deliberate (PR #247) // and is kept out of these assertions. @@ -41,6 +43,7 @@ import OpenAI from "openai" import { BEDROCK_DEFAULT_TEMPERATURE, + DEEP_SEEK_DEFAULT_TEMPERATURE, geminiDefaultModelId, kenariDefaultModelId, nanoGptDefaultModelId, @@ -49,6 +52,7 @@ import { } from "@roo-code/types" import { AwsBedrockHandler } from "../bedrock" +import { DeepSeekHandler } from "../deepseek" import { FireworksHandler } from "../fireworks" import { FriendliHandler } from "../friendli" import { GeminiHandler } from "../gemini" @@ -58,14 +62,17 @@ import { LmStudioHandler } from "../lm-studio" import { MistralHandler } from "../mistral" import { NanoGptHandler } from "../nanogpt" import { NativeOllamaHandler } from "../native-ollama" +import { OpenAiHandler } from "../openai" import { OpenAiNativeHandler } from "../openai-native" import { VercelAiGatewayHandler } from "../vercel-ai-gateway" +import { XAIHandler } from "../xai" import { ZAiHandler } from "../zai" import { ZooGatewayHandler } from "../zoo-gateway" import { getOllamaModels } from "../fetchers/ollama" import type { ApiHandlerOptions } from "../../../shared/api" import type { GoogleGenAI } from "@google/genai" import { asyncStreamFrom, collectStream } from "../../../test-utils/stream" +import { makeCreateMessageMetadata } from "../../../test-utils/api" // One shared catalog serves every handler that resolves models via modelCache. const MODEL_CATALOG = vitest.hoisted(() => ({ @@ -621,6 +628,204 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { // the request paths above omit the key when no custom value is set. expect(make().getModel().temperature).toBe(BEDROCK_DEFAULT_TEMPERATURE) }) + + it.each([0, 0.7])( + "I4 (createMessage): omits temperature %s while budget_tokens thinking is on (thread 4688025467)", + async (modelTemperature) => { + // Extended thinking is incompatible with a temperature change; the + // request omits the key instead of the raw setting or a forced 1.0. + const handler = make({ + apiModelId: "anthropic.claude-opus-4-6-v1", + enableReasoningEffort: true, + modelTemperature, + }) + await collectStream(handler.createMessage("system", userMessage)) + const { inferenceConfig, additionalModelRequestFields } = mockConverseStream.mock.calls[0][0] + expect(additionalModelRequestFields).toMatchObject({ thinking: { type: "enabled" } }) + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }, + ) + + it("I4 (createMessage): omits temperature when thinking is enabled through request metadata", async () => { + const handler = make({ apiModelId: "anthropic.claude-sonnet-4-5-20250929-v1:0", modelTemperature: 0.7 }) + await collectStream( + handler.createMessage("system", userMessage, { + ...makeCreateMessageMetadata(), + thinking: { enabled: true }, + }), + ) + const { inferenceConfig, additionalModelRequestFields } = mockConverseStream.mock.calls[0][0] + expect(additionalModelRequestFields).toMatchObject({ thinking: { type: "enabled" } }) + expect("temperature" in (inferenceConfig ?? {})).toBe(false) + }) + + it("completePrompt sends no thinking field, so a custom temperature stays valid with reasoning enabled", async () => { + const handler = make({ + apiModelId: "anthropic.claude-opus-4-6-v1", + enableReasoningEffort: true, + modelTemperature: 0.7, + }) + await handler.completePrompt("hello") + const { inferenceConfig } = mockConverse.mock.calls[0][0] + expect(inferenceConfig?.temperature).toBe(0.7) + }) + }) + + describe("OpenAiHandler (openai.ts createMessage, both stream modes)", () => { + const make = (options: Partial = {}) => + new OpenAiHandler({ + openAiApiKey: "test-api-key", + openAiModelId: "gpt-4", + openAiBaseUrl: "https://api.openai.com/v1", + ...options, + }) + + const streamModes = [true, false] as const + + // The non-streaming branch reads a plain completion; the streaming branch + // iterates the stream that beforeEach installs. + const prepare = (openAiStreamingEnabled: boolean) => { + if (!openAiStreamingEnabled) { + mockCreate.mockResolvedValueOnce(nonStreamingCompletion) + } + } + + it.each( + streamModes.flatMap((openAiStreamingEnabled) => + [undefined, null].map((modelTemperature) => ({ openAiStreamingEnabled, modelTemperature })), + ), + )( + "I1 (streaming $openAiStreamingEnabled): omits temperature when custom temperature is $modelTemperature", + async ({ openAiStreamingEnabled, modelTemperature }) => { + prepare(openAiStreamingEnabled) + await collectStream( + make({ openAiStreamingEnabled, modelTemperature }).createMessage("system", userMessage), + ) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) + + it.each(streamModes)( + "I2 (streaming %s): sends an explicit custom temperature of 0", + async (openAiStreamingEnabled) => { + prepare(openAiStreamingEnabled) + await collectStream( + make({ openAiStreamingEnabled, modelTemperature: 0 }).createMessage("system", userMessage), + ) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }, + ) + + it.each(streamModes)( + "I3 (streaming %s): sends a custom temperature unchanged", + async (openAiStreamingEnabled) => { + prepare(openAiStreamingEnabled) + await collectStream( + make({ openAiStreamingEnabled, modelTemperature: 0.7 }).createMessage("system", userMessage), + ) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }, + ) + + it.each(streamModes)( + "reasoner exception (streaming %s): keeps DEEP_SEEK_DEFAULT_TEMPERATURE for deepseek-reasoner when unset", + async (openAiStreamingEnabled) => { + prepare(openAiStreamingEnabled) + await collectStream( + make({ openAiStreamingEnabled, openAiModelId: "deepseek-reasoner" }).createMessage( + "system", + userMessage, + ), + ) + expect(mockCreate.mock.calls[0][0].temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + }, + ) + + it.each(streamModes)( + "I4 (streaming %s): sends the getModel() value 1.0, not the raw setting, for a reasoning-budget model", + async (openAiStreamingEnabled) => { + // model-params.ts forces 1.0 for a hybrid reasoning model; the raw + // setting must not bypass it (the bedrock.ts:520 finding, PR 2650). + const handler = make({ + openAiStreamingEnabled, + enableReasoningEffort: true, + modelTemperature: 0.3, + openAiCustomModelInfo: { + contextWindow: 128_000, + supportsPromptCache: false, + supportsReasoningBudget: true, + }, + }) + expect(handler.getModel().temperature).toBe(1) + prepare(openAiStreamingEnabled) + await collectStream(handler.createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(1) + }, + ) + }) + + describe("XAIHandler (xai.ts createMessage)", () => { + const make = (options: Partial = {}) => new XAIHandler(options) + + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) + expect(mockResponsesCreate.mock.calls[0][0]).toMatchObject({ max_output_tokens: expect.any(Number) }) + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + }) + + describe("DeepSeekHandler (deepseek.ts createMessage)", () => { + // Thinking off: the thinking gate omits temperature on its own (I4 below), + // so the settings gate is observable only with reasoning disabled. + const make = (options: Partial = {}) => + new DeepSeekHandler({ + deepSeekApiKey: "test-api-key", + apiModelId: "deepseek-v4-pro", + enableReasoningEffort: false, + ...options, + }) + + it.each([undefined, null])("I1: omits temperature when custom temperature is %s", async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0]).toMatchObject({ thinking: { type: "disabled" } }) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.7 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + + it("reasoner exception: keeps DEEP_SEEK_DEFAULT_TEMPERATURE for the legacy deepseek-reasoner alias when unset", async () => { + await collectStream(make({ apiModelId: "deepseek-reasoner" }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(DEEP_SEEK_DEFAULT_TEMPERATURE) + }) + + it.each([undefined, 0.7])( + "I4: omits temperature (%s) for a thinking model even when set", + async (modelTemperature) => { + await collectStream( + make({ enableReasoningEffort: true, modelTemperature }).createMessage("system", userMessage), + ) + expect(mockCreate.mock.calls[0][0]).toMatchObject({ thinking: { type: "enabled" } }) + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) }) describe("VercelAiGatewayHandler", () => { diff --git a/src/api/providers/__tests__/xai.spec.ts b/src/api/providers/__tests__/xai.spec.ts index ce345de2918..d78ccef7b45 100644 --- a/src/api/providers/__tests__/xai.spec.ts +++ b/src/api/providers/__tests__/xai.spec.ts @@ -283,18 +283,19 @@ describe("XAIHandler", () => { ) }) - it("createMessage should send max_output_tokens and temperature for the default model", async () => { + it("createMessage should send max_output_tokens and omit temperature for the default model (#242)", async () => { mockResponsesCreate.mockResolvedValueOnce(asyncStreamFrom([])) const stream = handler.createMessage("test prompt", []) await stream.next() + // Custom temperature is off: the key is absent so the service default applies. expect(mockResponsesCreate.mock.calls[0]?.[0]).toEqual( expect.objectContaining({ max_output_tokens: 65_536, - temperature: 0, }), ) + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) }) it("createMessage should omit tool parameters when no tools are provided", async () => { @@ -309,6 +310,24 @@ describe("XAIHandler", () => { expect(callArgs).not.toHaveProperty("parallel_tool_calls") }) + it("createMessage should send an explicit custom temperature of 0 (#242 I2)", async () => { + mockResponsesCreate.mockResolvedValueOnce(asyncStreamFrom([])) + + const custom = new XAIHandler({ modelTemperature: 0 }) + await custom.createMessage("test prompt", []).next() + + expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("createMessage should send a custom temperature unchanged (#242 I3)", async () => { + mockResponsesCreate.mockResolvedValueOnce(asyncStreamFrom([])) + + const custom = new XAIHandler({ modelTemperature: 0.7 }) + await custom.createMessage("test prompt", []).next() + + expect(mockResponsesCreate.mock.calls[0][0].temperature).toBe(0.7) + }) + it("completePrompt should return text from Responses API", async () => { const expectedResponse = "This is a test response" mockResponsesCreate.mockResolvedValueOnce({ @@ -506,18 +525,19 @@ describe("XAIHandler", () => { ) }) - it("createMessage should send max_output_tokens and temperature for the default model", async () => { + it("createMessage should send max_output_tokens and omit temperature for the default model (#242)", async () => { mockResponsesCreate.mockResolvedValueOnce(asyncStreamFrom([])) const stream = handler.createMessage("test prompt", []) await stream.next() + // Custom temperature is off: the key is absent so the service default applies. expect(mockResponsesCreate.mock.calls[0]?.[0]).toEqual( expect.objectContaining({ max_output_tokens: 65_536, - temperature: 0, }), ) + expect("temperature" in mockResponsesCreate.mock.calls[0][0]).toBe(false) }) it("should handle errors in completePrompt", async () => { diff --git a/src/api/providers/bedrock.ts b/src/api/providers/bedrock.ts index b2c9001b898..32ee4e62458 100644 --- a/src/api/providers/bedrock.ts +++ b/src/api/providers/bedrock.ts @@ -510,10 +510,14 @@ export class AwsBedrockHandler extends BaseProvider implements SingleCompletionH const inferenceConfig: BedrockInferenceConfig = { maxTokens: modelConfig.maxTokens || (modelConfig.info.maxTokens as number), // Claude 4.7+ (including 4.8) removed sampling parameters entirely — - // sending temperature causes a 400 error. #242: the non-adaptive path - // sends only the user's custom value and omits the key when unset so - // the service default applies. - ...(isAdaptiveThinkingModel + // sending temperature causes a 400 error. A budget_tokens thinking + // request rejects a temperature change too (Anthropic: extended thinking + // is incompatible with temperature modifications), so thinkingEnabled + // omits the key as well; before PR 2650 this path sent the getModelParams + // result, which forces 1.0 for that case (review thread 4688025467). + // #242: otherwise the non-adaptive path sends only the user's custom value + // and omits the key when unset so the service default applies. + ...(isAdaptiveThinkingModel || thinkingEnabled ? {} : this.options.modelTemperature == null ? {} diff --git a/src/api/providers/deepseek.ts b/src/api/providers/deepseek.ts index 25e660abec5..0ab3c5b0a3b 100644 --- a/src/api/providers/deepseek.ts +++ b/src/api/providers/deepseek.ts @@ -158,7 +158,15 @@ export class DeepSeekHandler extends OpenAiHandler { const requestOptions: DeepSeekChatCompletionParams = { model: modelId, - ...(!isThinkingModel && { temperature: temperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE }), + // #242: omit temperature when custom temperature is off so the service default + // applies (this line used to write the getModelParams fallback, 0). The legacy + // deepseek-reasoner alias keeps its default like openai.ts does (PR #247). A + // custom value still comes from getModel(), which keeps the reasoning-budget + // precedence. Thinking models omit the key: DeepSeek ignores it in thinking mode. + ...(!isThinkingModel && + (this.options.modelTemperature != null || modelId.includes("deepseek-reasoner")) && { + temperature: temperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE, + }), messages: convertedMessages, stream: true as const, stream_options: { include_usage: true }, diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index 98ea18df8ab..9325efb6109 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -109,6 +109,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl const strictToolSchemas = this.options.openAiStrictToolSchemas ?? DEFAULT_OPEN_AI_STRICT_TOOL_SCHEMAS const isAzureAiInference = this._isAzureAiInference(modelUrl) const deepseekReasoner = this.usesR1Format(modelId) + // #242: the temperature rule of both stream branches of createMessage lives in + // resolveTemperature, so a streaming toggle never drops or changes the field. + const temperature = this.resolveTemperature() if (modelId.includes("o1") || modelId.includes("o3") || modelId.includes("o4")) { yield* this.handleO3FamilyMessage(modelId, systemPrompt, messages, metadata) @@ -180,10 +183,8 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // flag and omit it when that flag is false. Beyond that, only send `temperature` when // the user set a custom value or the model needs a specific default (deepseek-reasoner); // otherwise omit it so the server's own default applies instead of forcing 0. - ...(modelInfo.supportsTemperature !== false && - (this.options.modelTemperature != null || deepseekReasoner) && { - temperature: this.options.modelTemperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE, - }), + // resolveTemperature keeps the getModel() precedence for a custom value. + ...(temperature !== undefined && { temperature }), messages: convertedMessages, stream: true as const, ...(isGrokXAI ? {} : { stream_options: { include_usage: true } }), @@ -251,6 +252,9 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl } else { let requestOptions: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming = { model: modelId, + // Same rule as the streaming branch; this branch never wrote the field + // before PR 2650 round 4, so a custom value was dropped here. + ...(temperature !== undefined && { temperature }), messages: deepseekReasoner ? convertToR1Format([{ role: "user", content: systemPrompt }, ...messages]) : [systemMessage, ...convertToOpenAiMessages(messages)], @@ -330,6 +334,27 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl return modelId.includes("deepseek-reasoner") || (this.options.openAiR1FormatEnabled ?? false) } + /** + * #242: the temperature for a chat-completions request body, or undefined to omit + * the key so the server's own default applies. Omitted when the model's + * `supportsTemperature` is false and when no custom value is set, unless the R1 + * reasoner format needs its specific default (deepseek-reasoner). A custom value + * is the getModel() result rather than the raw setting, so the reasoning-budget + * precedence holds: a hybrid reasoning model resolves to 1.0 (model-params.ts), + * the value bedrock.ts sent before PR 2650 switched it to the raw setting + * (review thread 4688025467). + */ + private resolveTemperature(): number | undefined { + const { info, temperature } = this.getModel() + if (info.supportsTemperature === false) { + return undefined + } + if (this.options.modelTemperature != null) { + return temperature + } + return this.usesR1Format(this.options.openAiModelId ?? "") ? DEEP_SEEK_DEFAULT_TEMPERATURE : undefined + } + override getModel() { const id = this.options.openAiModelId ?? "" const info: ModelInfo = this.options.openAiCustomModelInfo ?? openAiModelInfoSaneDefaults diff --git a/src/api/providers/xai.ts b/src/api/providers/xai.ts index 04fa2dd4fe7..b9c223aafb4 100644 --- a/src/api/providers/xai.ts +++ b/src/api/providers/xai.ts @@ -216,7 +216,13 @@ export class XAIHandler extends BaseProvider implements SingleCompletionHandler // Model params are always resolved by getModel(); send them unconditionally. requestBody.max_output_tokens = model.maxTokens - requestBody.temperature = model.temperature + // #242: omit temperature when custom temperature is off so the service default + // applies (this line used to write the getModelParams fallback, 0). A custom + // value still goes through getModel(), which keeps the reasoning-budget + // precedence (a hybrid reasoning model resolves to 1.0). + if (this.options.modelTemperature != null) { + requestBody.temperature = model.temperature + } if (responseTools) { requestBody.tools = responseTools From 4ad50bf93cb3cf345bf6ca13ff4763a230b7ed44 Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 02:05:16 +0100 Subject: [PATCH 10/12] refactor(openai): keep the streaming temperature spread intact and override it after the literal (#2650 round) Follow-up to f5c87532d. Replacing the streaming temperature spread in place put this branch's edit next to a line main changed in the openai.ts rework (#2498 Responses API path, #2643 thought signatures, #2684 max tokens), so the PR read has-conflicts and no pull_request workflow could build a merge commit for CI. The spread is restored byte for byte and the resolved value from resolveTemperature() is applied right after the literal instead: identical semantics (the getModel() value for a custom setting, no key when undefined), no merge of main, no force-push. git merge-file against main (a2922268a) reports zero conflicts. Gates re-run: scoped 589/589, test:core 5037/5037, test:api 5281 passed, tsc, eslint, prettier green. --- src/api/providers/openai.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/api/providers/openai.ts b/src/api/providers/openai.ts index 9325efb6109..14bff696f55 100644 --- a/src/api/providers/openai.ts +++ b/src/api/providers/openai.ts @@ -183,8 +183,10 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl // flag and omit it when that flag is false. Beyond that, only send `temperature` when // the user set a custom value or the model needs a specific default (deepseek-reasoner); // otherwise omit it so the server's own default applies instead of forcing 0. - // resolveTemperature keeps the getModel() precedence for a custom value. - ...(temperature !== undefined && { temperature }), + ...(modelInfo.supportsTemperature !== false && + (this.options.modelTemperature != null || deepseekReasoner) && { + temperature: this.options.modelTemperature ?? DEEP_SEEK_DEFAULT_TEMPERATURE, + }), messages: convertedMessages, stream: true as const, ...(isGrokXAI ? {} : { stream_options: { include_usage: true } }), @@ -194,6 +196,15 @@ export class OpenAiHandler extends BaseProvider implements SingleCompletionHandl parallel_tool_calls: metadata?.parallelToolCalls ?? true, } + // #242: the spread above writes the raw setting. resolveTemperature decides the final + // field for both stream branches — the getModel() value for a custom setting (so a + // hybrid reasoning model keeps the 1.0 precedence) or no key at all. + if (temperature !== undefined) { + requestOptions.temperature = temperature + } else { + delete requestOptions.temperature + } + // Add max_tokens if needed this.addMaxTokensIfNeeded(requestOptions, modelInfo) requestOptions = this.withExtraBody(requestOptions) From adbe5b06efa46b44267a92be4393959449b32c26 Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 09:51:30 +0100 Subject: [PATCH 11/12] fix(providers): keep main's declared temperature defaults on the merge tree (#2650 round) CI on 4ad50bf93 (windows platform-unit-test, ubuntu cancelled by fail-fast) failed baseten.spec.ts and zai.spec.ts on the CI merge of this branch with main. Reproduced locally on the merge tree: main's new fixture specs pin provider defaults this branch had stripped - baseten 0.5 for a plain request and the zai GLM thinking reasoning default (glm-5.4 expects 1). Editing those specs here would add/add-conflict with main's files, so the branch keeps them and restores the defaults instead. base-openai-compatible-provider.ts: the options type takes an optional defaultTemperature again and the streaming request sends the custom value, or the declared default, or omits (#242). Only baseten passes one, so the omit rule is unchanged for every other handler on this path. baseten.ts: declares defaultTemperature 0.5. zai.ts: the GLM thinking path sends info.defaultTemperature (falls back to ZAI_DEFAULT_TEMPERATURE) when no custom value is set; the plain path and completePrompt still omit, and a custom value under thinking still goes out. TemperatureOmission.tla round 5: providers gain zai and baseten, invariant DeclaredDefaultKept pins both declared defaults, OmitWhenUnset scopes to a non-thinking request without a declared default, and the sabotage cfgs BasDropsDefault and ZaiThinkingOmits reproduce the merge-tree drop. Fixed holds in 72 states; every sabotage cfg fails its named invariant. --- .../TemperatureOmission.BasDropsDefault.cfg | 4 + ...eratureOmission.BedrockRetainedDefault.cfg | 2 +- ...ratureOmission.DeepSeekRetainedDefault.cfg | 2 +- .../tla/TemperatureOmission.LegacyDefault.cfg | 2 +- .../tla/TemperatureOmission.LegacyTruthy.cfg | 2 +- .../tla/TemperatureOmission.NullPasses.cfg | 2 +- .../TemperatureOmission.OpenAiDropsCustom.cfg | 2 +- .../TemperatureOmission.OpenAiDropsZero.cfg | 2 +- .../TemperatureOmission.RawUnderThinking.cfg | 2 +- ...TemperatureOmission.XaiRetainedDefault.cfg | 2 +- .../TemperatureOmission.ZaiThinkingOmits.cfg | 4 + docs/architecture/tla/TemperatureOmission.cfg | 2 +- docs/architecture/tla/TemperatureOmission.tla | 82 ++++++++++++++----- .../__tests__/temperature-omission.spec.ts | 32 +++++++- .../base-openai-compatible-provider.ts | 12 ++- src/api/providers/baseten.ts | 2 + src/api/providers/zai.ts | 7 +- 17 files changed, 127 insertions(+), 36 deletions(-) create mode 100644 docs/architecture/tla/TemperatureOmission.BasDropsDefault.cfg create mode 100644 docs/architecture/tla/TemperatureOmission.ZaiThinkingOmits.cfg diff --git a/docs/architecture/tla/TemperatureOmission.BasDropsDefault.cfg b/docs/architecture/tla/TemperatureOmission.BasDropsDefault.cfg new file mode 100644 index 00000000000..260d51bc62b --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.BasDropsDefault.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "BasDropsDefault" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg index 1e6c42b9c81..100da63d0cb 100644 --- a/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.BedrockRetainedDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "BedrockRetainedDefault" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg index 8fd4976dda6..89637ddae5b 100644 --- a/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.DeepSeekRetainedDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "DeepSeekRetainedDefault" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg index 4ce537af6ae..6e4501a7a3a 100644 --- a/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.LegacyDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "LegacyDefault" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg index 1b6b251f379..4191590d567 100644 --- a/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg +++ b/docs/architecture/tla/TemperatureOmission.LegacyTruthy.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "LegacyTruthy" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.NullPasses.cfg b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg index 262c23d6a57..d9e1300341c 100644 --- a/docs/architecture/tla/TemperatureOmission.NullPasses.cfg +++ b/docs/architecture/tla/TemperatureOmission.NullPasses.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "NullPasses" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg b/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg index b1a7694e209..9f8f7597173 100644 --- a/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg +++ b/docs/architecture/tla/TemperatureOmission.OpenAiDropsCustom.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "OpenAiDropsCustom" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg b/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg index b6c65d768fe..8b36a0a190b 100644 --- a/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg +++ b/docs/architecture/tla/TemperatureOmission.OpenAiDropsZero.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "OpenAiDropsZero" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg b/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg index 6beabe61099..aaca357b442 100644 --- a/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg +++ b/docs/architecture/tla/TemperatureOmission.RawUnderThinking.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "RawUnderThinking" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg b/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg index 1f30eaf2270..6c02dbeb912 100644 --- a/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg +++ b/docs/architecture/tla/TemperatureOmission.XaiRetainedDefault.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "XaiRetainedDefault" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.ZaiThinkingOmits.cfg b/docs/architecture/tla/TemperatureOmission.ZaiThinkingOmits.cfg new file mode 100644 index 00000000000..b2e7c336911 --- /dev/null +++ b/docs/architecture/tla/TemperatureOmission.ZaiThinkingOmits.cfg @@ -0,0 +1,4 @@ +CONSTANT Variant = "ZaiThinkingOmits" +SPECIFICATION Spec +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept +CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.cfg b/docs/architecture/tla/TemperatureOmission.cfg index f2f675b4cdd..7c2701aecdb 100644 --- a/docs/architecture/tla/TemperatureOmission.cfg +++ b/docs/architecture/tla/TemperatureOmission.cfg @@ -1,4 +1,4 @@ CONSTANT Variant = "Fixed" SPECIFICATION Spec -INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral +INVARIANTS TypeOK OmitWhenUnset ExplicitZeroKept CustomKept ReasoningBudgetNeutral DeclaredDefaultKept CHECK_DEADLOCK FALSE diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index ff95020dd03..a8b22acc3e0 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -41,17 +41,33 @@ \* non-streaming branch of OpenAiHandler.createMessage never wrote a custom \* value. Added: the provider dimension; I1, I2 and I3 range over each sink. \* Covered: 0. Added: 2. Gap: 1 (the supportsTemperature gates below). +\* Round 5 (merge CI on 4ad50bf93: main's new fixture specs pin provider +\* defaults the merge tree dropped): baseten.spec.ts pins 0.5 for a plain +\* request and zai.spec.ts pins the reasoning default for GLM thinking. The +\* merge had stripped the declared defaults, so the request carried no +\* temperature at all. Added: the baseten sink with its declared default and +\* the zai thinking path that keeps the reasoning default; invariant +\* DeclaredDefaultKept. OmitWhenUnset now scopes to a non-thinking request +\* without a declared default; a custom value still goes out under thinking +\* for zai (GLM accepts it). Covered: 0. Added: 1. Gap: 1 (the +\* supportsTemperature gates below). \* Failure: the user turns custom temperature off and a provider still writes a -\* temperature field (often 0), or overwrites an explicit 0, or writes null; or a -\* budget-thinking request carries a non-neutral temperature. +\* temperature field (often 0), or overwrites an explicit 0, or writes null; or +\* a budget-thinking request carries a non-neutral temperature; or a provider +\* that declares a default for the path loses it and the request omits the +\* field. \* Invariant: no temperature field when the value is nullish and the model is not a -\* reasoner format. An explicit 0 and any custom number are sent unchanged on a -\* non-thinking request. A thinking request sends no temperature (Bedrock, DeepSeek) -\* or the neutral value that getModelParams forces (OpenAiHandler), never the setting. +\* reasoner format, on a non-thinking request without a declared default. An +\* explicit 0 and any custom number are sent unchanged on a non-thinking +\* request. A thinking request sends no temperature (Bedrock, DeepSeek) or the +\* neutral value that getModelParams forces (OpenAiHandler) or the reasoning +\* default (zai GLM thinking), never a raw wrong value. A declared default +\* (baseten) is sent when the value is nullish. \* Expect: LegacyDefault, LegacyTruthy, NullPasses, BedrockRetainedDefault, \* XaiRetainedDefault and DeepSeekRetainedDefault fail on unset or zero input; \* OpenAiDropsZero fails I2, OpenAiDropsCustom fails I3, RawUnderThinking fails -\* I4. Fixed holds. The provider constants are oracles. +\* I4, BasDropsDefault and ZaiThinkingOmits fail I5. Fixed holds. The provider +\* constants are oracles. \* BedrockRetainedDefault reproduces the pre-fix Bedrock shape (constructor \* clobber plus a non-adaptive send of the default) that round 2 removed. \* XaiRetainedDefault and DeepSeekRetainedDefault reproduce the round-4 pre-fix @@ -60,11 +76,12 @@ \* field. RawUnderThinking reproduces the bedrock.ts:520 shape of round 2. \* Cost: each TLC run takes less than 1 second. Agent work takes about 3 hours \* per round. -\* Result: Fixed holds in 54 states (27 reachable inputs). Every sabotage cfg +\* Result: Fixed holds in 72 states (36 reachable inputs). Every sabotage cfg \* fails the invariant named above. No false alarm was retained. \* Gate: Fixed must pass. LegacyDefault, LegacyTruthy, NullPasses, \* BedrockRetainedDefault, XaiRetainedDefault, DeepSeekRetainedDefault, -\* OpenAiDropsZero, OpenAiDropsCustom and RawUnderThinking must fail. +\* OpenAiDropsZero, OpenAiDropsCustom, RawUnderThinking, BasDropsDefault and +\* ZaiThinkingOmits must fail. \* Property test: src/api/providers/__tests__/temperature-omission.spec.ts. \* Not modeled: supportsTemperature capability gates, Bedrock adaptive-thinking \* paths, maxTokens and message fields. The thinking dimension models @@ -76,15 +93,17 @@ EXTENDS TLC CONSTANT Variant VARIABLES input, phase, sent -Providers == {"bedrock", "openai", "xai", "deepseek"} +Providers == {"bedrock", "openai", "xai", "deepseek", "zai", "baseten"} Settings == {"nullish", "zero", "custom"} \* Reachable inputs. An R1 reasoner format is an OpenAI-compatible or DeepSeek -\* model id, never a Bedrock or xAI model. A reasoning budget is a Bedrock -\* budget_tokens request, an OpenAI-compatible hybrid model, or a DeepSeek V4 -\* thinking request; xAI has no such model. An R1 reasoner is not a budget model. -Reachable(i) == (i.provider \in {"bedrock", "xai"} => ~i.reasoner) +\* model id, never a Bedrock, xAI, zai or baseten model. A reasoning budget is +\* a Bedrock budget_tokens request, an OpenAI-compatible hybrid model, or a +\* DeepSeek V4 thinking request; xAI has no such model. An R1 reasoner is not a +\* budget model. Baseten sends plain chat requests, never thinking ones. +Reachable(i) == (i.provider \in {"bedrock", "xai", "zai", "baseten"} => ~i.reasoner) /\ (i.provider = "xai" => ~i.thinking) + /\ (i.provider = "baseten" => ~i.thinking) /\ (i.reasoner => ~i.thinking) Inputs == {i \in [setting : Settings, reasoner : BOOLEAN, thinking : BOOLEAN, provider : Providers] : Reachable(i)} @@ -93,11 +112,16 @@ Inputs == {i \in [setting : Settings, reasoner : BOOLEAN, thinking : BOOLEAN, pr \* getModelParams forces for a reasoning-budget model. SentValues == {"absent", "null", "default", "zero", "custom", "neutral"} -\* Fixed is the rule of round 4. A reasoner format keeps its default when the -\* value is nullish. A thinking request omits the field (Bedrock, DeepSeek) or -\* sends the neutral value (OpenAiHandler). Otherwise the setting is sent as is. +\* Fixed is the rule of round 5. A reasoner format keeps its default when the +\* value is nullish. A declared provider default (baseten) is sent when the +\* value is nullish. A zai thinking request sends the reasoning default, any +\* other thinking request omits the field (or sends the neutral OpenAI value). +\* Otherwise the setting is sent as is. FixedValue(s, r, t, p) == IF r /\ s = "nullish" THEN "default" + ELSE IF s # "nullish" /\ t /\ p = "zai" THEN s + ELSE IF s = "nullish" /\ p = "baseten" THEN "default" + ELSE IF s = "nullish" /\ p = "zai" /\ t THEN "neutral" ELSE IF s = "nullish" THEN "absent" ELSE IF t /\ p = "openai" THEN "neutral" ELSE IF t THEN "absent" @@ -118,6 +142,8 @@ AssembleValue(s, r, t, p) == ELSE IF Variant = "OpenAiDropsZero" /\ s = "zero" /\ p = "openai" /\ ~t THEN "absent" ELSE IF Variant = "OpenAiDropsCustom" /\ s = "custom" /\ p = "openai" /\ ~t THEN "absent" ELSE IF Variant = "RawUnderThinking" /\ t /\ s \in {"zero", "custom"} THEN s + ELSE IF Variant = "BasDropsDefault" /\ s = "nullish" /\ p = "baseten" THEN "absent" + ELSE IF Variant = "ZaiThinkingOmits" /\ s = "nullish" /\ p = "zai" /\ t THEN "absent" ELSE FixedValue(s, r, t, p) Init == /\ input \in Inputs @@ -136,14 +162,30 @@ TypeOK == /\ input \in Inputs /\ phase \in {"source", "assembled"} /\ sent \in SentValues -\* I1: unset custom temperature sends no temperature field (F1, F3) in every sink. +\* A provider that declares a default for the modeled path: baseten on every +\* request. zai's reasoning default is thinking-only, so it stays out of this +\* predicate and I1 keeps covering the zai plain path. +DeclaresDefault(p) == p = "baseten" + +\* I1: unset custom temperature sends no temperature field (F1, F3) in every +\* sink, on a non-thinking request without a declared default. OmitWhenUnset == phase = "assembled" /\ input.setting = "nullish" /\ ~input.reasoner - => sent = "absent" + /\ ~input.thinking /\ ~DeclaresDefault(input.provider) => sent = "absent" \* I2: an explicit 0 is sent as 0 on a non-thinking request (F2). ExplicitZeroKept == phase = "assembled" /\ input.setting = "zero" /\ ~input.thinking => sent = "zero" \* I3: a custom number is sent unchanged on a non-thinking request. CustomKept == phase = "assembled" /\ input.setting = "custom" /\ ~input.thinking => sent = "custom" \* I4: a budget-thinking request never carries the setting; it omits the field -\* or sends the neutral value (round 4, thread 4688025467). -ReasoningBudgetNeutral == phase = "assembled" /\ input.thinking => sent \in {"absent", "neutral"} +\* or sends the neutral value (round 4, thread 4688025467). zai GLM thinking +\* accepts a custom temperature (main pins a default there), so its custom +\* value goes out and only its default is pinned by I5. +ReasoningBudgetNeutral == phase = "assembled" /\ input.thinking /\ input.provider # "zai" + => sent \in {"absent", "neutral"} +\* I5: a provider that declares a default for the path sends it when the value +\* is nullish (round 5: main's fixture specs pin baseten 0.5 and the zai GLM +\* reasoning default; the merge tree dropped both). +DeclaredDefaultKept == + (phase = "assembled" /\ input.setting = "nullish") => + /\ (input.provider = "baseten" => sent = "default") + /\ ((input.provider = "zai" /\ input.thinking) => sent = "neutral") ==== diff --git a/src/api/providers/__tests__/temperature-omission.spec.ts b/src/api/providers/__tests__/temperature-omission.spec.ts index 3c897b8bc09..1bed02404e3 100644 --- a/src/api/providers/__tests__/temperature-omission.spec.ts +++ b/src/api/providers/__tests__/temperature-omission.spec.ts @@ -53,6 +53,7 @@ import { import { AwsBedrockHandler } from "../bedrock" import { DeepSeekHandler } from "../deepseek" +import { BasetenHandler } from "../baseten" import { FireworksHandler } from "../fireworks" import { FriendliHandler } from "../friendli" import { GeminiHandler } from "../gemini" @@ -316,6 +317,31 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { }) }) + // Baseten declares 0.5 in its constructor (main's baseten.spec.ts pins it for + // a plain request), so the shared base path sends it instead of omitting. + describe("BasetenHandler (declared default, base-openai-compatible createStream)", () => { + const make = (options: Partial = {}) => + new BasetenHandler({ basetenApiKey: "test-key", ...options }) + + it.each([undefined, null])( + "I5: sends the declared 0.5 default when custom temperature is %s", + async (modelTemperature) => { + await collectStream(make({ modelTemperature }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.5) + }, + ) + + it("I2: sends an explicit custom temperature of 0", async () => { + await collectStream(make({ modelTemperature: 0 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0) + }) + + it("I3: sends a custom temperature unchanged", async () => { + await collectStream(make({ modelTemperature: 0.2 }).createMessage("system", userMessage)) + expect(mockCreate.mock.calls[0][0].temperature).toBe(0.2) + }) + }) + describe("LiteLLMHandler", () => { const make = (options: Partial = {}) => new LiteLLMHandler({ litellmApiKey: "test-key", ...options }) @@ -1058,12 +1084,14 @@ describe("temperature omission (issue #242, TemperatureOmission.tla)", () => { }) it.each([undefined, null])( - "I1: omits temperature when custom temperature is %s (thinking path)", + "I5: sends the model reasoning default when custom temperature is %s (thinking path)", async (modelTemperature) => { await collectStream( make({ apiModelId: "glm-5.3", modelTemperature }).createMessage("system", userMessage), ) - expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + // glm-5.3 declares defaultTemperature 1; main pins it for GLM thinking + // requests (merge round 5), so the thinking path keeps it. + expect(mockCreate.mock.calls[0][0].temperature).toBe(1) }, ) diff --git a/src/api/providers/base-openai-compatible-provider.ts b/src/api/providers/base-openai-compatible-provider.ts index 72c25d58226..5f99c4d4ee8 100644 --- a/src/api/providers/base-openai-compatible-provider.ts +++ b/src/api/providers/base-openai-compatible-provider.ts @@ -20,6 +20,7 @@ type BaseOpenAiCompatibleProviderOptions = ApiHandlerO baseURL: string defaultProviderModelId: ModelName providerModels: Record + defaultTemperature?: number } export abstract class BaseOpenAiCompatibleProvider @@ -30,6 +31,7 @@ export abstract class BaseOpenAiCompatibleProvider protected readonly baseURL: string protected readonly defaultProviderModelId: ModelName protected readonly providerModels: Record + protected readonly defaultTemperature: number | undefined protected readonly options: ApiHandlerOptions @@ -40,6 +42,7 @@ export abstract class BaseOpenAiCompatibleProvider baseURL, defaultProviderModelId, providerModels, + defaultTemperature, ...options }: BaseOpenAiCompatibleProviderOptions) { super() @@ -48,6 +51,7 @@ export abstract class BaseOpenAiCompatibleProvider this.baseURL = baseURL this.defaultProviderModelId = defaultProviderModelId this.providerModels = providerModels + this.defaultTemperature = defaultTemperature this.options = options @@ -83,8 +87,12 @@ export abstract class BaseOpenAiCompatibleProvider const params: OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming = { model, max_tokens, - // Only send temperature when the user set a custom value (#242). - ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), + // Send the custom value, or the declared provider default, or omit (#242). + ...(this.options.modelTemperature != null + ? { temperature: this.options.modelTemperature } + : this.defaultTemperature != null + ? { temperature: this.defaultTemperature } + : {}), messages: [{ role: "system", content: systemPrompt }, ...convertToOpenAiMessages(messages)], stream: true, stream_options: { include_usage: true }, diff --git a/src/api/providers/baseten.ts b/src/api/providers/baseten.ts index 8a9b6c7a12f..0bdb956c095 100644 --- a/src/api/providers/baseten.ts +++ b/src/api/providers/baseten.ts @@ -12,6 +12,8 @@ export class BasetenHandler extends BaseOpenAiCompatibleProvider apiKey: options.basetenApiKey, defaultProviderModelId: basetenDefaultModelId, providerModels: basetenModels, + // Main pins this default on a plain request (baseten.spec.ts). + defaultTemperature: 0.5, }) } } diff --git a/src/api/providers/zai.ts b/src/api/providers/zai.ts index 54f47e1d1d6..822df61d9cf 100644 --- a/src/api/providers/zai.ts +++ b/src/api/providers/zai.ts @@ -5,6 +5,7 @@ import { internationalZAiDefaultModelId, mainlandZAiDefaultModelId, type ModelInfo, + ZAI_DEFAULT_TEMPERATURE, zaiApiLineConfigs, getZAiModels, } from "@roo-code/types" @@ -97,8 +98,10 @@ export class ZAiHandler extends BaseOpenAiCompatibleProvider { const params: ZAiChatCompletionParams = { model, max_tokens, - // Only send temperature when the user set a custom value (#242). - ...(this.options.modelTemperature != null && { temperature: this.options.modelTemperature }), + // A thinking request keeps the model's reasoning default when no custom value is set (#242). + ...(this.options.modelTemperature != null + ? { temperature: this.options.modelTemperature } + : { temperature: info.defaultTemperature ?? ZAI_DEFAULT_TEMPERATURE }), messages: [{ role: "system", content: systemPrompt }, ...convertedMessages], stream: true, stream_options: { include_usage: true }, From 3f36dbed6155e3e249d59b21a50f907adf5df7b5 Mon Sep 17 00:00:00 2001 From: Phil Date: Fri, 4 Dec 2026 17:03:08 +0100 Subject: [PATCH 12/12] test(openai): pin the supportsTemperature omission guard with a custom value (#2650 round) CodeRabbit review 6191828039, inline 4801992024 (Trivial, real): the existing supportsTemperature:false test set no modelTemperature, so resolveTemperature omitted the key regardless of the guard - removing the guard left that test green. The new it.each sends modelTemperature 0.7 with supportsTemperature false on both stream branches and asserts the key is absent. RED-VERIFIED: with the guard sabotaged out of openai.ts exactly the two new cases fail (2 failed | 2 passed); restored, they pass. getModelParams keeps the value for supportsTemperature:false in the openai format (only o1/o3-mini ids drop it), so the failure surfaces through the guard and not through a second drop below it. TemperatureOmission.tla round 6 header note: the gate stays the recorded gap (unmodeled by design); its direct unit test was mutation-vacuous and is now strengthened. No invariant change; check.sh TemperatureOmission re-run: base cfg passes (72 states), all 11 sabotage cfgs fail. --- docs/architecture/tla/TemperatureOmission.tla | 6 +++++ src/api/providers/__tests__/openai.spec.ts | 23 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/docs/architecture/tla/TemperatureOmission.tla b/docs/architecture/tla/TemperatureOmission.tla index a8b22acc3e0..83341442078 100644 --- a/docs/architecture/tla/TemperatureOmission.tla +++ b/docs/architecture/tla/TemperatureOmission.tla @@ -51,6 +51,12 @@ \* without a declared default; a custom value still goes out under thinking \* for zai (GLM accepts it). Covered: 0. Added: 1. Gap: 1 (the \* supportsTemperature gates below). +\* Round 6 (CR 6191828039, inline 4801992024 on openai.spec.ts): the direct +\* unit test pinning the openai supportsTemperature gate set no custom value, +\* so the omission held without the guard and guard removal was invisible. +\* Covered: 0. Added: 0. Gap: 1 (unchanged: the gate stays outside the model +\* by design; its pin is the strengthened unit test, which now sends a custom +\* 0.7 on both stream branches). \* Failure: the user turns custom temperature off and a provider still writes a \* temperature field (often 0), or overwrites an explicit 0, or writes null; or \* a budget-thinking request carries a non-neutral temperature; or a provider diff --git a/src/api/providers/__tests__/openai.spec.ts b/src/api/providers/__tests__/openai.spec.ts index fb0f0e45657..f5028f72618 100644 --- a/src/api/providers/__tests__/openai.spec.ts +++ b/src/api/providers/__tests__/openai.spec.ts @@ -609,6 +609,29 @@ describe("OpenAiHandler", () => { expect(callArgs).not.toHaveProperty("temperature") }) + // PR 2650 round 5 (CodeRabbit comment 4801992024): the omission above also + // holds without the resolveTemperature guard when no custom value is set, so + // that test cannot detect guard removal. A custom value with supportsTemperature + // false must still be dropped by the guard on both stream branches. + it.each([true, false])( + "should omit a custom temperature when supportsTemperature is false (streaming: %s)", + async (openAiStreamingEnabled) => { + const guardedHandler = new OpenAiHandler({ + ...mockOptions, + openAiStreamingEnabled, + modelTemperature: 0.7, + openAiCustomModelInfo: { + contextWindow: 128_000, + supportsPromptCache: false, + supportsTemperature: false, + }, + }) + await collectStream(guardedHandler.createMessage(systemPrompt, messages)) + expect(mockCreate).toHaveBeenCalled() + expect("temperature" in mockCreate.mock.calls[0][0]).toBe(false) + }, + ) + it("should omit temperature by default when no custom temperature is set", async () => { // Option A: when "use custom temperature" is off (modelTemperature unset) and the model has no // required default, omit `temperature` so the server's own default applies instead of forcing 0.