diff --git a/changelog.d/reasoning-effort-every-value.md b/changelog.d/reasoning-effort-every-value.md new file mode 100644 index 0000000000..af5cbd1f1b --- /dev/null +++ b/changelog.d/reasoning-effort-every-value.md @@ -0,0 +1,7 @@ +### Every model that reasons takes every reasoning effort a client sends + +- `reasoning_effort` and `reasoning.effort` take `none`, `minimal`, `low`, `medium`, `high`, `xhigh` and `max` on every model that reasons, on one Mac, on a pair and through the coordinator. Each becomes the model's nearest level, the higher one between two: `minimal` its lowest, `max` its highest, `none` thinking off where the model can. +- Qwen 3.8 27B (and the owned Flash-Next build) answered `high` and `max` with a 400 "Invalid inference request.", so Hermes, which sends the user's `max`, fell back to the user's other, paid provider. They now render `xhigh`, the template's highest level, and `minimal` renders `low`. +- MiMo V2.6 thinks for every effort but `none` (it refused them all), Nemotron 3.5 Super renders `minimal` and `low` at its medium depth and `xhigh` and `max` at its default (it refused them), and DiffusionGemma and Flint take `max`. +- An effort that is none of the names is refused on every model that reasons, also on Qwen 3.5 and 3.6, Bonsai 2, Gemma 4, GPT-OSS and Nemotron 3.5 Lightning, which rendered it. The local API answers 400 with code `invalid_reasoning_effort`, the field in `param`, and the accepted names. A model that doesn't reason ignores any effort. +- Nemotron 3.5 Super reads both `reasoning_effort` and `reasoning.effort`, and refuses two that differ, even two names such as `high` and `max`. Its local API now answers that with the same 400 as an unknown name (code `invalid_reasoning_effort`, `param` naming both fields, and the accepted names), where it gave an untyped "Invalid inference request." Send one of them, or the same effort in both. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index c20a0aa884..3802034a80 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -2737,7 +2737,7 @@ spends the caller's `max_tokens` before any JSON is written. A nested `reasoning.enabled`, a raw `enable_thinking` or `chat_template_kwargs` switch, any reasoning effort, or a positive `reasoning.max_tokens` budget keeps the caller's choice. The family predicate also matches Qwen3.8 -Flash-Next by model ID; `Qwen4SupportPolicy.validateReasoningContext` accepts +Flash-Next by model ID, whose template takes the closed block. Other families keep their thinking defaults because the predicate excludes them; GLM5-Next, MiMo and Nemotron Super also build their own template context, and Flint's template ignores the switch. @@ -2961,14 +2961,75 @@ and the coordinator can refuse to route A template `raise_exception` at request time is classified `jinja_template` and returned as HTTP 500, the provider-fault class, so a caller control that -a template is known to reject must be validated before rendering. The -Flash-Next and Qwen3.8-27B templates accept only `low`, `medium` and `xhigh` -while thinking is enabled; any other active effort, such as OpenAI's `high` -or `minimal`, is a typed HTTP 400 `client_error` and never reaches Jinja, on -text and media requests alike -(`provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift`, -`validateReasoningContext`). Media preparation rethrows such typed request -errors instead of wrapping them as a retryable 503 construction refusal. +a template is known to reject must be resolved before rendering. The +Flash-Next and Qwen3.8-27B templates raise for any effort but `low`, `medium` +and `xhigh` while thinking; they receive one of those for every effort a +client sends ([reasoning effort](#reasoning-effort)), on text and media +requests alike. Media preparation rethrows typed request errors instead of +wrapping them as a retryable 503 construction refusal. + +### Reasoning effort + +Every model that reasons takes each effort a client names (`none`, +`minimal`, `low`, `medium`, `high`, `xhigh`, `max`) as `reasoning_effort` or +`reasoning.effort`; Responses' `reasoning.effort` arrives as the latter, which +wins over the top-level spelling (Nemotron 3.5 Super reads both, below). Its +template receives one of the model's own levels: its own where the model has +it, else the next one up (an effort between two levels rounds up, toward more +reasoning), and the highest past them all. So `minimal` selects the lowest +level and `max` the highest. `none` (also `off` or `0`) switches thinking off +where the model can, and selects the lowest level where it can't. Spellings +are trimmed and read in any case, +except by GLM-5.3-Flash and Flint, which read the names exactly as written. +Each family's table of the seven efforts is in one place, +`provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift`, +and `ReasoningEffortValuesTests` checks every row against this rule. One Mac, +a pair's leader (tensor parallel and pipeline) and the coordinator path render +through the same prompt pipeline; the local router returns this Mac's answer +as it is, or passes the request's body on unchanged. + +| Family | Its levels | What each effort renders | Source | +|---|---|---|---| +| The Qwen 3.5 template family (`qwen3_5`, `qwen3_5_moe`, `prism_hadamard_qwen35`: Qwen 3.5, 3.6 and 3.8, Bonsai 2) and the owned Qwen 3.8 Flash-Next build | Qwen 3.8's `low`, `medium` and `xhigh` (its default), and a thinking switch | While thinking: `minimal` and `low` render `low`, `medium` renders `medium`, `high`, `xhigh` and `max` render `xhigh`, as the coordinator's first-party pool sends `high`. Thinking off: the effort as sent, which the template ignores. The 3.5, 3.6 and Bonsai templates read only the switch | `ReasoningEffort.qwen38Level`, `ReasoningEffortPolicy.templateEffort`, `Qwen4SupportPolicy.ownsEffortTemplate` | +| GLM-5.3-Flash | `low`, `high` and `max` (its default); thinking off closes `` | `minimal` and `low` render `low`, `medium` and `high` render `high`, `xhigh` and `max` render `max`, as the platform sidecar maps them | `ReasoningEffort.glmLevel` (`GLM5NextPromptPolicy`) | +| Nemotron 3.5 Super | `medium_effort`, and the template's default depth | `minimal`, `low` and `medium` set `medium_effort`; `high`, `xhigh` and `max` keep the default | `ReasoningEffort.nemotronSuperMediumEffort` (`NemotronSuperPromptContract.controls(body:)`) | +| MiMo V2.6, DiffusionGemma | one depth, and a thinking switch | Every effort but `none` thinks | `ReasoningEffort.oneDepthThinking` (`MiMoV26TemplateFix`, `DiffusionGemmaReasoningControl`) | +| Gemma 4, Nemotron 3.5 Lightning | a thinking switch | `none` switches thinking off; any other effort keeps the template's default (Gemma 4: off) | `MultiModelBatchSchedulerEngine.templateAdditionalContext` | +| GPT-OSS | Harmony's `low`, `medium` and `high` | The effort as sent, except `high`, which renders `medium` | `GPTOSSHarmonyTemplateFix.effectiveReasoningEffort` | +| Flint | none: Flint decides whether to reason | Every effort is taken, with no effect | `FlintRequestPolicy` | + +An effort that is none of the names is refused on any model that reasons, +with `MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(field)` +(HTTP 400), before the prompt renders or any KV is reserved. The engine +checks the effort once the request holds its model +(`MultiModelBatchSchedulerEngine.prepareCompletion`, after +`acquireForCompletion`; Super's owner in `NemotronSuperRequestPlan`), so a +cold model may load first, and on one Mac's unified endpoint the request +counts as the owner's use for "me first". The refusal releases the model. +MiMo's and Flint's efforts are checked before that when the model is +resident, and through the coordinator MiMo's, Flint's and GLM-5.3-Flash's are +refused before the request is accepted +(`ProviderPromptContractPipeline.nativeControlsRefusal`). The local API +answers `invalid_reasoning_effort` naming the field and the names ([direct +mode](../provider/direct-mode.md#reasoning-effort)); the coordinator receives +the closed `invalid_request` failure, which it shows as "invalid inference +request". A model of no family above ignores any effort +(`ReasoningEffortPolicy.validate`). + +Nemotron 3.5 Super reads both fields rather than letting `reasoning.effort` +win, and refuses two that differ, even two names such as `high` and `max`, +with `conflictingReasoningEfforts` (HTTP 400) at the same point +(`NemotronSuperPromptContract.controls(body:)`). The local API answers it in +the same shape: code `invalid_reasoning_effort`, `param` naming both fields +(`"reasoning_effort, reasoning.effort"`), and a message naming both fields and +the names, never the values sent. Through the coordinator it is the same +closed `invalid_request`. The same effort in both fields, in any spelling, is +served. + +Gemma 4 and GPT-OSS keep the prompts they rendered before: the coordinator's +prompt sidecar plans those prompts for cache-aware routing, so changing one +needs the sidecar's matching change and a new normalization version. + ### Vision constraints @@ -3806,7 +3867,8 @@ evidence, not a change to the normal final-row contract or the near-tie rule | Request cancelled by lease | No admission/prefill/decode progress within 120 s, or a step over 30 s. On the local API this comes after the response head, so a queued request that waits out the admission lease ends a streamed answer with an error event (as does a paged pool that stays full through its requeues) | `EngineLoopV2.swift`; `EngineV2Bridge+Events.swift` | | `promptExceedsContext` (400) | The prompt alone fills the slot's window (its advertised context, else its model's); a larger output is cut, never refused | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift` (`submitTokenized`) | | `advertisedContextExceeded` (400) | Candidate output reservation is negative or overflows; with the output cut to the window, nothing larger reaches it on one Mac | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift` (`submitTokenized`); `provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift` (`sanitizedInferenceFailure`) | -| `unsupportedReasoningEffort` (400) | Active effort outside `low`/`medium`/`xhigh` on a restricted-effort template (Flash-Next, Qwen3.8-27B) | `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift` (`validateReasoningContext`) | +| `unsupportedReasoningEffort` (400; on the local API `invalid_reasoning_effort`) | A model that reasons received an effort that is none of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` ([reasoning effort](#reasoning-effort)) | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift` (`ReasoningEffortPolicy.validate`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) | +| `conflictingReasoningEfforts` (400; on the local API `invalid_reasoning_effort`, `param` naming both fields) | Nemotron 3.5 Super received `reasoning_effort` and `reasoning.effort` that differ ([reasoning effort](#reasoning-effort)) | `provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift` (`controls(body:)`); `provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift` (`SuperHTTPErrors.map`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) | | Model dropped from advertised set | Unsupported `model_type` | `EngineV2SupportedModels.swift` | | Model advertised, capacity quotes rejected with reason `template` | Scan-time render check failed (`template_render_ok = false`) | `TemplateRenderCheck.swift`, `provider-swift/Sources/ProviderCore/Coordinator/CapacityQuoteEngine.swift` (`reject(.template)`) | | Image rejected | Over `MediaIngest` caps or over the N² tower budget | `MediaIngest.swift`, `VisionTowerBudget.swift` | @@ -3909,9 +3971,11 @@ Flint always decides for itself whether to reason; it has no trained switch, effort level or budget, and its pinned template reads none of these controls ([Recursive's serving guide](https://github.com/RecursiveSI/flint/blob/2a247be0c0aec895ccb0ac7ca92229ec6df37288/sglang/README.md)). `FlintRequestPolicy` accepts `reasoning_effort` and `reasoning.effort` (none, -minimal, low, medium, high or xhigh), `reasoning.enabled`, `enable_thinking` -and `chat_template_kwargs.enable_thinking`/`thinking` with no effect on the -prompt. Malformed values, unknown efforts, `preserve_thinking`, other reasoning +minimal, low, medium, high, xhigh or max, exactly as written), +`reasoning.enabled`, `enable_thinking` and +`chat_template_kwargs.enable_thinking`/`thinking` with no effect on the +prompt. Malformed values, unknown efforts (`invalid_reasoning_effort`), +`preserve_thinking`, other reasoning keys and media are refused. When a request sets `reasoning.exclude` true, `include_reasoning` false or `reasoning.enabled` false, `NativeToolStreamRouter` withholds the generated reasoning, so chat completions, the Responses API and diff --git a/docs/developer/test.md b/docs/developer/test.md index 096343a263..b5f463db13 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test Provider And Native Contracts -> Last updated: 2026-11-07 +> Last updated: 2026-11-08 Run isolated Swift, native-resource, public-fixture and landing tests here. Backend integration and cross-implementation qualification are platform-owned. @@ -1306,6 +1306,23 @@ SHA-256 in the commit. A provider change to the rendered prompt, such as the Qwen JSON `response_format` thinking default, lands with the regenerated vectors and must pass `scripts/verify-prompt-parity.sh` before review. +`fixtures/prompt-contract/v1/native_reasoning_vectors.json` (28 cases) is this +repository's: the template context the provider gives each reasoning control, +or its refusal. `CachePromptParityTests` checks the provider against it, and +the platform's prompt sidecar and first-party pool read the same cases, so a +change lands here first and the platform follows. Since the reasoning-effort +levels ([reasoning effort](../architecture/inference.md#reasoning-effort)), +Qwen 3.8 Flash-Next's `high`, `max`, `minimal` and ` low ` render a level and +`turbo` is refused. `ReasoningEffortValuesTests` checks every family's table +against the rounding rule and sends every effort to every family through the +production prompt pipeline, and +`ReasoningEffortLocalAPITests` sends them to one Mac's local API and a pair +leader's over the `ClusterAPIParityTests` harness. It also renders Nemotron 3.5 +Super's refusal of two efforts that differ through `SuperHTTPErrors` and +`CORSResponder`; `NemotronSuperLocalHTTPTests`' live text route sends it, and +an unknown `reasoning.effort`, through the real application (it needs Metal, +so it runs in CI). + darkbloom-platform keeps byte-identical copies of the provider's `paged_footprint_wire.json` and `process_memory_wire.json` for its own coordinator and console tests. Coordinate fixture changes with the platform and diff --git a/docs/provider/direct-mode.md b/docs/provider/direct-mode.md index f23ecb56c7..a6ce654771 100644 --- a/docs/provider/direct-mode.md +++ b/docs/provider/direct-mode.md @@ -487,6 +487,28 @@ headers: while the model loads for it, while it waits for a pair's lane, and while its prompt is tokenized. A client that limits how long it waits for headers must allow a cold model load. +### Reasoning effort + +Every model this Mac serves that reasons takes each effort your tool sends, +as `reasoning_effort` or `reasoning: {"effort": …}` (Responses: +`reasoning.effort`): `none`, `minimal`, `low`, `medium`, `high`, `xhigh` or +`max`. The model gets the nearest of its own levels, the higher one between +two; `minimal` is its lowest and `max` its highest; `none` switches thinking +off where it can. So Hermes's `max` and an OpenAI client's `high` on Qwen 3.8 +27B reach its template as `xhigh`, its highest level. One Mac, a pair and the +[local router](#when-this-mac-cant-take-a-request-the-local-router) answer +alike. Each family's levels are in +[reasoning effort](../architecture/inference.md#reasoning-effort). A model +that doesn't reason ignores the effort. Send the effort in one field: +`reasoning.effort` wins over `reasoning_effort`, and Nemotron 3.5 Super, which +reads both, refuses two that differ. + +```bash +curl -s "$OPENAI_BASE_URL/chat/completions" \ + -H "Authorization: Bearer $OPENAI_API_KEY" -H "Content-Type: application/json" \ + -d '{"model":"EigenLabs/Qwen3.8-27B-4bit-mtp","reasoning_effort":"max","messages":[{"role":"user","content":"hi"}]}' +``` + ### Refused request shapes The chat routes and Responses input answer these shapes with an OpenAI error @@ -497,6 +519,8 @@ envelope, the same on one Mac and on a [two-Mac cluster](./two-mac-cluster.md): | On one Mac, a prompt that fills the model's context window: the context it advertises (GLM-5.3-Flash and Nemotron Super: 262,144; MiMo V2.6, Qwen4, Flint, Bonsai 9B and Diffusion Gemma: their configs'), else its model's own (Gemma 4, Qwen 3.5, 3.6 and 3.8, GPT-OSS, Nemotron Lightning) | HTTP `400`, code `context_length_exceeded`, before the engine and before any SSE header: `The prompt fills this model's context window of tokens, leaving no room for an answer. Shorten the prompt or start a new conversation.` A `max_tokens` beyond what a shorter prompt leaves is cut to it instead, on every model, and the answer ends with `finish_reason: length` if it gets there | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Translation.swift` (`outputTokens(requested:promptTokens:)`, `promptExceedsContextMessage`) | | On one Mac, a request its memory can't hold now: the shared KV reservation of a contiguous slot, the engine's own admission of a paged slot (the automatic backend; it refuses one that can never fit and queues the rest), or the whole Mac's request limit | HTTP `503` before any SSE header, streamed or not: `This Mac's memory can't hold this request right now. Lower max_tokens or shorten the prompt (or send less media), or retry when this Mac's other requests finish.` The local router passes it on when a route dials out. A request a paged slot queued and then couldn't admit (the 120 s admission lease, or the pool full through its requeues) fails later: a streamed answer, whose head is already sent, ends with an error event, and a non-streamed one gets 503 (after the lease, with the older `Provider capacity is temporarily unavailable.`) | `provider-swift/Sources/ProviderCore/Inference/Engine/Bridge/EngineV2Bridge+Submission.swift` (`submitTokenized`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) | | A content part whose `type` is none of `text`, `input_text`, `output_text`, `image_url`, `input_image`, `video_url`, `input_audio` (for example `input_file`, `input_video`, `refusal`) | HTTP `400` before model acquisition or SSE headers: `Content part type "" is not supported. Send text, image_url, video_url or input_audio parts.` The type is shown with at most 64 of its letters, digits and `_.-:/`. Models without native audio still refuse `input_audio` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/OpenAIRequestValidation.swift` (`OpenAIRequestValidationError.unsupportedContentPart`) | +| A reasoning effort that is none of `none`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` (for example `turbo`), on a model that reasons | HTTP `400` before the prompt renders or any KV is reserved, code `invalid_reasoning_effort`, `param` the field it came in (`reasoning_effort`, `reasoning.effort`, or GLM-5.3-Flash's `chat_template_kwargs.reasoning_effort`): `reasoning_effort must be one of: none, minimal, low, medium, high, xhigh, max.` The request may hold its model first: a cold model loads, and with Both, me first it counts as your use of the Mac. Through the coordinator the same request gets HTTP `400` `invalid inference request` | `provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift` (`ReasoningEffortPolicy.validate`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) | +| On Nemotron 3.5 Super, `reasoning_effort` and `reasoning.effort` that differ, even two names (`high` and `max`). The same effort in both, in any spelling, is served | HTTP `400` at the same point, code `invalid_reasoning_effort`, `param` `reasoning_effort, reasoning.effort`: `reasoning_effort and reasoning.effort must be the same when both are sent, one of: none, minimal, low, medium, high, xhigh, max.` Through the coordinator, HTTP `400` `invalid inference request` | `provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift` (`controls(body:)`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`) | | `response_format` `json_object`/`json_schema` whose answer stopped at `max_tokens` before it was complete (a reasoning model can spend the whole budget thinking) | HTTP `422`: `The output was cut off by max_tokens before the structured (response_format) answer was complete. Raise max_tokens or lower the reasoning effort, and retry.` Invalid JSON at a natural stop keeps its `422` with the closed internal-failure message. GLM-5.3-Flash validates its withheld JSON answer itself (`GLM5NextResponseFormat`) and answers a truncated one with that closed `422` | `libs/mlx-swift-lm/Libraries/MLXLMServer/Runtime/MLXOpenAIService.swift` (`MLXOpenAIServiceError.responseFormatCutOffByMaxTokens`); `provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift` (`CORSResponder`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextResponseFormat.swift` (`validatedContent`) | | GLM-5.3-Flash with images or video and `response_format` `json_object`/`json_schema` or a required or named `tool_choice` | HTTP `400` `Invalid inference request.` (failure code `invalid_request`) before any media decode: only the text path withholds and validates such an answer or call. Hidden reasoning (`reasoning.exclude: true`, `include_reasoning: false`, `thinking.display: "omitted"`) is served with media too, its reasoning withheld | `provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift` (`prepareCompletion`); `provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift` (`withholdsOutput`, `withholdsReasoning`) | | An image or video the model's processor refuses: for Qwen 3.5 and 3.8 a side below `patch_size × merge_size` (32 pixels) or an aspect ratio above 200:1, which it does not upscale; a video without a decodable track; more images or videos than the processor takes | HTTP `400` `Invalid media input.` (failure code `invalid_media`), before the vision tower or any native reservation, never the retryable `503` | `provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2VisionPrefill.swift` (`clientFault(for:)`) | diff --git a/docs/reference/qwen4-next-support.md b/docs/reference/qwen4-next-support.md index de26d75e88..fb168be88c 100644 --- a/docs/reference/qwen4-next-support.md +++ b/docs/reference/qwen4-next-support.md @@ -1,6 +1,6 @@ # Qwen 3.8 Next (Flash-Next) native support reference -> Last updated: 2026-10-20 +> Last updated: 2026-11-08 Reference for the native Qwen4 support candidate and its remaining qualification gates. These source defaults do not publish a model, approve a catalog entry, qualify a hardware tier or establish a production release. The composed SDK's `libs/mlx-swift-lm/docs/qwen4/composition.md` records source selection and excluded experiments. @@ -69,18 +69,23 @@ Boundary/policy unit tests do not certify a 262K workload on 128 GiB hardware. The SDK pin, weights, quantization, embedded MTP and native arithmetic are unchanged by this policy update. -The owned artifact supports reasoning ON with its default `xhigh`, or explicit -`low`, `medium`, `xhigh`. Chat supports `reasoning.enabled=false`; Chat and -Responses both support `reasoning.effort=none`. The local Responses schema -does not model `reasoning.enabled`; do not substitute that extension for its -supported OFF form. Existing Chat Boolean precedence is preserved. -Unsupported active efforts such as `high` or `minimal` are rejected before -template rendering with a typed HTTP 400, not coerced to another effort. -Disabled thinking retains its existing precedence. Every concrete +The owned artifact's template renders reasoning ON at its default `xhigh`, or +`low`, `medium`, `xhigh`, and raises for any other effort while thinking. +Every effort a client sends reaches it as one of those: `minimal` renders +`low`, and `high` and `max` render `xhigh` +([reasoning effort](../architecture/inference.md#reasoning-effort)). Chat +supports `reasoning.enabled=false`; Chat and Responses both support +`reasoning.effort=none`. The local Responses schema does not model +`reasoning.enabled`; do not substitute that extension for its supported OFF +form. Existing Chat Boolean precedence is preserved, and disabled thinking +retains its existing precedence. An effort that is none of the names is +refused before template rendering with a typed HTTP 400. Every concrete Qwen3.8-27B build (`ModelRuntimeRequirements.qwen38ConcreteModelIDs`) ships a -template with the same effort raise, so it shares this boundary; other -artifact templates are unaffected. Source: `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift` -(`validateReasoningContext`) and `provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift` +template with the same effort levels, and so does the Qwen 3.5 template family; +another Qwen4 artifact's effort goes to its template as sent. Source: +`provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift` +(`ReasoningEffortPolicy`), `provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift` +(`ownsEffortTemplate`) and `provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift` (`tokenize`). Hosted OpenRouter routing, adapter control mappings, exclusion, reasoning-token budgets and opaque reasoning-history extensions require separate qualification; localhost success does not establish them. diff --git a/fixtures/prompt-contract/v1/native_reasoning_vectors.json b/fixtures/prompt-contract/v1/native_reasoning_vectors.json index 0fe640fa17..5226a545a8 100644 --- a/fixtures/prompt-contract/v1/native_reasoning_vectors.json +++ b/fixtures/prompt-contract/v1/native_reasoning_vectors.json @@ -405,7 +405,7 @@ } }, { - "name": "native-high-rejected", + "name": "native-high-renders-xhigh", "model_type": "qwen4_exp", "request": { "model": "DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", @@ -431,10 +431,12 @@ "effort": "high" } }, - "error": true + "additional_context": { + "reasoning_effort": "xhigh" + } }, { - "name": "native-minimal-rejected", + "name": "native-minimal-renders-low", "model_type": "qwen4_exp", "request": { "model": "DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", @@ -460,7 +462,9 @@ "effort": "minimal" } }, - "error": true + "additional_context": { + "reasoning_effort": "low" + } }, { "name": "native-enabled-false-precedence", @@ -645,7 +649,7 @@ "error": true }, { - "name": "native-effort-space-rejected", + "name": "native-effort-space-renders-low", "model_type": "qwen4_exp", "request": { "model": "DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", @@ -671,8 +675,87 @@ "effort": " low " } }, + "additional_context": { + "reasoning_effort": "low" + } + }, + { + "name": "native-max-renders-xhigh", + "model_type": "qwen4_exp", + "request": { + "model": "DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", + "messages": [ + { + "role": "user", + "content": "Please call weather." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "weather", + "parameters": { + "type": "object", + "properties": {} + } + } + } + ], + "reasoning": { + "effort": "max" + } + }, + "additional_context": { + "reasoning_effort": "xhigh" + } + }, + { + "name": "native-unknown-effort-rejected", + "model_type": "qwen4_exp", + "request": { + "model": "DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", + "messages": [ + { + "role": "user", + "content": "Please call weather." + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "weather", + "parameters": { + "type": "object", + "properties": {} + } + } + } + ], + "reasoning": { + "effort": "turbo" + } + }, "error": true }, + { + "name": "qwen38-raw-max-renders-xhigh", + "model_type": "qwen3_5", + "request": { + "model": "EigenLabs/Qwen3.8-27B-4bit-mtp", + "messages": [ + { + "role": "user", + "content": "Please call weather." + } + ], + "reasoning_effort": "max" + }, + "additional_context": { + "reasoning_effort": "xhigh" + } + }, { "name": "null-tool-choice-is-auto", "model_type": "qwen4_exp", diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceRefusalReason.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceRefusalReason.swift index 8f8837257d..2f3d712b27 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceRefusalReason.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/InferenceRefusalReason.swift @@ -48,7 +48,8 @@ public enum InferenceRefusalReason: String, CaseIterable, Sendable, Equatable { switch engineError { case .invalidToolPayload(_, let refusal?): self = refusal case .invalidRole: self = .unsupportedMessageRole - case .unsupportedReasoningEffort, .unsupportedNativeReasoningEffort: self = .unsupportedReasoningControl + case .unsupportedReasoningEffort: self = .unsupportedReasoningControl + case .conflictingReasoningEfforts: self = .contradictoryReasoningControls case .advertisedContextExceeded, .promptExceedsContext: self = .requestExceedsContext case .unsupportedOutputControl: self = .unsupportedOutputControl default: return nil diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift index 3b0db32283..a62a66f0e3 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine+Translation.swift @@ -82,11 +82,7 @@ public struct ChatTemplateControls: Sendable, Equatable { } var effortDisablesThinking: Bool { - guard let value = reasoningEffort? - .trimmingCharacters(in: .whitespacesAndNewlines) - .lowercased() - else { return false } - return ["none", "off", "0"].contains(value) + reasoningEffort.map(ReasoningEffort.switchesThinkingOff) ?? false } var hasExplicitThinkingControl: Bool { @@ -114,18 +110,11 @@ extension MultiModelBatchSchedulerEngine { let fixContext = ChatTemplateFixContext( modelId: request.model, modelType: modelType) - if let effectiveEffort = GPTOSSHarmonyTemplateFix.effectiveReasoningEffort( - effort, - context: fixContext) - { - context["reasoning_effort"] = effectiveEffort - } // Reviewed precedence: the typed nested control wins over both raw-body - // aliases; explicit booleans win over effort shorthands; only the exact - // none/off/0 spellings disable through reasoning_effort. `minimal` is - // preserved as an effort value and intentionally is not rewritten to - // false. + // aliases; explicit booleans win over effort shorthands; only the + // none/off/0 spellings disable through reasoning_effort. `minimal` + // reasons, at the model's lowest level, and is not rewritten to false. if requiresToolCall && Qwen35TemplateFix.applies(to: fixContext) && !ToolChoiceEnforcementPolicy.nativeStructuredTarget(fixContext) { @@ -162,6 +151,10 @@ extension MultiModelBatchSchedulerEngine { // mirrors this rule. context["enable_thinking"] = false } + if let effort { + context["reasoning_effort"] = ReasoningEffortPolicy.templateEffort( + effort, modelID: request.model, modelType: modelType, thinking: context["enable_thinking"] as? Bool) + } if let preserveThinking = controls.preserveThinking { context["preserve_thinking"] = preserveThinking } diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift index 5c8e3408a1..50cccf98c7 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngine.swift @@ -509,8 +509,7 @@ public struct MultiModelBatchSchedulerEngine: MLXServerEngine, Sendable { nativeMiMoThinkingEnabled = try MiMoV26TemplateFix.effectiveThinkingEnabled( request: request, controls: templateControls) } else { nativeMiMoThinkingEnabled = true } - try DiffusionGemmaReasoningControl.validate( - request: request, controls: templateControls, modelType: modelType) + try ReasoningEffortPolicy.validate(request, controls: templateControls, modelType: modelType) prepared = try ToolChoicePromptPolicy.prepare( request, modelType: modelType, diff --git a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngineError.swift b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngineError.swift index bc7c412fdd..30f901ca0b 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngineError.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Engine/Scheduler/MultiModelBatchSchedulerEngineError.swift @@ -40,12 +40,16 @@ public enum MultiModelBatchSchedulerEngineError: Error, LocalizedError, Equatabl /// 500s. `refusal` names the closed reason `darkbloom logs` shows; the /// message never reaches a log or the wire. case invalidToolPayload(String, refusal: InferenceRefusalReason? = nil) - /// The owned native Flash-Next or Qwen3.8-27B template does not support - /// the resolved thinking effort. Deterministic request error, before - /// template rendering. - case unsupportedReasoningEffort - /// Native binary-thinking model received an unknown effort alias. - case unsupportedNativeReasoningEffort + /// A model that reasons received an effort that is none of the seven + /// names (`ReasoningEffort`), in `field`. Deterministic request error, + /// before template rendering; the message names only the field and the + /// accepted names, so a client may be shown it. + case unsupportedReasoningEffort(ReasoningEffortField) + /// Nemotron 3.5 Super received `reasoning_effort` and `reasoning.effort` + /// that differ: it reads both and doesn't choose one. Deterministic + /// request error, before template rendering; the message names only the + /// two fields and the accepted names, so a client may be shown it. + case conflictingReasoningEfforts /// The MODEL failed to satisfy the request's forced `tool_choice` /// contract, or the inference-time grammar reached an impossible state. /// This depends on what the model GENERATED — @@ -133,10 +137,10 @@ public enum MultiModelBatchSchedulerEngineError: Error, LocalizedError, Equatabl return "Unsupported chat message role: '\(role)'" case .invalidToolPayload(let message, _): return message - case .unsupportedReasoningEffort: - return "This model supports reasoning effort low, medium, or xhigh when thinking is enabled" - case .unsupportedNativeReasoningEffort: - return "DiffusionGemma supports binary reasoning: none/off/0 or minimal/low/medium/high/xhigh" + case .unsupportedReasoningEffort(let field): + return field.refusalMessage + case .conflictingReasoningEfforts: + return ReasoningEffortField.conflictMessage case .toolChoiceViolation(let message): return message case .tokenBudgetExhausted(let message): diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/DiffusionGemmaReasoningControl.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/DiffusionGemmaReasoningControl.swift index 57a10cc3ba..88fcfe6d42 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/DiffusionGemmaReasoningControl.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/DiffusionGemmaReasoningControl.swift @@ -13,24 +13,9 @@ enum DiffusionGemmaReasoningControl { ?? enabled(for: request.reasoning?.effort ?? controls.reasoningEffort) ?? false } + /// Every effort but `none` thinks (`ReasoningEffort.oneDepthThinking`); nil + /// names no effort (`ReasoningEffortPolicy.validate` refuses it). static func enabled(for effort: String?) -> Bool? { - guard let effort else { return nil } - switch effort.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { - case "none", "off", "0": return false - case "minimal", "low", "medium", "high", "xhigh": return true - default: return nil - } - } - - static func validate(request: OpenAIChatCompletionRequest, - controls: ChatTemplateControls, modelType: String?) throws - { - guard modelType == "diffusion_gemma", - request.reasoning?.enabled == nil, controls.enableThinking == nil, - let effort = request.reasoning?.effort ?? controls.reasoningEffort - else { return } - guard enabled(for: effort) != nil else { - throw MultiModelBatchSchedulerEngineError.unsupportedNativeReasoningEffort - } + effort.flatMap(ReasoningEffort.init(clientValue:))?.oneDepthThinking } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/FlintRequestPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/FlintRequestPolicy.swift index 06b2d67d51..848d2041ab 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/FlintRequestPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/FlintRequestPolicy.swift @@ -7,8 +7,9 @@ import MLXLMServer /// caller's choice not to receive reasoning is honored, by withholding the /// reasoning Flint still generates. Output length is not a reasoning effort. enum FlintRequestPolicy { - /// OpenRouter's reasoning effort names. - static let acceptedEfforts: Set = ["none", "minimal", "low", "medium", "high", "xhigh"] + /// Each of the seven effort names, exactly as written (`ReasoningEffort`): + /// taken, with no effect on the prompt. + static func acceptsEffort(_ effort: String) -> Bool { ReasoningEffort(rawValue: effort) != nil } /// Request-local evidence from the original body, captured before the /// permissive extension decoder and the typed request drop wrong-typed or @@ -17,6 +18,8 @@ enum FlintRequestPolicy { struct RawControls: Sendable, Equatable, Decodable { /// A malformed value, unknown effort or unsupported reasoning key. var invalid = false + /// The field of an effort that is none of the names. + var unknownEffort: ReasoningEffortField? /// `reasoning.exclude` true, `include_reasoning` false or /// `reasoning.enabled` false. var withholdsReasoning = false @@ -42,14 +45,17 @@ enum FlintRequestPolicy { guard values.contains(Key(name)) else { return nil } return try values.decode(Bool.self, forKey: Key(name)) // No numeric truthiness. } - func effort(_ values: KeyedDecodingContainer, _ name: String) throws { + func effort(_ values: KeyedDecodingContainer, _ name: String, + _ field: ReasoningEffortField) throws { guard values.contains(Key(name)) else { return } - let value = try values.decode(String.self, forKey: Key(name)) - guard FlintRequestPolicy.acceptedEfforts.contains(value) else { throw Malformed() } + guard FlintRequestPolicy.acceptsEffort(try values.decode(String.self, forKey: Key(name))) else { + result.unknownEffort = field + throw Malformed() + } } if root.contains(Key("preserve_thinking")) { result.invalid = true } _ = try boolean(root, "enable_thinking") - try effort(root, "reasoning_effort") + try effort(root, "reasoning_effort", .reasoningEffort) if try boolean(root, "include_reasoning") == false { result.withholdsReasoning = true } if root.contains(Key("chat_template_kwargs")) { let kwargs = try root.nestedContainer(keyedBy: Key.self, forKey: Key("chat_template_kwargs")) @@ -64,7 +70,7 @@ enum FlintRequestPolicy { if reasoning.allKeys.contains(where: { !["effort", "enabled", "exclude"].contains($0.stringValue) }) { result.invalid = true } - try effort(reasoning, "effort") + try effort(reasoning, "effort", .reasoningObject) if try boolean(reasoning, "enabled") == false { result.withholdsReasoning = true } if try boolean(reasoning, "exclude") == true { result.withholdsReasoning = true } } @@ -79,12 +85,15 @@ enum FlintRequestPolicy { guard modelType == "flint" else { return } // Raw evidence is authoritative; the typed fields cover programmatic // controls. The media-only evidence bit is unrelated. - guard !controls.rawFlintControls.invalid, controls.preserveThinking == nil, - controls.reasoningEffort.map(acceptedEfforts.contains) ?? true - else { + if let field = controls.rawFlintControls.unknownEffort { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(field) + } + if let effort = controls.reasoningEffort, !acceptsEffort(effort) { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort) + } + guard !controls.rawFlintControls.invalid, controls.preserveThinking == nil else { throw MultiModelBatchSchedulerEngineError.invalidToolPayload( - "Flint reasoning controls require an effort of none, minimal, low, medium, high or xhigh and Boolean switches" - ) + "Flint reasoning controls require Boolean switches and known reasoning keys") } } @@ -93,9 +102,8 @@ enum FlintRequestPolicy { ) throws { guard modelType == "flint" else { return } try validateControls(controls, modelType: modelType) - if let effort = request.reasoning?.effort, !acceptedEfforts.contains(effort) { - throw MultiModelBatchSchedulerEngineError.invalidToolPayload( - "Flint reasoning effort must be none, minimal, low, medium, high or xhigh") + if let effort = request.reasoning?.effort, !acceptsEffort(effort) { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject) } if MediaIngest.hasMedia(request) { throw MultiModelBatchSchedulerEngineError.mediaUnsupportedByModel(request.model) diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift index 121aebb3c5..f61785c529 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/GLM5NextPromptPolicy.swift @@ -50,23 +50,11 @@ enum GLM5NextPromptPolicy { private static let contradictoryThinking = "thinking-off cannot be combined with a thinking-on switch, effort level or reasoning budget" - /// The template renders low, high or max. The other OpenAI effort names map - /// to the nearest of those, matching the platform prompt sidecar. `none` - /// and `off` turn thinking off; other unknown values are refused. + /// The levels the template renders (`max` is its default); an effort's + /// level is its row of `ReasoningEffort.glmLevel`. enum Effort: String, Sendable, Equatable { case low, high, max - static let disablingRequests: Set = ["none", "off"] - - init?(requested: String) { - switch requested { - case "minimal", "low": self = .low - case "medium", "high": self = .high - case "xhigh", "max": self = .max - default: return nil - } - } - /// A `reasoning.max_tokens` budget selects the nearest level using the /// budgets OpenAI-compatible APIs conventionally give `low` (1,024) and /// `medium` (8,192). The template cannot enforce a token budget. @@ -75,6 +63,12 @@ enum GLM5NextPromptPolicy { } } + /// The effort a request names, read exactly as written, with `off` for + /// `none`; nil for any other value or spelling, which is refused. + private static func namedEffort(_ requested: String) -> ReasoningEffort? { + requested == "off" ? ReasoningEffort.none : ReasoningEffort(rawValue: requested) + } + /// Request-local original declarations survive the legacy model-blind /// decoder. They are used only after provider-owned metadata selects GLM; /// never publish them in diagnostics, telemetry, or a model advertisement. @@ -83,6 +77,9 @@ enum GLM5NextPromptPolicy { /// The first refused member; such controls never validate. private(set) var invalidReason: InferenceRefusalReason? var invalid: Bool { invalidReason != nil } + /// The field of an effort that is none of the names, when it is the + /// first refused member. + private(set) var unknownEffort: ReasoningEffortField? /// A thinking-off switch or effort (`none`/`off`). var disablesThinking = false /// An explicit thinking-on switch (`true`), effort level or budget. @@ -167,17 +164,19 @@ enum GLM5NextPromptPolicy { return try !(nullable && values.decodeNil(forKey: Key(key))) } func effort( - _ values: KeyedDecodingContainer, _ key: String, nullable: Bool = false + _ values: KeyedDecodingContainer, _ key: String, _ field: ReasoningEffortField, + nullable: Bool = false ) throws -> Effort? { guard try present(values, key, nullable: nullable) else { return nil } let requested = try values.decode(String.self, forKey: Key(key)) - if Effort.disablingRequests.contains(requested) { + guard let named = GLM5NextPromptPolicy.namedEffort(requested) else { + if result.invalidReason == nil { result.unknownEffort = field } + throw GLM5NextPromptPolicy.invalid("unsupported reasoning effort", .unsupportedReasoningControl) + } + guard let effort = named.glmLevel else { result.disablesThinking = true return nil } - guard let effort = Effort(requested: requested) else { - throw GLM5NextPromptPolicy.invalid("unsupported reasoning effort", .unsupportedReasoningControl) - } result.requestsThinking = true return effort } @@ -217,7 +216,7 @@ enum GLM5NextPromptPolicy { if root.contains(Key("preserve_thinking")) { result.refuse(.unsupportedReasoningControl) } try thinkingSwitch(root, "enable_thinking") try exclusionSwitch(root, "include_reasoning", excludingValue: false, nullable: true) - let topEffort = try effort(root, "reasoning_effort", nullable: true) + let topEffort = try effort(root, "reasoning_effort", .reasoningEffort, nullable: true) let topClear = try clear(root) // GLM's own API spelling, `{"type": "enabled"|"disabled", // "clear_thinking": Bool}`; a Boolean is the kwargs alias. The @@ -271,7 +270,7 @@ enum GLM5NextPromptPolicy { break } } - nestedEffort = try effort(reasoning, "effort", nullable: true) + nestedEffort = try effort(reasoning, "effort", .reasoningObject, nullable: true) try thinkingSwitch(reasoning, "enabled", nullable: true) try exclusionSwitch(reasoning, "exclude", excludingValue: true, nullable: true) if try present(reasoning, "context", nullable: true) { @@ -294,7 +293,7 @@ enum GLM5NextPromptPolicy { !["reasoning_effort", "clear_thinking", "enable_thinking", "thinking"] .contains($0.stringValue) }) { result.refuse(.unsupportedReasoningControl) } - kwargsEffort = try effort(kwargs, "reasoning_effort") + kwargsEffort = try effort(kwargs, "reasoning_effort", .templateKwargs) kwargsClear = try clear(kwargs) try thinkingSwitch(kwargs, "enable_thinking") try thinkingSwitch(kwargs, "thinking") @@ -327,6 +326,7 @@ enum GLM5NextPromptPolicy { } func validate() throws { + if let unknownEffort { throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(unknownEffort) } if let invalidReason { throw GLM5NextPromptPolicy.invalid( "controls require reasoning_effort none/off/minimal/low/medium/high/xhigh/max, a positive integer reasoning.max_tokens, reasoning.context auto/all_turns/current_turn, reasoning.mode standard, and Boolean clear_thinking and reasoning switches", @@ -397,20 +397,20 @@ enum GLM5NextPromptPolicy { guard controls.preserveThinking == nil else { throw invalid("preserve_thinking is unsupported", .unsupportedReasoningControl) } var thinkingOff = raw.disablesThinking var thinkingOn = raw.requestsThinking - func checked(_ value: String?) throws -> Effort? { + func checked(_ value: String?, _ field: ReasoningEffortField) throws -> Effort? { guard let value else { return nil } - if Effort.disablingRequests.contains(value) { + guard let named = namedEffort(value) else { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(field) + } + guard let effort = named.glmLevel else { thinkingOff = true return nil } - guard let effort = Effort(requested: value) else { - throw invalid("reasoning_effort must be none, minimal, low, medium, high, xhigh or max", .unsupportedReasoningControl) - } thinkingOn = true return effort } - let nested = try checked(request.reasoning?.effort) - let top = try checked(controls.reasoningEffort) + let nested = try checked(request.reasoning?.effort, .reasoningObject) + let top = try checked(controls.reasoningEffort, .reasoningEffort) for enabled in [request.reasoning?.enabled, controls.enableThinking].compactMap({ $0 }) { if enabled { thinkingOn = true } else { thinkingOff = true } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift index d3bc58cc32..16c1411c7e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/MiMo/MiMoV26TemplateFix.swift @@ -11,10 +11,13 @@ import MLXLMServer struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { enum Surface: Equatable { case chat, responses } var invalid = false + /// The field of the first effort that is none of the names. + var unknownEffort: ReasoningEffortField? var unsupportedMediaRichControls = false var templateThinkingAlias: Bool? var responseEnableThinking: Bool? - var responseEffortDisablesThinking: Bool? + /// The thinking switch a Responses body's top-level effort implies. + var responseEffortThinking: Bool? private struct Key: CodingKey { let stringValue: String @@ -68,15 +71,20 @@ struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { guard values.contains(Key(name)) else { return nil } return try values.decode(Bool.self, forKey: Key(name)) // No numeric truthiness. } - func effort(_ values: KeyedDecodingContainer, _ name: String) throws -> Bool? { + // The checkpoint has one reasoning depth (`ReasoningEffort.oneDepthThinking`). + func effort(_ values: KeyedDecodingContainer, _ name: String, + _ field: ReasoningEffortField) throws -> Bool? { guard values.contains(Key(name)) else { return nil } - let value = try values.decode(String.self, forKey: Key(name)) - guard ["none", "off", "0"].contains(value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()) - else { evidence.invalid = true; return nil } - return false + guard let effort = ReasoningEffort(clientValue: try values.decode(String.self, forKey: Key(name))) + else { + evidence.invalid = true + evidence.unknownEffort = evidence.unknownEffort ?? field + return nil + } + return effort.oneDepthThinking } let top = try boolean(root, "enable_thinking") - let topEffort = try effort(root, "reasoning_effort") + let topEffort = try effort(root, "reasoning_effort", .reasoningEffort) if root.contains(Key("preserve_thinking")) { evidence.invalid = true } var alias: Bool? if root.contains(Key("chat_template_kwargs")) { @@ -90,11 +98,11 @@ struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { let allowed = surface == .chat ? ["enabled", "effort"] : ["effort"] if nested.allKeys.contains(where: { !allowed.contains($0.stringValue) }) { evidence.invalid = true } _ = try boolean(nested, "enabled") - _ = try effort(nested, "effort") + _ = try effort(nested, "effort", .reasoningObject) } if surface == .responses { evidence.responseEnableThinking = top ?? alias - evidence.responseEffortDisablesThinking = topEffort + evidence.responseEffortThinking = topEffort } } catch { evidence.invalid = true @@ -104,6 +112,7 @@ struct MiMoV26RawControlEvidence: Sendable, Equatable, Decodable { func validate(modelType: String?) throws { guard modelType == "mimo_v2", invalid else { return } + if let unknownEffort { throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(unknownEffort) } throw MultiModelBatchSchedulerEngineError.invalidToolPayload("MiMo: invalid or unsupported reasoning controls") } func validateMedia(modelType: String?) throws { @@ -164,18 +173,21 @@ enum MiMoV26TemplateFix { /// permissive extension decoder discards wrong-typed controls. This does /// not rewrite body bytes or mutate another family's decoding behavior. static func validateRawControls(_ body: Data) throws { + let evidence: MiMoV26RawControlEvidence do { - let evidence = try JSONDecoder().decode(MiMoV26RawControlEvidence.self, from: body) - try evidence.validate(modelType: "mimo_v2") + evidence = try JSONDecoder().decode(MiMoV26RawControlEvidence.self, from: body) } catch { throw invalid("invalid or unsupported reasoning controls") } + try evidence.validate(modelType: "mimo_v2") } /// API controls are projected to the native Boolean; the checkpoint itself - /// does not consume effort. Absence retains the native ON default. Keep - /// the existing nested > top-level > kwargs Boolean precedence. Granular - /// effort and preserve_thinking are explicit refusals, not ignored knobs. + /// does not consume effort, and has one reasoning depth: every effort but + /// `none` is ON (`ReasoningEffort.oneDepthThinking`). Absence retains the + /// native ON default. Keep the existing nested > top-level > kwargs Boolean + /// precedence. An effort that is none of the names and preserve_thinking + /// are explicit refusals, not ignored knobs. static func additionalContext( request: OpenAIChatCompletionRequest, controls: ChatTemplateControls @@ -201,18 +213,18 @@ enum MiMoV26TemplateFix { guard controls.preserveThinking == nil else { throw invalid("preserve_thinking is unsupported; native history always preserves reasoning_content") } - let rawEffort = try controls.reasoningEffort.map(thinkingFromEffort) - let nestedEffort = try request.reasoning?.effort.map(thinkingFromEffort) + let rawEffort = try controls.reasoningEffort.map { try thinkingFromEffort($0, .reasoningEffort) } + let nestedEffort = try request.reasoning?.effort.map { try thinkingFromEffort($0, .reasoningObject) } return request.reasoning?.enabled ?? controls.rawMiMoControls.responseEnableThinking ?? controls.enableThinking ?? controls.rawMiMoControls.templateThinkingAlias ?? nestedEffort - ?? controls.rawMiMoControls.responseEffortDisablesThinking ?? rawEffort + ?? controls.rawMiMoControls.responseEffortThinking ?? rawEffort } - private static func thinkingFromEffort(_ effort: String) throws -> Bool { - switch effort.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() { - case "none", "off", "0": return false - default: throw invalid("native MiMo supports binary thinking, not granular reasoning effort") + private static func thinkingFromEffort(_ effort: String, _ field: ReasoningEffortField) throws -> Bool { + guard let effort = ReasoningEffort(clientValue: effort) else { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(field) } + return effort.oneDepthThinking } private static func validateValues(_ values: any Sendable) throws { diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift index 860ad863a3..6e6615f05f 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/NemotronSuperPromptContract.swift @@ -16,9 +16,13 @@ enum NemotronSuperPromptContract { static let imageStartTokenID = 19 static let imageEndTokenID = 20 - enum Failure: Error { + enum Failure: Error, Equatable { case templateMismatch, unsupportedControl, conflictingControls, unsupportedMedia case invalidToolArguments, toolDeclarationMismatch, invalidTokens, contextExceeded + /// An effort that is none of the names, in this field. + case unknownReasoningEffort(ReasoningEffortField) + /// `reasoning_effort` and `reasoning.effort` differ. + case conflictingReasoningEfforts } /// Effective template and parser controls. Absent values take the pinned @@ -120,30 +124,35 @@ enum NemotronSuperPromptContract { } /// The official template defaults thinking on even for images. Medium effort - /// is a separate template boolean, not the generic reasoning_effort key. - /// Contradictory spellings of one control are refused, never reconciled. + /// is a separate template boolean, not the generic reasoning_effort key: an + /// effort sets it by its row of `ReasoningEffort.nemotronSuperMediumEffort`. + /// Contradictory spellings of one control are refused, never reconciled: + /// `reasoning_effort` and `reasoning.effort` that differ, even two names, + /// with the typed `conflictingReasoningEfforts`. static func controls(body: Data) throws -> Controls { let raw = try JSONDecoder().decode(RawControls.self, from: body) func normalized(_ value: String?) -> String? { value?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() } - let effort = normalized(raw.nestedEffort ?? raw.effort) - if let effort, !["none", "off", "0", "medium", "high"].contains(effort) { - throw Failure.unsupportedControl + let effort = try (raw.nestedEffort ?? raw.effort).map { value in + guard let effort = ReasoningEffort(clientValue: value) else { + throw Failure.unknownReasoningEffort(raw.nestedEffort != nil ? .reasoningObject : .reasoningEffort) + } + return effort } if let top = normalized(raw.effort), let nested = normalized(raw.nestedEffort), top != nested { - throw Failure.conflictingControls + throw Failure.conflictingReasoningEfforts } if let top = raw.enabled, let nested = raw.nestedEnabled, top != nested { throw Failure.conflictingControls } - let disabled = ["none", "off", "0"].contains(effort ?? "") + let disabled = effort == ReasoningEffort.none let enabled = raw.nestedEnabled ?? raw.enabled ?? !disabled if let explicit = raw.nestedEnabled ?? raw.enabled, effort != nil, explicit == disabled { throw Failure.conflictingControls } - if let medium = raw.medium, effort == "medium" || effort == "high", - medium != (effort == "medium") { throw Failure.conflictingControls } - let medium = raw.medium ?? (effort == "medium") + let effortMedium = effort?.nemotronSuperMediumEffort + if let medium = raw.medium, let effortMedium, medium != effortMedium { throw Failure.conflictingControls } + let medium = raw.medium ?? effortMedium ?? false guard !(medium && !enabled) else { throw Failure.conflictingControls } return Controls(enableThinking: enabled, mediumEffort: medium, truncateHistoryThinking: raw.truncate ?? true, diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift index bedee3feee..4542b79574 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ProviderPromptContractPipeline.swift @@ -138,8 +138,7 @@ enum ProviderPromptContractPipeline { } try MediaIngest.rejectUnsupportedAudio(request, modelType: preserveMiMoMediaParts ? modelType : nil) - try DiffusionGemmaReasoningControl.validate( - request: request, controls: templateControls, modelType: modelType) + try ReasoningEffortPolicy.validate(request, controls: templateControls, modelType: modelType) let isMiMo = MiMoV26TemplateFix.applies(to: .init(modelType: modelType)) if isMiMo { try MiMoV26TemplateFix.validateRequest(request) } guard preserveMiMoMediaParts || !MediaIngest.hasAudio(request) else { @@ -181,8 +180,6 @@ enum ProviderPromptContractPipeline { hasMedia: MediaIngest.hasMedia(request), requiresToolCall: prepared.requiresToolCall) } - try Qwen4SupportPolicy.validateReasoningContext( - modelID: request.model, modelType: modelType, additionalContext: additionalContext) return try NormalizedInput( messages: ChatTemplateFixes.normalizeMessages(messages, context: context), tools: ChatTemplateFixes.normalizeTools(tools, context: context), diff --git a/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift new file mode 100644 index 0000000000..4e00d4113c --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Prompting/ReasoningEffort.swift @@ -0,0 +1,204 @@ +// Copyright © 2026 Eigen Labs. + +import Foundation +import MLXLMServer + +/// A reasoning effort a client names, least reasoning first: OpenAI's and +/// OpenRouter's `none` through `xhigh`, and `max`, which Hermes sends. +/// +/// On one Mac, on a pair's leader and on the coordinator's path alike: +/// - A model that reasons takes each of the seven, as `reasoning_effort` or +/// `reasoning.effort`, and never answers one with a 400: its family's table +/// (below) gives the level its template renders. +/// - A value that is none of the seven is refused before the prompt renders or +/// any KV is reserved, with `MultiModelBatchSchedulerEngineError +/// .unsupportedReasoningEffort(field)`. The engine checks it once the +/// request holds its model, so a cold model may load first; the refusal +/// releases the model. The local API answers it with the field and the +/// seven names, never the value sent (`ReasoningEffortField.refusalMessage`); +/// the coordinator shows its own closed text. +/// - Nemotron 3.5 Super reads both fields and refuses two that differ, even +/// two names, with `.conflictingReasoningEfforts`, which the local API +/// answers in the same shape, naming both fields +/// (`ReasoningEffortField.conflictMessage`). +/// - A model that doesn't reason ignores the effort, whatever it is +/// (`ReasoningEffortPolicy.reasons`). +enum ReasoningEffort: String, CaseIterable, Sendable { + case none, minimal, low, medium, high, xhigh, max + + /// The names a refusal lists. + static let acceptedNames = allCases.map(\.rawValue).joined(separator: ", ") + + /// A client's value, trimmed and in any case: one of the seven names, or + /// `off` or `0`, which mean `none`. GLM-5.3-Flash and Flint read the + /// names exactly as written (`init(rawValue:)`). + init?(clientValue value: String) { + let name = value.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + if name == "off" || name == "0" { + self = Self.none + } else if let effort = Self(rawValue: name) { + self = effort + } else { + return nil + } + } + + /// Whether a client's value switches thinking off: `none`, `off` or `0`. + static func switchesThinkingOff(_ value: String) -> Bool { + Self(clientValue: value) == ReasoningEffort.none + } +} + +/// Each family's table: the level its template renders for each of the seven +/// efforts. A family gets the effort's own level where it has one, else the +/// next one up (toward more reasoning), and its highest past them all, so +/// `minimal` gets its lowest level and `max` its highest; `none` switches +/// thinking off where the model can. Each switch names all seven efforts and +/// has no `default`, so a table that misses one doesn't build; +/// `ReasoningEffortValuesTests.everyFamilyTableCoversEveryEffort` checks +/// every row against that rule. +/// +/// The other families take every effort too. Flint decides for itself whether +/// to reason and reads no effort (`FlintRequestPolicy`). Gemma 4 and Nemotron +/// 3.5 Lightning have only a thinking switch: `none` turns it off, and any +/// other effort reaches the template as sent, which keeps its default. GPT-OSS +/// gets each as sent, except `high`, which renders `medium` +/// (`GPTOSSHarmonyTemplateFix`). The coordinator's prompt sidecar plans Gemma +/// 4's and GPT-OSS's prompts, so they change only together with it. +extension ReasoningEffort { + /// Qwen 3.8's template renders `low`, `medium` and `xhigh` (its default) + /// and raises for any other effort while thinking. The Qwen 3.5 template + /// family (Qwen 3.5, 3.6 and 3.8, and Bonsai 2) and the owned Flash-Next + /// build get these levels (`ReasoningEffortPolicy.takesQwen38Levels`); the + /// 3.5, 3.6 and Bonsai templates read only the thinking switch. `high`, the + /// effort clients send most, renders `xhigh`, as the coordinator's + /// first-party pool sends it. `none` gets a level only when a switch keeps + /// thinking on. + var qwen38Level: ReasoningEffort { + switch self { + case .none, .minimal, .low: .low + case .medium: .medium + case .high, .xhigh, .max: .xhigh + } + } + + /// GLM-5.3-Flash's template renders `low`, `high` and `max` (its default); + /// nil switches thinking off. The coordinator's pool and prompt sidecar + /// map the same way. + var glmLevel: GLM5NextPromptPolicy.Effort? { + switch self { + case .none: nil + case .minimal, .low: .low + case .medium, .high: .high + case .xhigh, .max: .max + } + } + + /// Nemotron 3.5 Super's template has two depths, `medium_effort` and its + /// default: this is the `medium_effort` an effort sets, and nil switches + /// thinking off. + var nemotronSuperMediumEffort: Bool? { + switch self { + case .none: nil + case .minimal, .low, .medium: true + case .high, .xhigh, .max: false + } + } + + /// MiMo V2.6 and DiffusionGemma reason at one depth, so an effort only + /// switches thinking: on for every effort but `none`. + var oneDepthThinking: Bool { + switch self { + case .none: false + case .minimal, .low, .medium, .high, .xhigh, .max: true + } + } +} + +/// Where a request named its reasoning effort; a refusal names it. +public enum ReasoningEffortField: String, Sendable { + case reasoningEffort = "reasoning_effort" + case reasoningObject = "reasoning.effort" + case templateKwargs = "chat_template_kwargs.reasoning_effort" + + /// The refusal of an effort that is none of the names: the field and the + /// seven names, fixed text, never the value sent. + var refusalMessage: String { "\(rawValue) must be one of: \(ReasoningEffort.acceptedNames)." } + + /// The refusal of `reasoning_effort` and `reasoning.effort` that differ, + /// where a model reads both rather than letting one win (Nemotron 3.5 + /// Super): its `param` names both fields, and its message names both and + /// the seven names, fixed text, never the values sent. + static let conflictParam = "\(Self.reasoningEffort.rawValue), \(Self.reasoningObject.rawValue)" + static let conflictMessage = "\(Self.reasoningEffort.rawValue) and \(Self.reasoningObject.rawValue) must be " + + "the same when both are sent, one of: \(ReasoningEffort.acceptedNames)." +} + +/// Which models reason, and the `reasoning_effort` the template context +/// `MultiModelBatchSchedulerEngine.templateAdditionalContext` builds. MiMo, +/// GLM-5.3, Flint and Nemotron 3.5 Super read the effort in their own prompt +/// policies, through their tables above. +enum ReasoningEffortPolicy { + /// Model types whose templates reason: an effort none of the seven names + /// is refused for them. Any other model ignores the effort. + /// `qwen3_vl_moe` is left out: it holds instruct-only Qwen3-VL builds. + private static let reasoningModelTypes: Set = [ + "qwen3_5", "qwen3_5_moe", "prism_hadamard_qwen35", "qwen4_exp", "qwen4_exp_text", + "gemma4", "gemma4_text", "gemma4_vision", "diffusion_gemma", "gpt_oss", + "nemotron_h", "nemotron_h_omni", "mimo_v2", "glm5_next", "glm5_next_text", "glm5_next_mtp", "flint", + ] + + /// The Qwen 3.5 template family's model types. + private static let qwen35TemplateTypes: Set = ["qwen3_5", "qwen3_5_moe", "prism_hadamard_qwen35"] + + /// Whether a model's template gets Qwen 3.8's levels + /// (`ReasoningEffort.qwen38Level`): the Qwen 3.5 template family, and the + /// owned Flash-Next build (`Qwen4SupportPolicy.ownsEffortTemplate`). + static func takesQwen38Levels(modelID: String, modelType: String?) -> Bool { + normalized(modelType).map(qwen35TemplateTypes.contains) == true + || Qwen4SupportPolicy.ownsEffortTemplate(modelID: modelID, modelType: modelType) + } + + /// Whether a model reasons, by its template family. + static func reasons(modelID: String, modelType: String?) -> Bool { + takesQwen38Levels(modelID: modelID, modelType: modelType) + || normalized(modelType).map(reasoningModelTypes.contains) == true + } + + /// Refuses an effort that is none of the seven names, on a model that + /// reasons, naming the field it came in. The typed `reasoning.effort` wins + /// over the top-level spelling, as in the template context. A model that + /// doesn't reason ignores the effort. + static func validate( + _ request: OpenAIChatCompletionRequest, controls: ChatTemplateControls, modelType: String? + ) throws { + guard reasons(modelID: request.model, modelType: modelType) else { return } + if let effort = request.reasoning?.effort { + guard ReasoningEffort(clientValue: effort) != nil else { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject) + } + } else if let effort = controls.reasoningEffort, ReasoningEffort(clientValue: effort) == nil { + throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort) + } + } + + /// The `reasoning_effort` a template receives for `effort`: while + /// thinking, Qwen 3.8's level for it where the model takes those levels; + /// otherwise the effort as sent (a Qwen template ignores it with thinking + /// off), except that GPT-OSS's Harmony policy renders `high` as `medium`. + static func templateEffort( + _ effort: String, modelID: String, modelType: String?, thinking: Bool? + ) -> String { + if thinking != false, takesQwen38Levels(modelID: modelID, modelType: modelType), + let named = ReasoningEffort(clientValue: effort) + { + return named.qwen38Level.rawValue + } + let context = ChatTemplateFixContext(modelId: modelID, modelType: modelType) + return GPTOSSHarmonyTemplateFix.effectiveReasoningEffort(effort, context: context) ?? effort + } + + private static func normalized(_ modelType: String?) -> String? { + modelType?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift b/provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift index eafe0e0bc0..90b2ef6118 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Qwen4SupportPolicy.swift @@ -27,26 +27,13 @@ enum Qwen4SupportPolicy { } } - /// Validate this owned artifact's template contract after the existing - /// boolean/effort precedence has resolved. Other Qwen4 artifacts may ship - /// different templates, so architecture identity alone is insufficient; - /// the concrete Qwen3.8-27B builds ship the same effort contract. - /// Never coerce an unsupported effort or change disabled-thinking behavior. - static func validateReasoningContext( - modelID: String, - modelType: String?, - additionalContext: [String: any Sendable]? - ) throws { - guard (isOwnedModelID(modelID) && isQwen4ModelType(modelType)) - || ModelRuntimeRequirements.qwen38ConcreteModelIDs.contains(modelID), - additionalContext?["enable_thinking"] as? Bool != false, - let effort = additionalContext?["reasoning_effort"] as? String - else { return } - // The original template defaults to xhigh and accepts these exact - // spellings. Preserve that behavior rather than inventing aliases. - guard ["low", "medium", "xhigh"].contains(effort) else { - throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort - } + /// Whether a request renders this owned artifact's template, whose effort + /// levels the concrete Qwen3.8-27B builds share + /// (`ReasoningEffort.qwen38Level`). Other Qwen4 artifacts may ship + /// different templates, so architecture identity alone is insufficient. + static func ownsEffortTemplate(modelID: String, modelType: String?) -> Bool { + (isOwnedModelID(modelID) && isQwen4ModelType(modelType)) + || ModelRuntimeRequirements.qwen38ConcreteModelIDs.contains(modelID) } /// An explicit operator limit can narrow the native window. Unset or diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2DiffusionVisionPrefill.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2DiffusionVisionPrefill.swift index dd828345c0..3cd0abbfb1 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2DiffusionVisionPrefill.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/EngineV2DiffusionVisionPrefill.swift @@ -55,8 +55,7 @@ extension EngineV2VisionPrefill { /// moving decoded assets or opting into an autoregressive tool grammar. static func prepareDiffusionUserInput(request: OpenAIChatCompletionRequest, templateControls: ChatTemplateControls) async throws -> UserInput { - try DiffusionGemmaReasoningControl.validate(request: request, controls: templateControls, - modelType: "diffusion_gemma") + try ReasoningEffortPolicy.validate(request, controls: templateControls, modelType: "diffusion_gemma") for message in request.messages where message.role != .user && message.role != .tool { if case .parts(let parts) = message.content, parts.contains(where: { part in switch part { case .imageURL, .videoURL: true; default: false } diff --git a/provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift b/provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift index 7d84b62001..70859bdc8a 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Vision/MediaIngest.swift @@ -278,10 +278,9 @@ public enum MediaIngest { try rejectUnsupportedAudio(request) let tools = ChatTemplateFixes.normalizeToolMetadata( tools, context: .init(modelId: request.model, modelType: modelType)) + try ReasoningEffortPolicy.validate(request, controls: templateControls, modelType: modelType) let additionalContext = MultiModelBatchSchedulerEngine.templateAdditionalContext( for: request, controls: templateControls, modelType: modelType, hasMedia: true) - try Qwen4SupportPolicy.validateReasoningContext( - modelID: request.model, modelType: modelType, additionalContext: additionalContext) var chatMessages: [Chat.Message] = [] let retainToolMedia = preserveTemplateFields && modelType == "diffusion_gemma" var totalPixels = 0 diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift index 5a6911cfc1..0cc50481f6 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ErrorMapping.swift @@ -69,7 +69,7 @@ extension ProviderLoop { case .modelNotLoaded, .noModelLoadedForTokenization: return .modelLoad case .invalidRole, .invalidToolPayload, .missingUserQuery, .unsupportedReasoningEffort, - .unsupportedNativeReasoningEffort, .mediaUnsupportedByModel, .multimodalRejected, + .conflictingReasoningEfforts, .mediaUnsupportedByModel, .multimodalRejected, .advertisedContextExceeded, .promptExceedsContext, .unsupportedOutputControl: return .clientError case .toolChoiceViolation: @@ -168,7 +168,7 @@ extension ProviderLoop { case .modelNotLoaded, .noModelLoadedForTokenization: return .modelUnavailable case .invalidRole, .invalidToolPayload, .missingUserQuery, .unsupportedReasoningEffort, - .unsupportedNativeReasoningEffort, .advertisedContextExceeded, .promptExceedsContext, + .conflictingReasoningEfforts, .advertisedContextExceeded, .promptExceedsContext, .unsupportedOutputControl: return .invalidRequest case .toolChoiceViolation, .generationFailed: @@ -274,7 +274,7 @@ extension ProviderLoop { return 400 case .invalidToolPayload, .missingUserQuery: return 400 - case .unsupportedReasoningEffort, .unsupportedNativeReasoningEffort: + case .unsupportedReasoningEffort, .conflictingReasoningEfforts: return 400 case .advertisedContextExceeded, .promptExceedsContext, .unsupportedOutputControl: return 400 diff --git a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift index 4fcaafd73f..23b6763479 100644 --- a/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift +++ b/provider-swift/Sources/ProviderCore/Server/NemotronSuperLocalImageHTTP.swift @@ -249,6 +249,12 @@ enum SuperHTTPErrors { || error is NemotronSuperVideoPreprocessing.Failure { return MultiModelBatchSchedulerEngineError.multimodalRejected("unsupported or invalid inline video request") } + if case .unknownReasoningEffort(let field)? = error as? NemotronSuperPromptContract.Failure { + return MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(field) + } + if error as? NemotronSuperPromptContract.Failure == .conflictingReasoningEfforts { + return MultiModelBatchSchedulerEngineError.conflictingReasoningEfforts + } if error is DecodingError || error is NemotronSuperImageDecode.Failure || error is NemotronSuperImagePreprocessing.Failure || error is MediaIngest.MediaError || error is NemotronSuperPromptContract.Failure || error is NemotronSuperRequestPlan.Failure diff --git a/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift b/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift index a10055ad46..b8641ef851 100644 --- a/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift +++ b/provider-swift/Sources/ProviderCore/Server/StandaloneServer+HTTP.swift @@ -176,6 +176,14 @@ public struct CORSResponder: HTTPResponder { } catch MultiModelBatchSchedulerEngineError.promptExceedsContext(let message) { // The model window this Mac holds requests to, in plain words. return Self.openAIErrorResponse(status: .badRequest, message: message, code: "context_length_exceeded") + } catch MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(let field) { + // The field and the names a model that reasons takes (fixed text, never the value sent). + return Self.openAIErrorResponse(status: .badRequest, message: field.refusalMessage, + code: "invalid_reasoning_effort", param: field.rawValue) + } catch MultiModelBatchSchedulerEngineError.conflictingReasoningEfforts { + // Both fields and the names, as for an unknown name (fixed text, never the values sent). + return Self.openAIErrorResponse(status: .badRequest, message: ReasoningEffortField.conflictMessage, + code: "invalid_reasoning_effort", param: ReasoningEffortField.conflictParam) } catch MultiModelBatchSchedulerEngineError.distributedRequestRefused(let refusal, let message) { // A cluster pair's refusal names its rule and the model's limits // (a closed template, never request content): the client sees why. @@ -243,14 +251,16 @@ public struct CORSResponder: HTTPResponder { /// `/v1/embeddings` route emits when the engine is missing). Sets /// the CORS allow-origin header so browser clients can read the /// body even on a cross-origin request. `code` is the optional OpenAI - /// error code; it is omitted from the body when nil. + /// error code and `param` the request field it names; each is omitted + /// from the body when nil. static func openAIErrorResponse( status: HTTPResponse.Status, message: String, - code: String? = nil + code: String? = nil, + param: String? = nil ) -> Response { let body = OpenAIErrorEnvelope( - error: .init(message: message, type: "invalid_request_error", code: code) + error: .init(message: message, type: "invalid_request_error", param: param, code: code) ) let data: Data do { @@ -277,7 +287,8 @@ private struct OpenAIErrorEnvelope: Encodable { struct ErrorObject: Encodable { let message: String let type: String - /// Omitted when nil, so every existing envelope is unchanged. + /// Both omitted when nil, so every existing envelope is unchanged. + var param: String? = nil var code: String? = nil } let error: ErrorObject diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift index 3abf44c424..017c206f17 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Engine/MultiModelBatchSchedulerEngineTests.swift @@ -406,7 +406,7 @@ func templateContextLeavesOtherFormatsAndFamiliesUnchanged() { } } -@Test("none off and zero disable; minimal remains an explicit effort") +@Test("none off and zero disable; minimal reasons, at the model's lowest level") func templateContextNormalizesOnlyReviewedDisableSpellings() { let request = OpenAIChatCompletionRequest( model: "EigenLabs/Qwen3.8-27B-4bit", @@ -423,7 +423,8 @@ func templateContextNormalizesOnlyReviewedDisableSpellings() { for: request, controls: .init(reasoningEffort: "minimal"), hasMedia: true) - #expect(minimal?["reasoning_effort"] as? String == "minimal") + // Qwen 3.8's lowest level. + #expect(minimal?["reasoning_effort"] as? String == "low") #expect(minimal?["enable_thinking"] == nil) } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/FlintPolicyTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/FlintPolicyTests.swift index fe8d858065..1c8bcbc425 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/FlintPolicyTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/FlintPolicyTests.swift @@ -53,7 +53,7 @@ struct FlintPolicyTests { #""reasoning":{"exclude":true}"#, #""reasoning":{"exclude":false}"#, #""reasoning":{"effort":"high","enabled":true,"exclude":false}"#, #""include_reasoning":true"#, #""include_reasoning":false"#, #""reasoning":null"#, - ] + FlintRequestPolicy.acceptedEfforts.sorted().flatMap { + ] + ReasoningEffort.allCases.map(\.rawValue).flatMap { [#""reasoning_effort":"\#($0)""#, #""reasoning":{"effort":"\#($0)"}"#] } @@ -65,19 +65,20 @@ struct FlintPolicyTests { } for controls in [ ChatTemplateControls(enableThinking: false), .init(enableThinking: true), - .init(reasoningEffort: "none"), .init(reasoningEffort: "xhigh"), + .init(reasoningEffort: "none"), .init(reasoningEffort: "xhigh"), .init(reasoningEffort: "max"), ] { try FlintRequestPolicy.validateControls(controls, modelType: "flint") } // Typed values outside the accepted set, without raw evidence. - for controls in [ChatTemplateControls(reasoningEffort: "max"), .init(preserveThinking: false)] { - #expect(throws: MultiModelBatchSchedulerEngineError.self) { - try FlintRequestPolicy.validateControls(controls, modelType: "flint") - } + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort)) { + try FlintRequestPolicy.validateControls(.init(reasoningEffort: "turbo"), modelType: "flint") + } + #expect(throws: MultiModelBatchSchedulerEngineError.self) { + try FlintRequestPolicy.validateControls(.init(preserveThinking: false), modelType: "flint") } - for fields in [#""reasoning":{"effort":"max"}"#] { + for fields in [#""reasoning":{"effort":"turbo"}"#] { let request = try JSONDecoder().decode(OpenAIChatCompletionRequest.self, from: chatBody(fields)) - #expect(throws: MultiModelBatchSchedulerEngineError.self) { + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject)) { try FlintRequestPolicy.validate(request, controls: .init(), modelType: "flint") } } @@ -180,7 +181,7 @@ struct FlintPolicyTests { for fields in [ #""enable_thinking":"false""#, #""enable_thinking":null"#, #""reasoning_effort":" ""#, #""reasoning_effort":false"#, - #""reasoning_effort":"max""#, #""reasoning_effort":"HIGH""#, #""reasoning_effort":" high""#, + #""reasoning_effort":"turbo""#, #""reasoning_effort":"HIGH""#, #""reasoning_effort":" high""#, #""preserve_thinking":false"#, #""preserve_thinking":null"#, #""chat_template_kwargs":{"enable_thinking":0}"#, #""chat_template_kwargs":{"thinking":"true"}"#, diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/CachePromptParityTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/CachePromptParityTests.swift index 7a36294d49..b20b830345 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/CachePromptParityTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/CachePromptParityTests.swift @@ -8,19 +8,19 @@ struct CachePromptParityTests { func nativeReasoningContextVectors() throws { let url = try vectorFile("native_reasoning_vectors.json") let cases = try #require(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [[String: Any]]) - #expect(cases.count == 25) + #expect(cases.count == 28) for fixture in cases { let body = try JSONSerialization.data(withJSONObject: #require(fixture["request"])) do { let request = try ProviderLoop.decodeOpenAIRequest(body) let prepared = try ToolChoicePromptPolicy.prepare(request) + let controls = ProviderLoop.extractChatTemplateControls(from: body) + try ReasoningEffortPolicy.validate(request, controls: controls, + modelType: fixture["model_type"] as? String) let context = MultiModelBatchSchedulerEngine.templateAdditionalContext( - for: request, controls: ProviderLoop.extractChatTemplateControls(from: body), + for: request, controls: controls, modelType: fixture["model_type"] as? String, requiresToolCall: prepared.requiresToolCall) ?? [:] - try Qwen4SupportPolicy.validateReasoningContext( - modelID: request.model, modelType: fixture["model_type"] as? String, - additionalContext: context) #expect(fixture["error"] as? Bool != true) let actual = try JSONSerialization.jsonObject(with: JSONSerialization.data(withJSONObject: context)) let expected = try #require(fixture["additional_context"] as? [String: Any]) diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/DiffusionGemmaReasoningControlTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/DiffusionGemmaReasoningControlTests.swift index 76d0e903ad..2e050cf97f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/DiffusionGemmaReasoningControlTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/DiffusionGemmaReasoningControlTests.swift @@ -8,7 +8,7 @@ struct DiffusionGemmaReasoningControlTests { @Test func emissionPermissionMatchesNativeRenderingPrecedence() throws { for nested: Bool? in [nil, false, true] { for raw: Bool? in [nil, false, true] { - for effort: String? in [nil, "none", "OFF", "0", "minimal", "medium", "xhigh"] { + for effort: String? in [nil, "none", "OFF", "0", "minimal", "medium", "xhigh", "max"] { let request = OpenAIChatCompletionRequest(model: "native-diffusion", messages: [], reasoning: .init(enabled: nested, effort: effort)) let controls = ChatTemplateControls(reasoningEffort: "high", enableThinking: raw) @@ -31,10 +31,10 @@ struct DiffusionGemmaReasoningControlTests { } @Test func responsesPositiveEffortActivatesNativeThinking() throws { - for effort in ["minimal", "low", "medium", "high", "xhigh"] { + for effort in ["minimal", "low", "medium", "high", "xhigh", "max", " Max "] { let request = OpenAIResponseRequest(model: "native-diffusion", input: .text("hello"), reasoning: .init(effort: effort)).chatCompletionRequest - try DiffusionGemmaReasoningControl.validate(request: request, controls: .init(), modelType: "diffusion_gemma") + try ReasoningEffortPolicy.validate(request, controls: .init(), modelType: "diffusion_gemma") let context = MultiModelBatchSchedulerEngine.templateAdditionalContext( for: request, controls: .init(), modelType: "diffusion_gemma") #expect(context?["enable_thinking"] as? Bool == true) @@ -62,16 +62,19 @@ struct DiffusionGemmaReasoningControlTests { @Test func unknownEffortFailsClosedWithoutChangingOtherModels() throws { let request = OpenAIChatCompletionRequest(model: "native-diffusion", messages: [], reasoning: .init(effort: "unsupported")) - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedNativeReasoningEffort) { - try DiffusionGemmaReasoningControl.validate(request: request, controls: .init(), modelType: "diffusion_gemma") + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject)) { + try ReasoningEffortPolicy.validate(request, controls: .init(), modelType: "diffusion_gemma") } for type: String? in [nil, "qwen4_exp", "gemma4", "llama"] { - try DiffusionGemmaReasoningControl.validate(request: request, controls: .init(), modelType: type) let context = MultiModelBatchSchedulerEngine.templateAdditionalContext( for: request, controls: .init(), modelType: type) #expect(context?["enable_thinking"] == nil) } + // A model that doesn't reason ignores the effort. + for type: String? in [nil, "llama"] { + try ReasoningEffortPolicy.validate(request, controls: .init(), modelType: type) + } #expect(ProviderLoop.mapInferenceErrorToStatus( - MultiModelBatchSchedulerEngineError.unsupportedNativeReasoningEffort) == 400) + MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject)) == 400) } } diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningEffortValuesTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningEffortValuesTests.swift new file mode 100644 index 0000000000..a373717095 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Prompting/ReasoningEffortValuesTests.swift @@ -0,0 +1,261 @@ +import Foundation +import MLXLMCommon +import MLXLMServer +import Testing +@testable import ProviderCore + +/// Every reasoning effort a client sends (`none` through `max`, as +/// `reasoning_effort` or `reasoning.effort`) reaches a model that reasons as +/// one of its own levels, through the production prompt pipeline +/// (`ProviderPromptContractPipeline.tokenizeProviderBody`). Hermes sends `max`; +/// Qwen 3.8 answered `high` and `max` with an untyped 400 (journey 2a, B-J2-1). +@Suite("Reasoning effort values") +struct ReasoningEffortValuesTests { + static let efforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"] + + enum Spelling: CaseIterable { + case topLevel, reasoningObject + + /// The field a refusal names. + var field: ReasoningEffortField { + switch self { + case .topLevel: .reasoningEffort + case .reasoningObject: .reasoningObject + } + } + } + + static func body(model: String, effort: String, _ spelling: Spelling) -> Data { + let control = switch spelling { + case .topLevel: #""reasoning_effort":"\#(effort)""# + case .reasoningObject: #""reasoning":{"effort":"\#(effort)"}"# + } + return Data(#"{"model":"\#(model)","messages":[{"role":"user","content":"hi"}],\#(control)}"#.utf8) + } + + /// The template context the request renders with. + static func context(model: String, type: String, effort: String, _ spelling: Spelling) throws -> [String: any Sendable] { + let tokenizer = EffortContextTokenizer() + _ = try ProviderPromptContractPipeline.tokenizeProviderBody( + body(model: model, effort: effort, spelling), tokenizer: tokenizer, modelType: type) + return try #require(tokenizer.contexts.last) + } + + /// Every family's table (`ReasoningEffort.swift`) has a level for each of + /// the seven efforts, and each follows one rule: the effort's own level + /// where the family has it, else the next one up, and the family's highest + /// past them all, so `minimal` gets its lowest and `max` its highest. + /// `none` switches thinking off where the family can. The families without + /// a table take every name too. The tests below render each row. + @Test func everyFamilyTableCoversEveryEffort() throws { + #expect(ReasoningEffort.allCases.map(\.rawValue) == Self.efforts) + // The level `effort` selects among a family's `levels`, lowest first. + func rule(_ effort: String, _ levels: [String]) -> String { + let rank = { (name: String) in Self.efforts.firstIndex(of: name)! } + return levels.first { rank($0) >= rank(effort) } ?? levels[levels.count - 1] + } + let harmony = ChatTemplateFixContext(modelId: "gpt-oss-20b", modelType: "gpt_oss") + for name in Self.efforts { + let effort = try #require(ReasoningEffort(rawValue: name)) + let thinks = name != "none" + #expect(effort.qwen38Level.rawValue == rule(name, ["low", "medium", "xhigh"]), "Qwen 3.8, \(name)") + #expect(effort.glmLevel?.rawValue == (thinks ? rule(name, ["low", "high", "max"]) : nil), "GLM, \(name)") + // Super's depths: `medium_effort`, then its default, ranked as `high`. + #expect(effort.nemotronSuperMediumEffort == (thinks ? rule(name, ["medium", "high"]) == "medium" : nil), + "Super, \(name)") + #expect(effort.oneDepthThinking == thinks, "MiMo and DiffusionGemma, \(name)") + #expect(FlintRequestPolicy.acceptsEffort(name), "Flint, \(name)") + #expect(ReasoningEffort.switchesThinkingOff(name) == !thinks, "Gemma 4 and Lightning, \(name)") + #expect(GPTOSSHarmonyTemplateFix.effectiveReasoningEffort(name, context: harmony) + == (name == "high" ? "medium" : name), "GPT-OSS, \(name)") + } + } + + /// The Qwen 3.8 template renders `low`, `medium` and `xhigh` and raises for + /// anything else while thinking. The Qwen 3.5 template family and the owned + /// Flash-Next build receive the same level; Qwen 3.5, 3.6 and Bonsai 2 read + /// only the thinking switch. + @Test(arguments: [ + ("EigenLabs/Qwen3.8-27B-4bit-mtp", "qwen3_5"), (Qwen4SupportPolicy.ownedModelID, "qwen4_exp"), + (Qwen4SupportPolicy.ownedModelID, "qwen4_exp_text"), ("qwen3.5-35b-a3b", "qwen3_5_moe"), + ("ternary-bonsai-2-27b", "prism_hadamard_qwen35"), + ]) + func theQwenFamilyRendersTheNearestQwen38Level(model: String, type: String) throws { + let levels = ["minimal": "low", "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", + "max": "xhigh"] + for spelling in Spelling.allCases { + let off = try Self.context(model: model, type: type, effort: "none", spelling) + #expect(off["enable_thinking"] as? Bool == false, "\(type) none \(spelling)") + for (effort, level) in levels { + let context = try Self.context(model: model, type: type, effort: effort, spelling) + #expect(context["reasoning_effort"] as? String == level, "\(type) \(effort) \(spelling)") + #expect(context["enable_thinking"] as? Bool != false, "\(type) \(effort) \(spelling)") + } + } + } + + /// Families whose template has a thinking switch and reads no effort level: + /// every effort is taken, and `none` switches thinking off. GPT-OSS cannot + /// switch Harmony's reasoning off; its levels are its Harmony policy's. + @Test(arguments: [ + ("gemma-4-26b-qat-4bit", "gemma4"), (EngineV2SupportedModels.nemotron35LightningModelID, "nemotron_h"), + ("gpt-oss-20b", "gpt_oss"), + ]) + func thinkingSwitchFamiliesTakeEveryEffort(model: String, type: String) throws { + for effort in Self.efforts { + for spelling in Spelling.allCases { + let context = try Self.context(model: model, type: type, effort: effort, spelling) + #expect((context["enable_thinking"] as? Bool == false) == (effort == "none"), "\(type) \(effort)") + } + } + } + + /// DiffusionGemma and MiMo have a thinking switch and no effort level: every + /// effort but `none` reasons. + @Test(arguments: [("native-diffusion", "diffusion_gemma"), ("mimo-v2.6-flash-mopd", "mimo_v2")]) + func binaryThinkingFamiliesReasonForEveryEffortButNone(model: String, type: String) throws { + for effort in Self.efforts { + for spelling in Spelling.allCases { + let context = try Self.context(model: model, type: type, effort: effort, spelling) + #expect(context["enable_thinking"] as? Bool == (effort != "none"), "\(type) \(effort) \(spelling)") + } + } + } + + /// GLM-5.3-Flash renders `low`, `high` and `max`; between two, an effort + /// rounds up, as the coordinator's pool and sidecar map it. + @Test func glmRendersItsNearestLevel() throws { + let levels = ["minimal": "low", "low": "low", "medium": "high", "high": "high", "xhigh": "max", "max": "max"] + for spelling in Spelling.allCases { + let off = try Self.context(model: "glm-5.3-flash", type: "glm5_next", effort: "none", spelling) + #expect(off[GLM5NextPromptPolicy.thinkingOffContextKey] as? Bool == false) + for (effort, level) in levels { + let context = try Self.context(model: "glm-5.3-flash", type: "glm5_next", effort: effort, spelling) + #expect(context["reasoning_effort"] as? String == level, "\(effort) \(spelling)") + #expect(context[GLM5NextPromptPolicy.thinkingOffContextKey] == nil, "\(effort) \(spelling)") + } + } + } + + /// Flint chooses whether to reason: every effort is taken, with no effect. + @Test func flintTakesEveryEffort() throws { + for effort in Self.efforts { + for spelling in Spelling.allCases { + _ = try Self.context(model: "RecursiveSI/flint-int4", type: "flint", effort: effort, spelling) + } + } + } + + /// Nemotron 3.5 Super renders two depths: `medium_effort`, and its default. + @Test func nemotronSuperRendersMediumOrItsDefaultDepth() throws { + let medium = ["minimal": true, "low": true, "medium": true, "high": false, "xhigh": false, "max": false] + for spelling in Spelling.allCases { + let off = try NemotronSuperPromptContract.controls(body: Self.body(model: "m", effort: "none", spelling)) + #expect(!off.enableThinking && !off.mediumEffort) + for (effort, isMedium) in medium { + let controls = try NemotronSuperPromptContract.controls( + body: Self.body(model: "m", effort: effort, spelling)) + #expect(controls.enableThinking, "\(effort) \(spelling)") + #expect(controls.mediumEffort == isMedium, "\(effort) \(spelling)") + } + } + } + + /// Nemotron 3.5 Super reads both fields and refuses two that differ, even + /// two names at one depth, as such: not as an unknown name, which an + /// unknown `reasoning.effort` is first. The same effort in both, in any + /// spelling, renders. + @Test func nemotronSuperRefusesTwoDifferentEfforts() throws { + func controls(_ top: String, _ nested: String) throws -> NemotronSuperPromptContract.Controls { + try NemotronSuperPromptContract.controls(body: Data( + #"{"model":"m","messages":[],"reasoning_effort":"\#(top)","reasoning":{"effort":"\#(nested)"}}"#.utf8)) + } + for (top, nested) in [("high", "max"), ("minimal", "medium"), ("turbo", "low")] { + #expect(throws: NemotronSuperPromptContract.Failure.conflictingReasoningEfforts, "\(top)/\(nested)") { + try controls(top, nested) + } + } + #expect(throws: NemotronSuperPromptContract.Failure.unknownReasoningEffort(.reasoningObject)) { + try controls("low", "turbo") + } + #expect(try controls("high", " HIGH ") == .init(enableThinking: true, mediumEffort: false)) + #expect(try controls("Low", "low") == .init(enableThinking: true, mediumEffort: true)) + } + + static let reasoningModels: [(String, String)] = [ + ("EigenLabs/Qwen3.8-27B-4bit-mtp", "qwen3_5"), (Qwen4SupportPolicy.ownedModelID, "qwen4_exp"), + ("qwen3.5-35b-a3b", "qwen3_5_moe"), ("ternary-bonsai-2-27b", "prism_hadamard_qwen35"), + ("gemma-4-26b-qat-4bit", "gemma4"), ("native-diffusion", "diffusion_gemma"), ("gpt-oss-20b", "gpt_oss"), + (EngineV2SupportedModels.nemotron35LightningModelID, "nemotron_h"), ("mimo-v2.6-flash-mopd", "mimo_v2"), + ("glm-5.3-flash", "glm5_next"), ("RecursiveSI/flint-int4", "flint"), + ] + + /// An effort that is none of the names is refused, never rendered or + /// silently ignored, by every model that reasons, with the error that + /// names the field it came in. + @Test func anUnknownEffortIsRefusedByEveryModelThatReasons() throws { + for (model, type) in Self.reasoningModels { + for spelling in Spelling.allCases { + let tokenizer = EffortContextTokenizer() + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(spelling.field), + "\(type) \(spelling)") { + try ProviderPromptContractPipeline.tokenizeProviderBody( + Self.body(model: model, effort: "turbo", spelling), tokenizer: tokenizer, modelType: type) + } + #expect(tokenizer.contexts.isEmpty, "\(type) \(spelling)") + } + } + for spelling in Spelling.allCases { + #expect(throws: NemotronSuperPromptContract.Failure.unknownReasoningEffort(spelling.field)) { + try NemotronSuperPromptContract.controls(body: Self.body(model: "m", effort: "turbo", spelling)) + } + } + // GLM-5.3-Flash also reads its template's own spelling. + let kwargs = #"{"model":"glm-5.3-flash","messages":[{"role":"user","content":"hi"}],"# + + #""chat_template_kwargs":{"reasoning_effort":"turbo"}}"# + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.templateKwargs)) { + try ProviderPromptContractPipeline.tokenizeProviderBody( + Data(kwargs.utf8), tokenizer: EffortContextTokenizer(), modelType: "glm5_next") + } + } + + /// A model that doesn't reason ignores the effort, whatever it is. + @Test func aModelThatDoesNotReasonIgnoresTheEffort() throws { + for effort in Self.efforts + ["turbo"] { + for spelling in Spelling.allCases { + let context = try Self.context(model: "llama-3.2-3b", type: "llama", effort: effort, spelling) + #expect(context["reasoning_effort"] as? String == effort) + } + } + } +} + +/// Records each chat-template context it renders; everything else is `inner`'s. +final class EffortContextTokenizer: MLXLMCommon.Tokenizer, @unchecked Sendable { + let inner: any MLXLMCommon.Tokenizer + private let lock = NSLock() + private var recorded: [[String: any Sendable]] = [] + + init(_ inner: any MLXLMCommon.Tokenizer = ParityTokenizer(eos: "<|im_end|>", harmony: false)) { + self.inner = inner + } + + var contexts: [[String: any Sendable]] { lock.withLock { recorded } } + + func encode(text: String, addSpecialTokens: Bool) -> [Int] { + inner.encode(text: text, addSpecialTokens: addSpecialTokens) + } + func decode(tokenIds: [Int], skipSpecialTokens: Bool) -> String { + inner.decode(tokenIds: tokenIds, skipSpecialTokens: skipSpecialTokens) + } + func convertTokenToId(_ token: String) -> Int? { inner.convertTokenToId(token) } + func convertIdToToken(_ id: Int) -> String? { inner.convertIdToToken(id) } + var bosToken: String? { inner.bosToken } + var eosToken: String? { inner.eosToken } + var unknownToken: String? { inner.unknownToken } + func applyChatTemplate(messages: [[String: any Sendable]], tools: [[String: any Sendable]]?, + additionalContext: [String: any Sendable]?) throws -> [Int] { + lock.withLock { recorded.append(additionalContext ?? [:]) } + return try inner.applyChatTemplate(messages: messages, tools: tools, additionalContext: additionalContext) + } +} diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/EngineV2VisionRoutingTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/EngineV2VisionRoutingTests.swift index 1ed1eacaa2..1c8dd5fd7c 100644 --- a/provider-swift/Tests/ProviderCoreTests/Inference/Vision/EngineV2VisionRoutingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Vision/EngineV2VisionRoutingTests.swift @@ -1135,11 +1135,11 @@ struct EngineV2VisionRoutingTests { func typedClientErrorKeepsItsMapping() async throws { let engine = VisionScriptedEngine(script: .stream([])) let plumbing = EngineV2VisionPlumbing( - prepare: { _, _, _ in throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort }, + prepare: { _, _, _ in throw MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort) }, emitTelemetry: VisionTelemetrySink().callback()) let router = makeRoutingEngine( container: makeStubContainer(), bridge: makeBridge(engine: engine), plumbing: plumbing) - await #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { + await #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort)) { _ = try await collectContent(try await router.streamChatCompletion(request: imageRequest())) } #expect(engine.submitted.isEmpty) diff --git a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ConsumerParityTests.swift b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ConsumerParityTests.swift index bb074fc1eb..9b6aa8d1a0 100644 --- a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ConsumerParityTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26ConsumerParityTests.swift @@ -41,10 +41,10 @@ final class MiMoV26ConsumerParityTests: XCTestCase { } } - func testRawControlCapsuleRejectsTypesUnknownKeysAndGranularEffort() throws { + func testRawControlCapsuleRejectsTypesUnknownKeysAndUnknownEffort() throws { let bad = [ #""enable_thinking":"false""#, #""enable_thinking":0"#, #""enable_thinking":1"#, - #""enable_thinking":null"#, #""reasoning_effort":"high""#, #""reasoning_effort":7"#, + #""enable_thinking":null"#, #""reasoning_effort":"turbo""#, #""reasoning_effort":7"#, #""chat_template_kwargs":{"unknown":"sensitive_fixture_detail"}"#, #""chat_template_kwargs":false"#, #""chat_template_kwargs":{"enable_thinking":0}"#, #""preserve_thinking":false"#, #""reasoning":{"summary":"sensitive_fixture_detail"}"#, @@ -234,7 +234,7 @@ final class MiMoV26ConsumerParityTests: XCTestCase { controls: ProviderLoop.extractChatTemplateControls(from: data)), expected) } for bad in [#""enable_thinking":"false""#, #""enable_thinking":0"#, - #""reasoning_effort":"high""#, #""preserve_thinking":false"#] { + #""reasoning_effort":"turbo""#, #""preserve_thinking":false"#] { let body = MiMoConsumerFixture.body(bad) XCTAssertThrowsError(try MiMoV26TemplateFix.effectiveThinkingEnabled( request: ProviderLoop.decodeOpenAIRequest(body), diff --git a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26PromptContractTests.swift b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26PromptContractTests.swift index 6f362222ae..35e1cff359 100644 --- a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26PromptContractTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26PromptContractTests.swift @@ -95,7 +95,7 @@ final class MiMoV26PromptContractTests: XCTestCase { for bad: Any in ["false", 0, 1, NSNull()] { bodies.append(["model": "m", "messages": [["role": "user", "content": "hello"]], "enable_thinking": bad]) } - bodies.append(["model": "m", "messages": [["role": "user", "content": "hello"]], "reasoning": ["effort": "high"]]) + bodies.append(["model": "m", "messages": [["role": "user", "content": "hello"]], "reasoning": ["effort": "turbo"]]) bodies.append(["model": "m", "messages": [ ["role": "assistant", "content": "", "tool_calls": [["id": "a", "type": "function", "function": ["name": "f", "arguments": [1, NSNull()] as [Any]]]]], diff --git a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26TemplateFixTests.swift b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26TemplateFixTests.swift index 0e545d8d6e..c2b7b9dd63 100644 --- a/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26TemplateFixTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/MiMo/MiMoV26TemplateFixTests.swift @@ -263,9 +263,20 @@ final class MiMoV26TemplateFixTests: XCTestCase { XCTAssertThrowsError(try MiMoV26TemplateFix.validateRawControls(JSONSerialization.data(withJSONObject: body))) } } - for effort in ["minimal", "low", "medium", "high", "xhigh", "on", "false", ""] { + for effort in ["on", "false", ""] { XCTAssertThrowsError(try MiMoV26TemplateFix.additionalContext( - request: .init(model: "m", messages: []), controls: .init(reasoningEffort: effort))) + request: .init(model: "m", messages: []), controls: .init(reasoningEffort: effort))) { + XCTAssertEqual($0 as? MultiModelBatchSchedulerEngineError, .unsupportedReasoningEffort(.reasoningEffort)) + } + } + // One reasoning depth: every effort but none thinks. + for effort in ["minimal", "low", "medium", "high", "xhigh", "max"] { + let raw = try MiMoV26TemplateFix.additionalContext( + request: .init(model: "m", messages: []), controls: .init(reasoningEffort: effort)) + XCTAssertEqual(raw?["enable_thinking"] as? Bool, true, effort) + let nested = try MiMoV26TemplateFix.additionalContext( + request: .init(model: "m", messages: [], reasoning: .init(effort: effort)), controls: .init()) + XCTAssertEqual(nested?["enable_thinking"] as? Bool, true, effort) } for preserve in [true, false] { XCTAssertThrowsError(try MiMoV26TemplateFix.additionalContext( diff --git a/provider-swift/Tests/ProviderCoreTests/NativeMediaToolPreparationTests.swift b/provider-swift/Tests/ProviderCoreTests/NativeMediaToolPreparationTests.swift index 6d64e79383..c13236455e 100644 --- a/provider-swift/Tests/ProviderCoreTests/NativeMediaToolPreparationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NativeMediaToolPreparationTests.swift @@ -76,12 +76,12 @@ struct NativeMediaToolPreparationTests { /// native model type, exactly as `EngineV2VisionPrefill` builds them. @Test(arguments: [("DarkBloom/Qwen3.8-Flash-Next-Q4-mtp", true, "qwen4_exp"), ("EigenLabs/Qwen3.8-27B-4bit-mtp", false, nil)] as [(String, Bool, String?)]) - func nativeMediaRejectsUnsupportedEffortBeforeDecodingPixels( + func nativeMediaRejectsAnUnknownEffortBeforeDecodingPixels( model: String, preserveTemplateFields: Bool, modelType: String? ) async throws { let body = #""" {"model":"\#(model)", - "reasoning":{"enabled":true,"effort":"high"}, + "reasoning":{"enabled":true,"effort":"turbo"}, "messages":[{"role":"user","content":[ {"type":"image_url","image_url":{"url":"data:image/png;base64,AAAA"}}, {"type":"text","text":"Inspect the picture"}]}]} @@ -91,8 +91,8 @@ struct NativeMediaToolPreparationTests { do { _ = try await MediaIngest.buildUserInput( from: decoded, preserveTemplateFields: preserveTemplateFields, modelType: modelType) - Issue.record("unsupported native effort unexpectedly reached pixel decoding") - } catch MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort { + Issue.record("an unknown effort unexpectedly reached pixel decoding") + } catch MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject) { // The invalid image must not be decoded before the control error. } } diff --git a/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift b/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift index ef0a2f713b..a228dbe3b3 100644 --- a/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/NemotronSuperPromptContractTests.swift @@ -115,7 +115,7 @@ final class NemotronSuperPromptContractTests: XCTestCase { #"{"reasoning_effort":"medium","medium_effort":false}"#, #"{"reasoning_effort":"high","reasoning":{"effort":"medium"}}"#, #"{"enable_thinking":true,"reasoning":{"enabled":false}}"#,#"{"enable_thinking":"false"}"#, - #"{"reasoning_effort":"low"}"#, + #"{"reasoning_effort":"turbo"}"#, #"{"reasoning_effort":"low","medium_effort":false}"#, #"{"preserve_thinking":true}"#, #"{"enable_thinking":false,"medium_effort":true}"#, #"{"enable_thinking":false,"chat_template_kwargs":{"enable_thinking":true}}"#, diff --git a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedEffortLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedEffortLiveTests.swift index a7c8ba438a..19ee7a0299 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedEffortLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProviderLoop/NemotronSuperManagedEffortLiveTests.swift @@ -34,6 +34,7 @@ extension NemotronSuperManagedSlotTests { let modeControls: [(String, [String: Any], Bool)] = [ ("omitted", [:], true), ("high", ["reasoning_effort": "high"], true), ("medium", ["reasoning_effort": "medium"], true), ("none", ["reasoning_effort": "none"], false), + ("low", ["reasoning_effort": "low"], true), ("max", ["reasoning_effort": "max"], true), ("off", ["reasoning_effort": "off"], false), ("zero", ["reasoning_effort": "0"], false), ("nested-medium", ["reasoning": ["effort": " MEDIUM\n"]], true), ("template-medium", ["chat_template_kwargs": ["enable_thinking": true, "medium_effort": true]], true), @@ -54,7 +55,7 @@ extension NemotronSuperManagedSlotTests { try body(["reasoning_effort": effort, "response_format": ["type": "json_object"]], stream, "Return exactly one JSON object with key answer and integer value 4.")) } } - let invalid: [Data] = try ([["reasoning_effort": "low"], ["reasoning_effort": "xhigh"], + let invalid: [Data] = try ([["reasoning_effort": "turbo"], ["reasoning_effort": "low", "medium_effort": false], ["reasoning_effort": "medium", "medium_effort": false], ["reasoning_effort": "high", "reasoning": ["effort": "medium"]]] as [[String: Any]]) .map { try body($0, true, Self.arithmeticPrompt) } diff --git a/provider-swift/Tests/ProviderCoreTests/Qwen4ReasoningEffortValidationTests.swift b/provider-swift/Tests/ProviderCoreTests/Qwen4ReasoningEffortValidationTests.swift index f601b19ed1..2e4b766d13 100644 --- a/provider-swift/Tests/ProviderCoreTests/Qwen4ReasoningEffortValidationTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Qwen4ReasoningEffortValidationTests.swift @@ -4,13 +4,21 @@ import MLXLMServer import Testing @testable import ProviderCore -@Suite("Restricted-effort template request validation") +/// The Qwen 3.8 template renders `low`, `medium` and `xhigh` (its default) +/// and raises for any other effort while thinking. Every effort a client sends +/// reaches it as one of those; one that is none of the names is refused before +/// the template runs. +@Suite("Qwen 3.8 effort template levels") struct Qwen4ReasoningEffortValidationTests { private let owned = Qwen4SupportPolicy.ownedModelID + private static let levels: [String?: String?] = [ + nil: nil, "minimal": "low", "low": "low", "medium": "medium", "high": "xhigh", "xhigh": "xhigh", + "max": "xhigh", "LOW": "low", " low ": "low", "High": "xhigh", + ] @Test(arguments: [Qwen4SupportPolicy.ownedModelID, Qwen4SupportPolicy.registryModelID]) - func supportedAndDefaultEffortsReachTokenizerUnchanged(owned: String) throws { - for effort: String? in [nil, "low", "medium", "xhigh"] { + func everyEffortReachesTheTemplateAsOneOfItsLevels(owned: String) throws { + for (effort, level) in Self.levels { let tokenizer = ReasoningContextTokenizer() let request = OpenAIChatCompletionRequest(model: owned, messages: [.init(role: .user, content: .text("hi"))], @@ -18,27 +26,27 @@ struct Qwen4ReasoningEffortValidationTests { let tokens = try tokenize(request, controls: .init(), tokenizer: tokenizer) #expect(tokens == [7, 8]) #expect(tokenizer.context?["enable_thinking"] as? Bool == true) - #expect(tokenizer.context?["reasoning_effort"] as? String == effort) + #expect(tokenizer.context?["reasoning_effort"] as? String == level, "\(effort ?? "nil")") #expect(tokenizer.calls == 1) } } @Test(arguments: [Qwen4SupportPolicy.ownedModelID, Qwen4SupportPolicy.registryModelID]) - func unsupportedEffortsAreRejectedBeforeTemplateInvocation(owned: String) throws { - for effort in ["high", "minimal", "unsupported", "LOW", " low ", ""] { + func anUnknownEffortIsRefusedBeforeTemplateInvocation(owned: String) throws { + for effort in ["unsupported", "", "on"] { let tokenizer = ReasoningContextTokenizer() let request = OpenAIChatCompletionRequest(model: owned, messages: [.init(role: .user, content: .text("hi"))], reasoning: .init(enabled: true, effort: effort)) - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject)) { try tokenize(request, controls: .init(), tokenizer: tokenizer) } #expect(tokenizer.calls == 0) } } - @Test func disabledThinkingPreservesEveryCallerEffort() throws { - for effort in ["high", "minimal", "unsupported", "none"] { + @Test func disabledThinkingKeepsTheCallerEffortTheTemplateIgnores() throws { + for effort in ["high", "minimal", "none", "max"] { let tokenizer = ReasoningContextTokenizer() let request = OpenAIChatCompletionRequest(model: owned, messages: [.init(role: .user, content: .text("hi"))], @@ -47,6 +55,12 @@ struct Qwen4ReasoningEffortValidationTests { #expect(tokenizer.context?["enable_thinking"] as? Bool == false) #expect(tokenizer.context?["reasoning_effort"] as? String == effort) } + let request = OpenAIChatCompletionRequest(model: owned, + messages: [.init(role: .user, content: .text("hi"))], + reasoning: .init(enabled: false, effort: "unsupported")) + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningObject)) { + try tokenize(request, controls: .init(), tokenizer: ReasoningContextTokenizer()) + } } @Test func resolvedAliasAndTypedBooleanPrecedenceIsUnchanged() throws { @@ -55,53 +69,58 @@ struct Qwen4ReasoningEffortValidationTests { _ = try tokenize(base, controls: .init(reasoningEffort: "high", enableThinking: false), tokenizer: disabled) #expect(disabled.context?["enable_thinking"] as? Bool == false) #expect(disabled.context?["reasoning_effort"] as? String == "high") - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { - try tokenize(base, controls: .init(reasoningEffort: "high"), tokenizer: ReasoningContextTokenizer()) - } + let raw = ReasoningContextTokenizer() + _ = try tokenize(base, controls: .init(reasoningEffort: "high"), tokenizer: raw) + #expect(raw.context?["reasoning_effort"] as? String == "xhigh") for effort in ["none", "off", "0"] { let tokenizer = ReasoningContextTokenizer() _ = try tokenize(base, controls: .init(reasoningEffort: effort), tokenizer: tokenizer) #expect(tokenizer.context?["enable_thinking"] as? Bool == false) + // Thinking switched on explicitly: `none` is the lowest level. var explicit = base explicit.reasoning = .init(enabled: true, effort: effort) - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { - try tokenize(explicit, controls: .init(enableThinking: false), tokenizer: ReasoningContextTokenizer()) - } + let on = ReasoningContextTokenizer() + _ = try tokenize(explicit, controls: .init(enableThinking: false), tokenizer: on) + #expect(on.context?["enable_thinking"] as? Bool == true) + #expect(on.context?["reasoning_effort"] as? String == "low") } } - @Test func nonOwnedAndNonNativeTemplatesRemainUntouched() throws { - let combinations: [(String, String?)] = [ - ("another-qwen4", "qwen4_exp"), (owned + "-alias", "qwen4_exp_text"), - (owned, "qwen3_5"), (owned, nil), - ("Qwen3.5-9B", "qwen3_5"), ("eigenlabs/qwen3.8-27b-4bit-mtp", "qwen3_5"), + /// The levels follow the template: the Qwen 3.5 template family (its + /// strictest member is 3.8's) and the owned Flash-Next build. Another + /// Qwen4 artifact may ship another template; its effort goes as sent. + @Test func levelsFollowTheTemplateNotTheArchitecture() { + let mapped: [(String, String?)] = [ + (owned, "qwen4_exp"), (owned, "qwen4_exp_text"), (owned, "qwen3_5"), ("Qwen3.5-9B", "qwen3_5"), + ("eigenlabs/qwen3.8-27b-4bit-mtp", "qwen3_5"), ("bonsai", "prism_hadamard_qwen35"), + (ModelRuntimeRequirements.qwen38ConcreteModelID, nil), ] - for (modelID, modelType) in combinations { - try Qwen4SupportPolicy.validateReasoningContext(modelID: modelID, modelType: modelType, - additionalContext: ["enable_thinking": true, "reasoning_effort": "high"]) - } - for type in ["qwen4_exp", "qwen4_exp_text"] { - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { - try Qwen4SupportPolicy.validateReasoningContext(modelID: owned, modelType: type, - additionalContext: ["reasoning_effort": "high"]) + let untouched: [(String, String?)] = [ + ("another-qwen4", "qwen4_exp"), (owned + "-alias", "qwen4_exp_text"), (owned, nil), + ("qwen3-vl-30b-a3b-instruct", "qwen3_vl_moe"), ("gemma-4-26b", "gemma4"), + ] + for (cases, expected) in [(mapped, "xhigh"), (untouched, "high")] { + for (model, type) in cases { + let context = MultiModelBatchSchedulerEngine.templateAdditionalContext( + for: .init(model: model, messages: []), controls: .init(reasoningEffort: "high"), modelType: type) + #expect(context?["reasoning_effort"] as? String == expected, "\(model) \(type ?? "nil")") } } } @Test(arguments: [Qwen4SupportPolicy.ownedModelID, Qwen4SupportPolicy.registryModelID]) - func responsesTypedEffortUsesTheSameValidationBoundary(owned: String) throws { - for effort in ["high", "minimal"] { + func responsesTypedEffortReachesTheSameLevels(owned: String) throws { + for (effort, level) in [("high", "xhigh"), ("minimal", "low"), ("max", "xhigh")] { let request = OpenAIResponseRequest(model: owned, input: .text("hi"), reasoning: .init(effort: effort)) let tokenizer = ReasoningContextTokenizer() - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { - try tokenize(request.chatCompletionRequest, controls: .init(enableThinking: true), tokenizer: tokenizer) - } - #expect(tokenizer.calls == 0) + _ = try tokenize(request.chatCompletionRequest, controls: .init(enableThinking: true), tokenizer: tokenizer) + #expect(tokenizer.context?["reasoning_effort"] as? String == level) } } - @Test func typedErrorUsesClient400ClassificationOnBothServingPaths() throws { - let error = MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort + @Test(arguments: [MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort), + .conflictingReasoningEfforts]) + func typedErrorUsesClient400ClassificationOnBothServingPaths(error: MultiModelBatchSchedulerEngineError) throws { #expect(ProviderLoop.mapInferenceErrorToStatus(error) == 400) let failure = ProviderLoop.sanitizedInferenceFailure(from: error, phase: .streamStart) #expect(failure.statusCode == 400) @@ -116,21 +135,21 @@ struct Qwen4ReasoningEffortValidationTests { } @Test(arguments: ModelRuntimeRequirements.qwen38ConcreteModelIDs.sorted()) - func qwen38BuildsShareTheRestrictedEffortContract(model: String) throws { + func qwen38BuildsShareTheEffortLevels(model: String) throws { let hi: [OpenAIChatMessage] = [.init(role: .user, content: .text("hi"))] - for effort: String? in [nil, "low", "medium", "xhigh"] { - _ = try tokenize(.init(model: model, messages: hi, reasoning: .init(enabled: true, effort: effort)), - controls: .init(), tokenizer: ReasoningContextTokenizer(), modelType: "qwen3_5") - } - // Raw-body `reasoning_effort`, the shape OpenRouter traffic arrives in. - for effort in ["high", "minimal"] { + // Raw-body `reasoning_effort`, the shape OpenRouter and Hermes send. + for (effort, level) in Self.levels { let tokenizer = ReasoningContextTokenizer() - #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort) { - try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: effort), - tokenizer: tokenizer, modelType: "qwen3_5") - } - #expect(tokenizer.calls == 0) + _ = try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: effort), + tokenizer: tokenizer, modelType: "qwen3_5") + #expect(tokenizer.context?["reasoning_effort"] as? String == level, "\(effort ?? "nil")") + } + let tokenizer = ReasoningContextTokenizer() + #expect(throws: MultiModelBatchSchedulerEngineError.unsupportedReasoningEffort(.reasoningEffort)) { + try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: "turbo"), + tokenizer: tokenizer, modelType: "qwen3_5") } + #expect(tokenizer.calls == 0) _ = try tokenize(.init(model: model, messages: hi), controls: .init(reasoningEffort: "high", enableThinking: false), tokenizer: ReasoningContextTokenizer(), modelType: "qwen3_5") } diff --git a/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityHarness.swift b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityHarness.swift index b6ecc3e822..dc2f07835e 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityHarness.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ClusterAPIParityHarness.swift @@ -308,8 +308,10 @@ struct ParitySoloServer { let task: Task let port: UInt16 - static func start(family: ParityFamily, directory: URL, script: ParityScript) async throws -> Self { - let tokenizer = family.tokenizer + /// `tokenizer`: the family's own when nil. + static func start(family: ParityFamily, directory: URL, script: ParityScript, + tokenizer: (any MLXLMCommon.Tokenizer)? = nil) async throws -> Self { + let tokenizer = tokenizer ?? family.tokenizer // `ProviderModelContainer.tokenizerHandle`: the Gemma contract check. let handle = TokenizerHandle(tokenizer, toolConstraintContractVerified: Gemma4ToolConstraintContract.isVerified(modelType: family.modelType, modelDirectory: directory)) @@ -364,9 +366,11 @@ struct ParityClusterServer { let host: DistributedLocalServer let port: UInt16 - static func start(family: ParityFamily, directory: URL, supportsLogprobs: Bool = true) async throws -> Self { + /// `tokenizer`: the family's own when nil. + static func start(family: ParityFamily, directory: URL, supportsLogprobs: Bool = true, + tokenizer: (any MLXLMCommon.Tokenizer)? = nil) async throws -> Self { let session = try ParityClusterSession(family: family, directory: directory, supportsLogprobs: supportsLogprobs) - let tokenizer = family.tokenizer + let tokenizer = tokenizer ?? family.tokenizer // As `StartCommand+Distributed`: the plan's first-token budget is bound. let host = DistributedLocalServer(session: session, config: .init(host: "127.0.0.1", port: 0, authToken: parityToken), diff --git a/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ReasoningEffortLocalAPITests.swift b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ReasoningEffortLocalAPITests.swift new file mode 100644 index 0000000000..53dd26b4fc --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Server/Distributed/ReasoningEffortLocalAPITests.swift @@ -0,0 +1,207 @@ +import Foundation +import Hummingbird +import Logging +import NIOCore +import NIOEmbedded +import Testing +@testable import ProviderCore + +/// One Mac's local API and a pair leader's take every reasoning effort a +/// client sends, and refuse one that is none of the names with a 400 that +/// names the field and the names. Journey 2a (B-J2-1): Hermes's +/// `reasoning_effort: "max"` got an untyped 400 "Invalid inference request." +/// from Qwen 3.8 27B on pair-2, so Hermes fell back to the user's paid provider. +/// Model-free (`ClusterAPIParityHarness.swift`); not a hardware result. +@Suite(.timeLimit(.minutes(3))) +struct ReasoningEffortLocalAPITests { + /// The parity harness's Qwen 3.8 artifact, served under the registered + /// build's ID as pair-2 serves it. + static let qwen38: ParityFamily = { + let base = ParityFamily.all.first { $0.name == "qwen3.8-27b" }! + return ParityFamily(name: "qwen3.8-27b-registered", modelType: base.modelType, + modelID: "EigenLabs/Qwen3.8-27B-4bit-mtp", configJSON: base.configJSON, + generationJSON: base.generationJSON, eosToken: base.eosToken, harmony: base.harmony, plain: base.plain, + tool: base.tool, stopString: base.stopString, long: base.long, json: base.json) + }() + + struct Servers { + let family: ParityFamily + let solo: ParitySoloServer, pair: ParityClusterServer + let soloTokenizer: EffortContextTokenizer, pairTokenizer: EffortContextTokenizer + let client: URLSession + + static func start(_ family: ParityFamily, directory: URL) async throws -> Self { + let script = ParityScript() + script.set(family.plain) + let soloTokenizer = EffortContextTokenizer(family.tokenizer) + let pairTokenizer = EffortContextTokenizer(family.tokenizer) + let solo = try await ParitySoloServer.start(family: family, directory: directory, script: script, + tokenizer: soloTokenizer) + let pair = try await ParityClusterServer.start(family: family, directory: directory, tokenizer: pairTokenizer) + return .init(family: family, solo: solo, pair: pair, soloTokenizer: soloTokenizer, + pairTokenizer: pairTokenizer, client: URLSession(configuration: .ephemeral)) + } + + func stop() async { + client.invalidateAndCancel() + await pair.stop() + await solo.stop() + } + + /// The pair answers with the family's plain script; it serves one + /// request at a time, so this returns once it retired this one. + func sendToPair(_ testCase: ParityCase) async throws -> ParityAnswer { + let pair = pair, script = family.plain + let reservations = pair.session.base.reserveCount + let stop = ParityStopFlag() + let driver = Task { await pair.drive(after: reservations, script: script, failure: false, stop: stop) } + let answer: ParityAnswer + do { answer = try await paritySend(port: pair.port, testCase, session: client) } + catch { stop.set(); await driver.value; throw error } + stop.set(); await driver.value + let end = ContinuousClock.now.advanced(by: .seconds(5)) + while ContinuousClock.now < end { + let held = await !pair.host.pins.isEmpty + let queued = await !pair.host.waiting.isEmpty + if !held && !queued { break } + try await Task.sleep(for: .milliseconds(2)) + } + return answer + } + } + + /// The two fields a client names an effort in, and the body text naming `effort` in each. + static let fields = ["reasoning_effort", "reasoning.effort"] + + static func control(_ field: String, _ effort: String) -> String { + field == "reasoning_effort" ? #","reasoning_effort":"\#(effort)""# : #","reasoning":{"effort":"\#(effort)"}"# + } + + /// Qwen 3.8's template renders `low`, `medium` and `xhigh`: `high` and + /// `max` are served as `xhigh` and `minimal` as `low`, on one Mac and on + /// the pair alike (tensor-parallel and pipeline pairs share this leader + /// path); `none` switches thinking off. + @Test func everyEffortIsServedOnOneMacAndOnAPair() async throws { + let directory = try Self.qwen38.makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let servers = try await Servers.start(Self.qwen38, directory: directory) + let levels = ["none": "none", "minimal": "low", "low": "low", "medium": "medium", "high": "xhigh", + "xhigh": "xhigh", "max": "xhigh"] + do { + for (effort, level) in levels.sorted(by: { $0.key < $1.key }) { + for field in Self.fields { + for stream in [false, true] { + let testCase = ParityCase("\(field)=\(effort) stream=\(stream)", body: ParityCase.chat( + servers.family.modelID, Self.control(field, effort), stream: stream)) + let single = try await paritySend(port: servers.solo.port, testCase, session: servers.client) + let pair = try await servers.sendToPair(testCase) + for (place, answer, tokenizer) in [("one Mac", single, servers.soloTokenizer), + ("pair", pair, servers.pairTokenizer)] { + #expect(answer.status == 200, "\(place), \(testCase.name): \(answer)") + #expect(tokenizer.contexts.last?["reasoning_effort"] as? String == level, + "\(place), \(testCase.name)") + #expect((tokenizer.contexts.last?["enable_thinking"] as? Bool == false) == (effort == "none"), + "\(place), \(testCase.name)") + } + } + } + } + } catch { await servers.stop(); throw error } + await servers.stop() + } + + /// An effort that is none of the names is answered before the prompt + /// renders or the pair reserves any KV: 400, `invalid_reasoning_effort`, + /// the field it came in, and the names this API takes. + @Test func anUnknownEffortIsRefusedInWordsOnOneMacAndOnAPair() async throws { + let directory = try Self.qwen38.makeDirectory() + defer { try? FileManager.default.removeItem(at: directory) } + let servers = try await Servers.start(Self.qwen38, directory: directory) + do { + for field in Self.fields { + for stream in [false, true] { + let testCase = ParityCase("\(field)=turbo stream=\(stream)", body: ParityCase.chat( + servers.family.modelID, Self.control(field, "turbo"), stream: stream), script: .none) + let single = try await paritySend(port: servers.solo.port, testCase, session: servers.client) + let pair = try await servers.sendToPair(testCase) + for (place, answer) in [("one Mac", single), ("pair", pair)] { + #expect(answer.status == 400, "\(place), \(testCase.name): \(answer)") + let body = try #require(answer.body.first.flatMap { Data($0.utf8) }) + let object = try #require(JSONSerialization.jsonObject(with: body) as? [String: Any]) + let error = try #require(object["error"] as? [String: Any], "\(place): \(answer)") + #expect(error["type"] as? String == "invalid_request_error", "\(place)") + #expect(error["code"] as? String == "invalid_reasoning_effort", "\(place): \(answer)") + #expect(error["param"] as? String == field, "\(place): \(answer)") + #expect(error["message"] as? String + == "\(field) must be one of: none, minimal, low, medium, high, xhigh, max.", + "\(place): \(answer)") + } + } + } + #expect(servers.soloTokenizer.contexts.isEmpty) + #expect(servers.pairTokenizer.contexts.isEmpty) + #expect(servers.pair.session.base.reserveCount == 0) + } catch { await servers.stop(); throw error } + await servers.stop() + } + + /// Nemotron 3.5 Super reads both fields and doesn't choose between two that + /// differ, even two names (`NemotronSuperPromptContract.controls(body:)`). + /// Its local API refuses them as it refuses an unknown name, on text and + /// media requests alike: 400, `invalid_reasoning_effort`, with `param` and + /// the message naming both fields and the names, never the values sent. + /// The same effort in both fields, in any spelling, is served. + @Test func superRefusesTwoDifferentEffortsInWords() async throws { + func body(_ top: String, _ nested: String) -> Data { + Data(#"{"model":"m","messages":[{"role":"user","content":"hi"}],"reasoning_effort":"\#(top)","reasoning":{"effort":"\#(nested)"}}"#.utf8) + } + for (top, nested) in [("high", "max"), ("max", "high"), ("minimal", "medium"), ("turbo", "low")] { + let error = try #require(throws: (any Error).self, "\(top)/\(nested)") { + try NemotronSuperPromptContract.controls(body: body(top, nested)) + } + for media in [false, true] { + let (status, refusal) = try await Self.localAnswer(SuperHTTPErrors.map(error, media: media)) + let place = "\(top)/\(nested), media \(media)" + #expect(status == .badRequest, "\(place)") + #expect(refusal["type"] as? String == "invalid_request_error", "\(place)") + #expect(refusal["code"] as? String == "invalid_reasoning_effort", "\(place): \(refusal)") + #expect(refusal["param"] as? String == "reasoning_effort, reasoning.effort", "\(place): \(refusal)") + #expect(refusal["message"] as? String == "reasoning_effort and reasoning.effort must be the same " + + "when both are sent, one of: none, minimal, low, medium, high, xhigh, max.", "\(place): \(refusal)") + } + } + for (top, nested) in [("high", " HIGH "), ("none", "None")] { + _ = try NemotronSuperPromptContract.controls(body: body(top, nested)) + } + } + + /// The local API's answer (`CORSResponder`) to an error its engine threw. + static func localAnswer(_ error: any Error) async throws -> (HTTPResponse.Status, [String: Any]) { + let context = BasicRequestContext(source: ApplicationRequestContextSource( + channel: EmbeddedChannel(), logger: Logger(label: "reasoning-effort"))) + let request = Request(head: .init(method: .post, scheme: "http", authority: "localhost", + path: "/v1/chat/completions"), body: .init(buffer: ByteBuffer())) + let response = try await CORSResponder(inner: EffortThrowingResponder(error: error)) + .respond(to: request, context: context) + let body = EffortCollectedBody() + try await response.body.write(body) + let envelope = try #require( + JSONSerialization.jsonObject(with: Data(String(buffer: body.bytes).utf8)) as? [String: Any]) + return (response.status, try #require(envelope["error"] as? [String: Any])) + } +} + +private struct EffortThrowingResponder: HTTPResponder { + typealias Context = BasicRequestContext + let error: any Error + func respond(to request: Request, context: Context) async throws -> Response { throw error } +} + +private final class EffortCollectedBody: ResponseBodyWriter, @unchecked Sendable { + var bytes = ByteBuffer() + func write(_ buffer: ByteBuffer) async throws { + var buffer = buffer + bytes.writeBuffer(&buffer) + } + func finish(_ trailingHeaders: HTTPFields?) async throws {} +} diff --git a/provider-swift/Tests/ProviderCoreTests/Server/FlintOpenRouterLiveTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/FlintOpenRouterLiveTests.swift index 0f59699652..2c5665f541 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/FlintOpenRouterLiveTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/FlintOpenRouterLiveTests.swift @@ -98,7 +98,7 @@ struct FlintOpenRouterLiveTests { // Reasoning controls are accepted. Flint always chooses whether to // reason; effort has no effect and enabled/exclude only control // whether reasoning is returned. - for effort in ["minimal", "low", "medium", "high", "xhigh"] { + for effort in ["minimal", "low", "medium", "high", "xhigh", "max"] { var request = chat(reasoningPrompt) request["reasoning"] = ["effort": effort] let (code, data) = try await post(request, name: "reasoning-effort-\(effort)") diff --git a/provider-swift/Tests/ProviderCoreTests/Server/InferenceRefusalLoggingTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/InferenceRefusalLoggingTests.swift index dbf7e9cdd4..c40c595c36 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/InferenceRefusalLoggingTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/InferenceRefusalLoggingTests.swift @@ -111,8 +111,9 @@ struct InferenceRefusalLoggingTests { (.unsupportedOutputControl("unsupported_output_control: this model's engine does not return logprobs"), .unsupportedOutputControl), (.invalidRole("critic"), .unsupportedMessageRole), - (.unsupportedReasoningEffort, .unsupportedReasoningControl), - (.unsupportedNativeReasoningEffort, .unsupportedReasoningControl), + (.unsupportedReasoningEffort(.reasoningEffort), .unsupportedReasoningControl), + (.unsupportedReasoningEffort(.reasoningObject), .unsupportedReasoningControl), + (.conflictingReasoningEfforts, .contradictoryReasoningControls), (.invalidToolPayload("GLM5: history is missing a tool result", refusal: .unansweredToolCall), .unansweredToolCall), (.invalidToolPayload("tool message has no preceding assistant tool_calls"), nil), diff --git a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperLocalHTTPReasoningToolTests.swift b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperLocalHTTPReasoningToolTests.swift index 1369bf0c8f..bf4e770b3f 100644 --- a/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperLocalHTTPReasoningToolTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/Server/NemotronSuperLocalHTTPReasoningToolTests.swift @@ -127,6 +127,21 @@ extension NemotronSuperLocalHTTPTests { let text = try await send(body(["x"], stream: true, invalid), status: .badRequest) #expect(text.contains("error")) } + // An effort refusal names its fields, never the values sent: an + // unknown name, and two spellings that differ. + for (controls, param) in [ + (["reasoning": ["effort": "turbo"]], "reasoning.effort"), + (["reasoning_effort": "high", "reasoning": ["effort": "max"]], "reasoning_effort, reasoning.effort"), + ] as [([String: Any], String)] { + for stream in [true, false] { + let text = try await send(body(["x"], stream: stream, controls), status: .badRequest) + let object = try JSONSerialization.jsonObject(with: Data(text.utf8)) as? [String: Any] + let error = try #require(object?["error"] as? [String: Any], "\(param): \(text)") + #expect(error["code"] as? String == "invalid_reasoning_effort", "\(param): \(text)") + #expect(error["param"] as? String == param, "\(param): \(text)") + #expect(!text.contains("turbo"), "\(text)") + } + } // Logprobs: one entry per generated token in generation order, // reasoning tokens included, with the requested alternatives, // greedy first; the visible output is unchanged. A stream's