Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feature/Reasoning-on-structured-output · L-261006-d907b8 — validate reasoning per model (#1363)
Louis Choquelda78b214222c
diff --git a/.drift/acks/pipelex-kernel-docs.toml b/.drift/acks/pipelex-kernel-docs.tomlindex e97c69d1d..600f50a7f 100644--- a/.drift/acks/pipelex-kernel-docs.toml+++ b/.drift/acks/pipelex-kernel-docs.toml@@ -1,8 +1,8 @@contract = "pipelex-kernel-docs"-digest = "sha256:3b0caaabd67aa654f0b4155d7cb463aa866d01f7ebc559d66cac181c9df3c888"+digest = "sha256:31f0c6b43ae0e9120f1103aa12068a80fdf1e10ec120ca5b289f454f85667449"reviewed_by = "Claude (Opus 5.5)"-reviewed_at = "2026-10-06T03:07:41Z"-rationale = "clean-pass: re-acked on the merge of dev into the dotted-input branch, whose two acks each covered one side. The merged judgment_ops.py carries the branch's build_judgment_material (each entry one plain-named input's whole value, no path walk) and dev's resolve_judgment_setting docstring (a model whose backend is disabled keeps the deck's handle on a dry run); docs/under-the-hood/pipelex-kernel.md auto-merged both sides' sentences, the judgment paragraph stating plain names and the keyless-boot paragraph stating every enabled backend loaded with no credential resolved, and both still match the merged code."+reviewed_at = "2026-10-06T22:38:42Z"+rationale = "real-catch: llm_ops.py now raises LLMSettingRefusedError only for a built-in backend's refusal and re-raises an external plugin's as written; pipelex-kernel.md entry paragraph rewritten to say so, re-read against check_llm_setting_with_served_model; rest of the page unaffected."[trigger_files]"pipelex/kernel/__init__.py" = "blob:c4f1b0fe2ccc17db9110733f71b612f4ac1ba4ce"@@ -18,7 +18,7 @@ rationale = "clean-pass: re-acked on the merge of dev into the dotted-input bran"pipelex/kernel/img_gen_results.py" = "blob:46b4ca11c70d906ae6d58ce66461f9b3414f1bfa""pipelex/kernel/judgment_ops.py" = "blob:fe66d7d00433a9924d60710e9bb25838197c52e0""pipelex/kernel/judgment_results.py" = "blob:40ba1258cc81d34df3e427d5511ccd40c6edf789"-"pipelex/kernel/llm_ops.py" = "blob:64a6d3d77a165f4f70614ced69876f56d873a8c7"+"pipelex/kernel/llm_ops.py" = "blob:6555af22cadf5316cfcadf975d96b6792043c3a6""pipelex/kernel/llm_prompt_content.py" = "blob:3fade4a660226e63ad4f916952ee37d34e7d2bbd""pipelex/kernel/llm_results.py" = "blob:6e3b8a2878b5bb284ece5fac10262fb59ac2029d""pipelex/kernel/memory_ops.py" = "blob:7fbbfaaec99f9712d8e215520cb02e26aad3fb40"@@ -27,4 +27,4 @@ rationale = "clean-pass: re-acked on the merge of dev into the dotted-input bran"pipelex/kernel/search_ops.py" = "blob:f9c1dc09dd3beaf1a54ac8e3774db1d510cbdaa3""pipelex/kernel/search_results.py" = "blob:101b70dc96cc5ee1721c9f6b1cb725a5ca78ff70""pipelex/kernel/templating_style_ops.py" = "blob:395473806d600dfc4f124c07f2afebb951fc086b"-"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:39543269189511ac813fa99242b04d5c528ebfa2"+"tests/unit/pipelex/kernel/test_kernel_boot_contract.py" = "blob:63c06904e9f53f80f98a0a45e00aa8116c9beb31"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f1c84c1f4..dcc78e004 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,7 @@- **A reasoning setting reaches a structured output**: a pipe whose model setting carries `reasoning_effort` or `reasoning_budget`, the deck's `$deep-analysis`, `$quick-reasoning` and `$retrieval-premium` presets included, now generates its structured output with that setting on every provider, where every language-model worker refused it with `LLMCapabilityError` "does not support reasoning parameters for structured generation". A model refuses a reasoning setting on a structured output only where it refuses it on text, or on Mistral where its structure method is not `instructor/mistral_tools`, whose JSON parsing cannot read a reasoning reply; a structured call on an Anthropic tool method with thinking on leaves the tool choice to the model, since a forced tool choice cannot carry thinking.- **A manual thinking budget leaves room for the answer and stays in the model's range (Breaking)**: an Anthropic or Gemini thinking budget, resolved from an effort or set explicitly, is cut to leave a quarter of `max_tokens` for the answer, where it could take all but one token of it, and held within the range the model declares with the new `min_thinking_budget` and `max_thinking_budget` valued constraints. The kit's Anthropic models declare the API's minimum of 1,024 tokens, so the 512 that `minimal` maps to is raised to it, and its Gemini 2.5 models declare their ranges, so `max` effort's 65,536 tokens, which every Gemini 2.5 model refused, are cut to the model's maximum even without a `max_tokens`. A `max_tokens` too small to hold the model's minimum beside the answer reserve is refused with an `LLMCapabilityError` naming the numbers, where the request was sent, and a reasoning effort of `none` on a Gemini model that always thinks, which the kit marks with the new `thinking_cannot_be_disabled` listed constraint, is refused rather than sent as a budget of 0 that Gemini answers with a 400; a project that copied the kit's `anthropic.toml`, `bedrock.toml` or `google.toml` gets the bounds by declaring them in its copy.- **Mistral reasoning is sent as `reasoning_effort`**: a reasoning effort on a Mistral model is sent as `reasoning_effort = "high"`, the only reasoning value Mistral's reasoning models accept, where it was sent as `prompt_mode = "reasoning"`, which every current Mistral model refuses, so any reasoning effort on Mistral failed. The `reasoning` level of `[inference.llm.mistral.effort_to_level_map]` is unchanged.+- **A model setting its model refuses is refused when the method loads (Breaking)**: a `PipeLLM` or `PipeStructure` whose model setting the model it resolves to cannot take, such as a reasoning setting on a model declaring `thinking_mode = "none"`, a reasoning budget on an OpenAI or Mistral model, a thinking budget its `max_tokens` cannot hold, or a structured output on a Bedrock native model, is refused by `pipelex validate`, `POST /v1/validate` and a run's load as an item of the new `PipeValidationErrorType` value `llm_setting_refused_by_model` on its `model` or `model_to_structure` field, where it validated as runnable and failed at its first call. The check is the new `check_request` classmethod of the LLM workers, which `LLMWorkerAbstract` now runs before every provider call and which an LLM backend registers for validation through the new optional `check_llm_request` of `PluginRegistrar.add_inference_backend`; a backend registering none, an external plugin's included, is held to the rule every worker shares, that a model declaring `thinking_mode = "none"` takes no reasoning setting. The item names the model by its deck handle and is shown even under strict error disclosure, so an external plugin's refusal is shown as written only when the plugin raises it as caller-facing copy with `as_caller_fault()`, and by its title otherwise.- **A structured output on Google without a system prompt no longer fails**: a structured call on the `google` backend whose prompt has no system text failed with `TypeError` "generate_content() got an unexpected keyword argument 'system'", and is now sent with no system instruction.- **A model listing `temperature_unsupported` gets no temperature on any SDK**: a model whose backend file lists the `temperature_unsupported` constraint is now called without a temperature on the OpenAI Responses, Google, Mistral and Bedrock-native SDKs too, where those sent one anyway and only the Anthropic and OpenAI chat-completions SDKs honoured the constraint. The model spec answers it as the new `accepts_temperature` property, and a Bedrock client's `chat` now takes `temperature=None` to send none.diff --git a/docs/api-server/error-responses.md b/docs/api-server/error-responses.mdindex a30d0b407..878818e31 100644--- a/docs/api-server/error-responses.md+++ b/docs/api-server/error-responses.md@@ -51,7 +51,7 @@ When a bundle fails validation, the `ValidateBundleError` carries a `validation_| `field_path`, `field_name` | The offending field within the bundle, when the error localizes to one. || `variable_names`, `missing_concept_code`, `missing_pipe_code`, `declared_concepts` | Extra context for specific failure shapes (undefined variables, an unresolved concept, pipe or package reference, the set of concepts that were declared). On an `unresolved_package_dependency` item, `missing_pipe_code` is the reference as written, `<address>->domain.code`, so the package's address is the part before `->`. || `line`, `column` | The 1-based position where the TOML parser stopped, on a TOML syntax error. |-| `model_reference`, `model_type`, `suggestions` | On an `unknown_model` item — a pipe naming a model the deployment's model deck does not define — the reference as the bundle wrote it, the kind of model the pipe needs (`llm`, `extract`, …), and the deck's close matches of that kind. With exactly one suggestion the item also carries an `unsafe` `suggested_fix` renaming the model. |+| `model_reference`, `model_type`, `suggestions` | On an `unknown_model` item — a pipe naming a model the deployment's model deck does not define — the reference as the bundle wrote it, the kind of model the pipe needs (`llm`, `extract`, …), and the deck's close matches of that kind. With exactly one suggestion the item also carries an `unsafe` `suggested_fix` renaming the model. On an `llm_setting_refused_by_model` item — a `PipeLLM` or `PipeStructure` whose model setting the model it resolves to refuses, which its worker would refuse at the first call — `field_name` and `field_path` name the `model` or `model_to_structure` field holding the setting, and `model_reference` is the preset, alias or model that field names, absent when it writes the setting inline or the pipe leaves it to the deck's override or default. || `suggested_fix` | A structured, deterministic fix for this error — present only when the fix planner derived one. See [Suggested fixes](#suggested-fixes). |Items carry only the fields that apply to their category — absent fields are omitted, not null. `validation_errors` is **retained under STRICT disclosure** (it describes the caller's own submitted bundle, not server internals). It is present only on `ValidateBundleError`; other error types omit it.diff --git a/docs/api-server/openapi/pipelex-api.openapi.yaml b/docs/api-server/openapi/pipelex-api.openapi.yamlindex 6df657639..cbadd46dc 100644--- a/docs/api-server/openapi/pipelex-api.openapi.yaml+++ b/docs/api-server/openapi/pipelex-api.openapi.yaml@@ -5540,6 +5540,7 @@ components:- inadequate_output_concept- inadequate_output_multiplicity- llm_output_cannot_be_image+ - llm_setting_refused_by_model- invalid_pipe_code_syntax- invalid_input_name- unknown_pipe_typediff --git a/docs/api-server/pipe-validate.md b/docs/api-server/pipe-validate.mdindex daf9b21f1..87e5f7c8b 100644--- a/docs/api-server/pipe-validate.md+++ b/docs/api-server/pipe-validate.md@@ -104,7 +104,7 @@ The 200 body is one of two arms, discriminated on the mandatory `is_valid` field**Response Fields (invalid arm):**- `is_valid` (`false`): the discriminant of the invalid arm-- `validation_errors` (list): the structured per-error diagnostics a client maps to per-line problems — built by pipelex's one shared builder, so they are byte-for-byte the same items the agent CLI emits. Each item carries a `category` (the closed set `blueprint_validation` | `pipe_factory` | `pipe_validation` | `dry_run`), a `message`, and the locators the runtime can attribute (`error_type`, `pipe_code` / `concept_code` / `domain_code`, `field_path` / `field_name`, and `source`). Absent locators are omitted, not null. An item may also carry a **`suggested_fix`** — a structured, deterministic repair (`fix_code`, `description`, `safety: safe|unsafe`, and the `ops[]` of semantic TOML patch operations to apply). It is present only when the fix planner derived one from the typed error data; a client that ignores it behaves exactly as before. See [Error Responses → Structured validation errors](error-responses.md#structured-validation-errors) and [→ Suggested fixes](error-responses.md#suggested-fixes) for every field. The array is **never empty on an invalid verdict** (the structured-info invariant is total): a failing dry run becomes one `dry_run` item per failing pipe, located at the innermost pipe that failed (its `pipe_code`, `domain_code` and, when known, `source`), a TOML syntax error carries the `line` and `column` the parser stopped at, and a parse-level failure with no attributable locator (an empty blueprint, an elaborator failure) becomes one `blueprint_validation` residual item carrying the message (no `source`). Every refusal of the bundle while it loads is an item of the verdict, never a no-verdict `5xx`: an unknown model is an `unknown_model` item on the pipe's `model` field, and a call into a method package this runtime cannot resolve (not installed and not fetchable, or a fetch that failed) is an `unresolved_package_dependency` item on the first pipe naming the package, whose `missing_pipe_code` is the reference as written, `<address>->domain.code`+- `validation_errors` (list): the structured per-error diagnostics a client maps to per-line problems — built by pipelex's one shared builder, so they are byte-for-byte the same items the agent CLI emits. Each item carries a `category` (the closed set `blueprint_validation` | `pipe_factory` | `pipe_validation` | `dry_run`), a `message`, and the locators the runtime can attribute (`error_type`, `pipe_code` / `concept_code` / `domain_code`, `field_path` / `field_name`, and `source`). Absent locators are omitted, not null. An item may also carry a **`suggested_fix`** — a structured, deterministic repair (`fix_code`, `description`, `safety: safe|unsafe`, and the `ops[]` of semantic TOML patch operations to apply). It is present only when the fix planner derived one from the typed error data; a client that ignores it behaves exactly as before. See [Error Responses → Structured validation errors](error-responses.md#structured-validation-errors) and [→ Suggested fixes](error-responses.md#suggested-fixes) for every field. The array is **never empty on an invalid verdict** (the structured-info invariant is total): a failing dry run becomes one `dry_run` item per failing pipe, located at the innermost pipe that failed (its `pipe_code`, `domain_code` and, when known, `source`), a TOML syntax error carries the `line` and `column` the parser stopped at, and a parse-level failure with no attributable locator (an empty blueprint, an elaborator failure) becomes one `blueprint_validation` residual item carrying the message (no `source`). Every refusal of the bundle while it loads is an item of the verdict, never a no-verdict `5xx`: an unknown model is an `unknown_model` item on the pipe's `model` field, a model setting the model it resolves to refuses (a reasoning setting on a model that does not reason, for instance) is an `llm_setting_refused_by_model` item on the field naming the setting, and a call into a method package this runtime cannot resolve (not installed and not fetchable, or a fetch that failed) is an `unresolved_package_dependency` item on the first pipe naming the package, whose `missing_pipe_code` is the reference as written, `<address>->domain.code`- `pending_signatures` (list[str]): best-effort outstanding signatures (empty on the invalid arm, since no library was assembled)- `is_runnable` (`false`): an invalid bundle is never runnable- `message` (string): the human-readable verdict summary: the lone item's message when there is one item, `N validation errors (first: <the first item's message>)` when there are several, and the parser's own message for a parse-level failurediff --git a/docs/building-methods/pipes/pipe-operators/PipeLLM.md b/docs/building-methods/pipes/pipe-operators/PipeLLM.mdindex abea48b42..8ada4ed13 100644--- a/docs/building-methods/pipes/pipe-operators/PipeLLM.md+++ b/docs/building-methods/pipes/pipe-operators/PipeLLM.md@@ -255,6 +255,8 @@ When `model` is specified as a table (inline LLM setting), it accepts the follow| `reasoning_budget` | integer | Explicit token budget for reasoning. Mutually exclusive with `reasoning_effort`. Supported by Anthropic and Google only. || `description` | string | Human-readable description (for presets) |+A setting the model it resolves to cannot take is refused when the method loads, before a run spends anything: validation runs the check the model's worker runs before every call, so a reasoning setting on a model that does not reason, a reasoning budget on a model taking only an effort, or a budget its `max_tokens` cannot hold is an `llm_setting_refused_by_model` error on the `model` or `model_to_structure` field holding the setting. The setting checked is the one the output is generated with: `model` for a single text, the structuring setting for anything else.+!!! tip "More on Reasoning"For provider-specific behavior and model-specific examples, see [Reasoning Controls](../../../under-the-hood/reasoning-controls.md).diff --git a/docs/errors/inference-and-providers.md b/docs/errors/inference-and-providers.mdindex 9058c1c0d..b457a2a73 100644--- a/docs/errors/inference-and-providers.md+++ b/docs/errors/inference-and-providers.md@@ -56,6 +56,7 @@ own page. Classes are grouped by subsystem.- [`LLMModelNotFoundError`](llm-model-not-found-error.md) — LLM model not found- [`LLMPromptParameterError`](llm-prompt-parameter-error.md) — LLM prompt parameter- [`LLMPromptSpecError`](llm-prompt-spec-error.md) — LLM prompt spec+- [`LLMSettingRefusedError`](llm-setting-refused-error.md) — LLM setting refused- [`LLMSettingsValidationError`](llm-settings-validation-error.md) — LLM settings validation- [`ModelChoiceNotFoundError`](model-choice-not-found-error.md) — Model choice not found- [`ModelDeckNotFoundError`](model-deck-not-found-error.md) — Model deck not founddiff --git a/docs/errors/llm-setting-refused-error.md b/docs/errors/llm-setting-refused-error.mdnew file mode 100644index 000000000..d1c670476--- /dev/null+++ b/docs/errors/llm-setting-refused-error.md@@ -0,0 +1,21 @@+---+title: "LLM setting refused"+description: "Reference for the `LLMSettingRefusedError` Pipelex error class."+---++<!-- pipelex:generated -->++# LLM setting refused++A worker's refusal of an LLM setting, worded for the caller who wrote the setting.++| Field | Value |+|---|---|+| `error_type` | `LLMSettingRefusedError` |+| `title` | LLM setting refused |+| `type_uri` | `https://docs.pipelex.com/latest/errors/llm-setting-refused-error/` |+| `error_domain` | _(inherited from parent)_ |+| Defined in | `pipelex.cogt.exceptions` |+| Parent class | [`LLMCapabilityError`](llm-capability-error.md) |++[Back to Error Reference](index.md)diff --git a/docs/under-the-hood/inference-backend-plugins.md b/docs/under-the-hood/inference-backend-plugins.mdindex 4087c617d..5ec167180 100644--- a/docs/under-the-hood/inference-backend-plugins.md+++ b/docs/under-the-hood/inference-backend-plugins.md@@ -60,9 +60,21 @@ registrar.add_inference_backend(family=InferenceFamily.LLM, # LLM | IMG_GEN | EXTRACT | SEARCH | DOC_GEN | JUDGMENTsdk="acme", # the model's `sdk` stringmake_worker=_make_acme_worker, # a MakeWorkerFn (a plain callable)+ check_llm_request=_check_acme_request, # optional, LLM family only: a CheckLLMRequestFn)```+`check_llm_request` is how validation learns what the worker refuses. Every LLM worker runs a `check_request` classmethod before each provider call, which refuses, from the model's spec and the job params alone, a request it would refuse anyway: a reasoning setting the model's `thinking_mode` refuses, a reasoning budget where it takes only an effort, a thinking budget the call's `max_tokens` cannot hold, or a structured output it cannot generate. When a method loads, every `PipeLLM` and `PipeStructure` resolves its model setting to the model the deck serves and calls the check its backend registered, so such a step is refused as an `llm_setting_refused_by_model` item before a run spends anything. The item is shown to whoever wrote the setting, even under strict error disclosure, so the refusal's text must name nothing your plugin keeps private: raise it as caller-facing copy, `LLMCapabilityError(msg).as_caller_fault()`, to have it shown as written, and any other refusal your check raises is named on the item by its title alone. A built-in backend's refusal is shown with the model named by its deck handle. The registered check is import-light like `make_worker`, called with `inference_model`, `job_params` and `is_structured` as keyword arguments, and delegates to the worker class's own check, which builds no SDK client:++```python+def _check_acme_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ from acme_pipelex.acme_worker import AcmeLLMWorker++ AcmeLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)+```++An LLM backend that registers no check is held to `LLMWorkerAbstract.check_request`, the rule every worker shares: a model whose spec declares `thinking_mode = "none"` takes no reasoning setting. A worker that refuses more overrides `check_request` from the same helpers its calls resolve the request with, so validation and the call never disagree. A check raising `MissingDependencyError`, because the backend's SDK is not installed, leaves the step to the run. A plugin that builds one of the built-in workers for its own `sdk` registers a check calling that worker's `check_request`, as the built-in plugins do.+A registry key is `(family, sdk)`. The same `sdk` string may appear in two families (e.g. `google` serves both `LLM` and `IMG_GEN`); they are distinct keys. A duplicate `(family, sdk)` fails loud with `DuplicateInferenceBackendError` naming **both** contributing plugins.One plugin may register across several families from a single `register` — `openai` and `google` serve `LLM` + `IMG_GEN`, `mistral` serves `LLM` + `EXTRACT`, `linkup` serves `EXTRACT` + `SEARCH`, and `typesafe` serves `JUDGMENT` alone. This is the cross-family-vendor coordination point: one plugin, many backends. `DOC_GEN` is the family of the document engines a `PipeDocGen` step prints with, local libraries rather than inference, which the built-in `reportlab` plugin and the Pipelex document generation plugin serve (see [Document Engine Plugins](document-engine-plugins.md)).diff --git a/docs/under-the-hood/pipelex-kernel.md b/docs/under-the-hood/pipelex-kernel.mdindex 6dc558a52..1ef980766 100644--- a/docs/under-the-hood/pipelex-kernel.md+++ b/docs/under-the-hood/pipelex-kernel.md@@ -56,7 +56,7 @@ Four gates hold this, and each covers something the others miss — see [Hub Lay| `pipelex-dev check-hub-layering` | No kernel *module* imports the interpreter hub || `tests/unit/pipelex/test_kernel_layer_import_closure.py` | A kernel entry point *imports* clean || `tests/unit/pipelex/test_kernel_layer_exceptions_aggregate_gate.py` | No kernel module reaches the exceptions aggregate — imports and bare strings alike |-| `tests/unit/pipelex/kernel/test_kernel_boot_contract.py` | Every kernel entry point **runs** on a keyless boot, swept afterwards — except the deck-reading helpers (`resolve_*_setting`, `concrete_llm_model_handle`), which read the model deck (a separate question from this one) |+| `tests/unit/pipelex/kernel/test_kernel_boot_contract.py` | Every kernel entry point **runs** on a keyless boot, swept afterwards — except the deck-reading helpers (`resolve_*_setting`, `served_*_model`, `check_llm_setting_with_served_model`, `concrete_llm_model_handle`), which read the model deck (a separate question from this one) |Only the last one can see a function-local interpreter import, and it is **per-function**: it catches one inside `run_search` only by calling `run_search`. Every new kernel entry point owes it an arm.@@ -71,7 +71,7 @@ Both façade calls take the concept and the output class the caller wants, defau| Module | Entry points ||---|---|| `pipelex.kernel.pipelex_kernel` | `PipelexKernel.make`, `.llm_text`, `.llm_object`, `.make_step_metadata`, `.log_context` |-| `pipelex.kernel.llm_ops` | `resolve_llm_setting_for_text` / `_for_object`, `concrete_llm_model_handle`, `derive_structure_prompt`, `generate_object_content`, `run_llm_text`, `run_llm_object` |+| `pipelex.kernel.llm_ops` | `resolve_llm_setting_for_text` / `_for_object`, `served_llm_model`, `check_llm_setting_with_served_model`, `concrete_llm_model_handle`, `derive_structure_prompt`, `generate_object_content`, `run_llm_text`, `run_llm_object` || `pipelex.kernel.templating_style_ops` | `resolve_templating_style` || `pipelex.kernel.extract_ops` | `resolve_extract_setting`, `build_extract_job_params`, `run_extract` || `pipelex.kernel.img_gen_ops` | `resolve_img_gen_setting`, `resolve_default_size`, `build_img_gen_job_params`, `run_img_gen` |@@ -87,6 +87,8 @@ Both façade calls take the concept and the output class the caller wants, defauThe two `assemble_*` functions are there because `run_llm_text` and `run_img_gen` both take a *ready* prompt. A caller that could not build one would be holding an operator it cannot reach, which is what image generation was until `assemble_img_gen_prompt` existed: its only builder was an interpreter-layer blueprint. What they own is the part a caller must not re-derive — resolving `ImageReference` and `DocumentReference` out of working memory, and, on the image side, keeping the `[Image N]` tokens numbered from the same registry that orders `input_images`, since a mismatch mislabels which image the prompt is describing and nothing downstream can detect it.+`served_llm_model` gives the spec of the LLM a handle resolves to on this boot, an alias to its target and a waterfall to its first served member as a run resolves them, or `None` when no backend serves one. `check_llm_setting_with_served_model` refuses an LLM setting the model it resolves to refuses, before anything is spent: it runs the request check the model's backend registered beside its worker factory, which is the check the worker itself runs before every call, against the job params the setting gives once the model's constraints apply, for a text or a structured output. For a built-in backend it raises an `LLMSettingRefusedError`, an `LLMCapabilityError` carrying the worker's reason with the model named by its deck handle rather than by the SDK, backend and provider model id the worker's own refusal names, so its message is shown to a caller even under strict error disclosure. An external plugin's refusal is raised as the plugin wrote it, and its message reaches a caller only when the plugin raised it as caller-facing copy. A backend that registered no check is held to the rule every worker shares, that a model whose spec declares `thinking_mode = "none"` takes no reasoning setting, and a model no backend serves, or whose backend's SDK is not installed, is left to the run. The interpreter's `PipeLLM` and `PipeStructure` call it when a method loads; a programmatic caller calls it before `run_llm_text` or `run_llm_object` to get the same refusal without a call.+`run_judgment` asks one question over the step's inputs by name, which it calls the material. `build_judgment_material` reads each input off its content's class, never off its concept, so the kernel stays free of the concept library: text is its string, a number its number, a yes/no its boolean, a date or a time its ISO string, a list the array of its items, any other structure its JSON object without its absent members, and an image or a document, or a list of either, travels beside that JSON state as prompt images and documents keyed by the input's name. An optional input that holds no value is left out, whether its absence was recorded or it was never written. An input name is a plain name, so each entry is one input's whole value, and the material holds exactly what the step declares: a field reaches a judgment only when the calling sequence binds it under a name of its own. `make_verdict_content` turns the answer into the verdict native: a yes/no answer's probability decides the verdict against the step's threshold, inclusive, or against 0.5 when none is declared; an answer with no probability keeps the model's own verdict, and when a threshold was declared a live run logs a warning and its `JudgmentResult` reports `threshold_applied` as false. A rating's distribution is keyed by the level index written as text. `judgment_setting_of_choice` gives the setting of the step's model, else of the deck's default, and raises `JudgmentModelMissingError` when neither names one, since the deck serves none by default. `served_judgment_model` gives the spec of the model a handle resolves to on this boot, or `None` when no backend serves one, a waterfall none of whose models is served included. `resolve_judgment_setting` then pins the setting to the handle the model resolves to; on a dry run, a model no backend serves on this boot keeps the deck's handle, since no judging worker is called.**Every entry point that renders a template takes a required `templating_style`** — `run_llm_text`, `run_llm_object`, `derive_structure_prompt`, `assemble_llm_prompt`, `assemble_img_gen_prompt`, `run_search`, `run_judgment`, `run_compose_template`. It is not nullable, and that is the contract: the Jinja2 filters that tag and format a value have no default of their own, so a call that omitted the style would render a prompt in a shape nobody chose. `resolve_templating_style(authored=...)` is what produces one — pass what the caller authored, or `None` to take the runtime default.diff --git a/docs/under-the-hood/reasoning-controls.md b/docs/under-the-hood/reasoning-controls.mdindex 2e1ccd428..617620a5b 100644--- a/docs/under-the-hood/reasoning-controls.md+++ b/docs/under-the-hood/reasoning-controls.md@@ -158,7 +158,7 @@ flowchart TBC -->|Anthropic| E["_build_thinking_params()<br>-> _ThinkingParams"]C -->|Google| F["_build_thinking_config()<br>-> ThinkingConfig"]C -->|Mistral| G["_resolve_reasoning_effort()<br>-> reasoning_effort"]- C -->|Bedrock (aiobotocore)| H["_validate_no_reasoning_params()<br>-> LLMCapabilityError if set"]+ C -->|Bedrock (aiobotocore)| H["check_request()<br>-> LLMCapabilityError if set"]```---@@ -439,9 +439,13 @@ The behavior of `ReasoningEffort.NONE` varies by provider:---+## Checked When the Method Loads++Every refusal below is raised by a worker's `check_request` classmethod, which reads only the model's spec and the job params and builds no SDK client. The worker runs it before every call, on text and structured outputs alike, and bundle validation runs the same check: when a method loads, each `PipeLLM` and `PipeStructure` resolves the setting its output is generated with (`model` for a single text, or a single `Dynamic` output, which a run generates as text unless its caller names another concept; `model_to_structure`, else `model`, else the deck's override or default for structured outputs, for anything else, a declared list of any concept included) to the model the deck serves, applies the model's constraints to the job params as the worker does, and calls the check its backend registered beside its worker factory. A refusal is an `llm_setting_refused_by_model` validation error on the field holding the setting, naming the pipe, the setting and the worker's reason, with the model named by its deck handle and never by its SDK or backend (an external plugin's refusal is shown as written only when the plugin raised it as caller-facing copy, and by its title otherwise), so `pipelex validate`, the API's validate route and a run all refuse the method before any credit is spent, where it used to validate as runnable and fail at the first call. A model no backend serves on the boot, or whose backend's SDK is not installed, is left to the run. A backend that registers no check, an external plugin's for instance, is held to the rule every worker shares: a model whose spec declares `thinking_mode = "none"` takes no reasoning setting.+## Error Handling-All reasoning-related errors use `LLMCapabilityError` (`pipelex/cogt/exceptions.py`):+All reasoning-related errors use `LLMCapabilityError` (`pipelex/cogt/exceptions.py`), raised by the worker's `check_request` before the call and, when the method loads, reported as an `llm_setting_refused_by_model` validation error:| Scenario | Error ||----------|-------|@@ -477,6 +481,9 @@ All reasoning-related errors use `LLMCapabilityError` (`pipelex/cogt/exceptions.| `pipelex/providers/google/google_llm_worker.py` | Google thinking config builder || `pipelex/providers/mistral/mistral_llm_worker.py` | Mistral reasoning effort resolution || `pipelex/providers/bedrock/bedrock_llm_worker.py` | Bedrock reasoning validation |+| `pipelex/cogt/llm/llm_worker_abstract.py` | `check_request()`, the shared rule each worker overrides and runs before every call, and `constrained_job_params()` |+| `pipelex/kernel/llm_ops.py` | `check_llm_setting_with_served_model()`: a setting checked against the model it resolves to, with the check its backend registered |+| `pipelex/pipe_operators/shared/llm_setting_check.py` | The load-time `llm_setting_refused_by_model` refusal of a `PipeLLM` or `PipeStructure` || `pipelex/pipelex.toml` | Default effort-to-budget maps and effort-to-level maps |---diff --git a/docs/under-the-hood/writing-an-inference-plugin.md b/docs/under-the-hood/writing-an-inference-plugin.mdindex 9b0c903ae..7b20707ea 100644--- a/docs/under-the-hood/writing-an-inference-plugin.md+++ b/docs/under-the-hood/writing-an-inference-plugin.md@@ -122,6 +122,8 @@ A plugin is any object with a `name`, a `targets_api` and a `register` method. ``add_inference_backend` registers a worker factory for one pair of family and `sdk` token, here the LLM family and `hello`. When a pipe first calls a model whose `sdk` is `hello`, Pipelex calls the factory with four keyword arguments: the resolved model spec, the backend's configuration, the process-wide cache of SDK clients, and the reporting delegate. The hello worker needs only the first and the last. The factory imports the worker module inside its body, so discovering the plugin imports nothing heavy.+An LLM backend may also pass `check_llm_request`, a callable delegating to its worker's `check_request`, the check the worker runs before every call: bundle validation then runs it against the model a pipe's setting resolves to, so a method naming a setting the model refuses is refused when it loads ([Inference Backend Plugins](inference-backend-plugins.md#registering-an-inference-backend) shows one). The hello plugin registers none, so it is held to the rule every worker shares: a model whose spec declares `thinking_mode = "none"` takes no reasoning setting.+`add_model_lister` is optional. It registers the callable behind `pipelex show models`, which Pipelex awaits when you list the models of a backend whose models use the `hello` token.The registrar offers two more menu methods, which this plugin does not need: `add_internal_model` declares a model in the `internal` backend, and `add_doc_gen_default` declares the model deck's default document engine for a format and source. A document engine uses them to ship its models with its code rather than in a backend file, as [Document Engine Plugins](document-engine-plugins.md#registering-an-engine) describes. The hello model stays in a backend file of its own, which Step 5 writes.diff --git a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.pyindex 7addf1fc0..7731c7afe 100644--- a/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py+++ b/pipelex/cli/dev_cli/commands/generate_corpus_vocabulary_cmd.py@@ -175,6 +175,13 @@ _ERROR_TYPE_EXCLUSIONS: dict[ValidationErrorType, str] = {"address-based reference to a package that is not installed fails as `unresolved_package_dependency` instead. ""Revisit if an entry can ever carry the packages it depends on."),+ PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL: (+ "It refuses a model setting the model it resolves to refuses, such as reasoning on a model that does not "+ "think, so the bundle that produces it must name a model the deck defines with that particular capability. "+ "The corpus rule that an entry names no model forbids exactly that: whether a model takes a setting is a "+ "fact of each consumer's deck, not of the language. "+ "Revisit if the corpus ever grows a deck axis."+ ),HintLintErrorType.HINT_UNKNOWN_KEY: _ADVISORY_HINT_LINT_EXCLUSION,HintLintErrorType.HINT_UNKNOWN_INTENT: _ADVISORY_HINT_LINT_EXCLUSION,HintLintErrorType.HINT_INAPPLICABLE_INTENT: _ADVISORY_HINT_LINT_EXCLUSION,diff --git a/pipelex/cogt/exceptions.py b/pipelex/cogt/exceptions.pyindex dca73f461..326c11f76 100644--- a/pipelex/cogt/exceptions.py+++ b/pipelex/cogt/exceptions.py@@ -382,6 +382,16 @@ class LLMCapabilityError(CogtError):error_category = InferenceErrorCategory.CONFIGURATION+class LLMSettingRefusedError(LLMCapabilityError):+ """A worker's refusal of an LLM setting, worded for the caller who wrote the setting.++ Its message names the model by its deck handle, never by the SDK, backend or provider model id a+ worker's own refusal carries, so a validation verdict can show it under strict disclosure.+ """++ _authors_caller_facing_message = True++class LLMCompletionError(CogtError):passdiff --git a/pipelex/cogt/llm/llm_worker_abstract.py b/pipelex/cogt/llm/llm_worker_abstract.pyindex 8fdfbbf97..563b55b5d 100644--- a/pipelex/cogt/llm/llm_worker_abstract.py+++ b/pipelex/cogt/llm/llm_worker_abstract.py@@ -13,6 +13,7 @@ from pipelex.cogt.exceptions import CogtError, LLMCapabilityErrorfrom pipelex.cogt.inference.inference_constants import InferenceOutputTypefrom pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstractfrom pipelex.cogt.inference.prompt_file_checks import check_prompt_documents_are_read, check_prompt_images_are_images+from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraintfrom pipelex.cogt.usage.token_category import TokenCategoryfrom pipelex.system.exceptions import JobMetadataError@@ -57,6 +58,68 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):InferenceWorkerAbstract.__init__(self, reporting_delegate=reporting_delegate)self.inference_model = inference_model+ #########################################################+ # Class methods+ #########################################################++ @classmethod+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None: # ruff: ignore[unused-class-method-argument]+ """Refuse a request this worker refuses before it calls its provider, from the model's spec and the job params alone.++ The worker runs it before every call, and bundle validation runs the same check against the+ model a pipe's setting resolves to, so a setting the model refuses is refused before a run+ spends anything. It reads nothing but its arguments and the config, and builds no SDK client.+ A worker that refuses more overrides it, from the same helpers its calls resolve the request+ with, so validation and the call never disagree. This base check holds for every worker: a+ model whose spec declares `thinking_mode = "none"` takes no reasoning setting.++ Args:+ inference_model: The spec of the model the request goes to.+ job_params: The job params the request sends, with the model's constraints applied.+ is_structured: Whether the request generates a structured output rather than text.++ Raises:+ LLMCapabilityError: When the worker refuses the request.++ """+ if inference_model.thinking_mode != ThinkingMode.NONE:+ return+ if job_params.reasoning_effort is not None or job_params.reasoning_budget is not None:+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"+ raise LLMCapabilityError(msg)++ @classmethod+ def constrained_job_params(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams) -> LLMJobParams | None:+ """The job params a request to the model sends once its spec's constraints are applied, `None` when none changes them.++ Args:+ inference_model: The spec of the model the request goes to.+ job_params: The job params the request was made with.++ Returns:+ A copy of the job params with the constraints applied, or None if no change was needed.++ """+ new_temperature = cls._scaled_temperature(inference_model=inference_model, temperature=job_params.temperature)+ has_changes = ListedConstraint.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in inference_model.listed_constraints+ fixed_temperature = inference_model.valued_constraints.get(ValuedConstraint.FIXED_TEMPERATURE)+ if fixed_temperature is not None and new_temperature != fixed_temperature:+ new_temperature = fixed_temperature+ has_changes = True++ if not has_changes:+ return None++ max_tokens = job_params.max_tokens or inference_model.max_tokens+ return job_params.model_copy(update={"temperature": new_temperature, "max_tokens": max_tokens})++ @classmethod+ def _scaled_temperature(cls, *, inference_model: InferenceModelSpec, temperature: float) -> float:+ """The temperature a request asks for once the model's scale is applied, before a fixed temperature replaces it."""+ if ListedConstraint.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in inference_model.listed_constraints:+ return temperature * 2+ return temperature+########################################################## Instance methods#########################################################@@ -348,8 +411,13 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):llm_job.llm_job_before_start(inference_model=self.inference_model)llm_job.applied_job_params = self._apply_constraints(llm_job=llm_job)+ @classmethod+ def _sent_job_params(cls, *, llm_job: LLMJob) -> LLMJobParams:+ """The job params the request sends: the constrained ones `_before_job` applied, else the job's own."""+ return llm_job.applied_job_params or llm_job.job_params+def _apply_constraints(self, llm_job: LLMJob) -> LLMJobParams | None:- """Apply constraints from the inference model to job params.+ """Apply constraints from the inference model to job params, warning when a fixed temperature replaces the one asked for.Args:llm_job: The LLM job containing the original job params@@ -358,29 +426,14 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):A copy of job_params with constraints applied, or None if no changes were needed"""- original_params = llm_job.job_params- new_temperature = original_params.temperature- max_tokens = original_params.max_tokens or self.inference_model.max_tokens- new_max_tokens = max_tokens- has_changes = False-- # Temperature constraints- if ListedConstraint.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2 in self.inference_model.listed_constraints:- new_temperature *= 2- has_changes = Truefixed_temperature = self.inference_model.valued_constraints.get(ValuedConstraint.FIXED_TEMPERATURE)- if fixed_temperature is not None and new_temperature != fixed_temperature:+ requested_temperature = self._scaled_temperature(inference_model=self.inference_model, temperature=llm_job.job_params.temperature)+ if fixed_temperature is not None and requested_temperature != fixed_temperature:log.warning(- f"Model {self.inference_model.desc} used with temperature {new_temperature}, "+ f"Model {self.inference_model.desc} used with temperature {requested_temperature}, "f"but it must be {fixed_temperature} for this model so we forced it to {fixed_temperature}")- new_temperature = fixed_temperature- has_changes = True-- if not has_changes:- return None-- return original_params.model_copy(update={"temperature": new_temperature, "max_tokens": new_max_tokens})+ return self.constrained_job_params(inference_model=self.inference_model, job_params=llm_job.job_params)async def _after_text_job(self,@@ -465,6 +518,7 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):# context is left alone, and it is what the line's standard trace fields name.with pipelex_span_active(span=span):try:+ self.check_request(inference_model=self.inference_model, job_params=self._sent_job_params(llm_job=llm_job), is_structured=False)text_result = await self._gen_text(llm_job=llm_job)await self._after_text_job(span=span, llm_job=llm_job, result_text=text_result)return text_result@@ -508,6 +562,7 @@ class LLMWorkerAbstract(InferenceWorkerAbstract, ABC):# context is left alone, and it is what the line's standard trace fields name.with pipelex_span_active(span=span):try:+ self.check_request(inference_model=self.inference_model, job_params=self._sent_job_params(llm_job=llm_job), is_structured=True)object_result = await self._gen_object(llm_job=llm_job, schema=schema)# Cleanup resultdiff --git a/pipelex/core/exceptions.py b/pipelex/core/exceptions.pyindex 55d6733e6..20499d66a 100644--- a/pipelex/core/exceptions.py+++ b/pipelex/core/exceptions.py@@ -150,7 +150,7 @@ class PipesAndConceptValidationErrorData(BaseModel):"so a fix planner can diff the two without file access",)- # === Unknown-model locators (for unknown_model errors) ===+ # === Model locators: all three on unknown_model errors, model_reference alone on llm_setting_refused_by_model errors ===model_reference: str | None = Field(default=None, description="The model reference exactly as the author wrote it")model_type: str | None = Field(default=None, description="The model type the field takes (llm, text_extractor, img_gen, search)")suggestions: list[str] | None = Field(diff --git a/pipelex/core/pipes/exceptions.py b/pipelex/core/pipes/exceptions.pyindex 70a92b415..40207ca7b 100644--- a/pipelex/core/pipes/exceptions.py+++ b/pipelex/core/pipes/exceptions.py@@ -187,6 +187,8 @@ class PipeValidationError(ValueError):redundant_input_name: str | None = None,dropped_input_marker: str | None = None,root_input_marker: str | None = None,+ field_name: str | None = None,+ model_reference: str | None = None,):self.error_type = error_typeself.domain_code = domain_code@@ -218,6 +220,10 @@ class PipeValidationError(ValueError):# Set together with `dropped_input_marker`: the marker the root declares, written the same way. The warning# compares the two markers' multiplicity and presence apart, so it names only the part the deletion drops.self.root_input_marker = root_input_marker+ # The pipe's field the refusal is about, set where one field is at fault (`model` or `model_to_structure`+ # for a model setting its model refuses), and the model reference that field holds, as the author wrote it.+ self.field_name = field_name+ self.model_reference = model_referenceself.file_path = file_pathself.explanation = explanationsuper().__init__(message)diff --git a/pipelex/kernel/llm_ops.py b/pipelex/kernel/llm_ops.pyindex 64a6d3d77..6555af22c 100644--- a/pipelex/kernel/llm_ops.py+++ b/pipelex/kernel/llm_ops.py@@ -20,9 +20,12 @@ from typing import Anyfrom pipelex import logfrom pipelex.cogt.content_generation.cogt_run_params import CogtRunParams-from pipelex.cogt.exceptions import ModelChoiceNotFoundError+from pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedError, ModelChoiceNotFoundError, ModelNotFoundErrorfrom pipelex.cogt.llm.llm_prompt import LLMPromptfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSetting+from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelTypefrom pipelex.cogt.models.model_reference import ModelReferenceKind, ensure_model_referencefrom pipelex.cogt.templating.template_rendering import render_templatefrom pipelex.config import get_config@@ -33,7 +36,8 @@ from pipelex.core.stuffs.stuff_content import StuffContentfrom pipelex.kernel.llm_prompt_content import LlmPromptContent, assemble_llm_promptfrom pipelex.kernel.llm_results import LlmObjectResult, LlmTextResult, StructuringPathfrom pipelex.kernel.memory_ops import store_result-from pipelex.runtime_hub import get_content_generator, get_model_deck+from pipelex.runtime_hub import get_content_generator, get_inference_backend_registry, get_model_deck+from pipelex.system.exceptions import MissingDependencyErrorfrom pipelex.system.job_metadata import JobMetadatafrom pipelex.tools.jinja2.template_category import TemplateCategoryfrom pipelex.tools.templating.templating_style import TemplatingStyle@@ -60,6 +64,61 @@ def resolve_llm_setting_for_object(*, llm_choice: LLMModelChoice | None = None,return model_deck.get_llm_setting(llm_choice=resolved_choice)+def served_llm_model(*, model_handle: str) -> InferenceModelSpec | None:+ """The spec of the LLM a handle resolves to on this boot, `None` when no backend serves one.++ An alias resolves to its target, a waterfall to its first member the deck serves, exactly as a run+ resolves them. The deck answers `None` for a handle it does not serve, but raises for a waterfall+ none of whose models it serves, or whose fallbacks are disabled: here the two mean the same thing.+ """+ try:+ return get_model_deck().get_optional_inference_model(model_handle=model_handle, model_type=ModelType.LLM)+ except ModelNotFoundError:+ return None+++def check_llm_setting_with_served_model(*, llm_setting: LLMSetting, is_structured: bool) -> None:+ """Refuse an LLM setting the model it resolves to refuses, before a run spends anything.++ The model's spec is checked by the request check its backend registered, which is the check its+ worker runs before every call, with the job params the setting gives once the model's constraints+ are applied: a reasoning setting the model's thinking mode refuses, a reasoning budget where it takes+ only an effort, a thinking budget its max_tokens cannot hold, or a structured output its worker cannot+ generate. A backend that registered no check is held to the rule every worker shares. A model no+ backend serves on this boot, or whose backend's SDK is not installed, is left to the run, whose+ refusal names it.++ Args:+ llm_setting: The setting a step generates with, its model a handle, an alias or a waterfall.+ is_structured: Whether the step generates a structured output rather than text.++ Raises:+ LLMSettingRefusedError: A built-in worker's refusal, naming the model by its deck handle and what it refuses.+ LLMCapabilityError: An external plugin's refusal, as the plugin raised it.++ """+ inference_model = served_llm_model(model_handle=llm_setting.model)+ if inference_model is None:+ return+ job_params = llm_setting.make_llm_job_params()+ job_params = LLMWorkerAbstract.constrained_job_params(inference_model=inference_model, job_params=job_params) or job_params+ registered_check = get_inference_backend_registry().lookup_llm_request_check(sdk=inference_model.sdk)+ check_request = registered_check.check if registered_check else LLMWorkerAbstract.check_request+ try:+ check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)+ except MissingDependencyError:+ # The backend's SDK is not installed here, so no worker for the model can be built: the run says so+ log.verbose(f"Model '{inference_model.desc}' was not checked: its backend's SDK is not installed")+ except LLMCapabilityError as refusal:+ if registered_check and not registered_check.is_builtin:+ # An external plugin's text may carry what it keeps private: it reaches the caller only if the plugin vouched for it+ raise+ # A built-in worker names the model by its description, which carries the SDK, the backend and the+ # provider's model id: the caller who wrote the setting knows the model by its deck handle alone.+ msg = str(refusal).replace(inference_model.desc, inference_model.name)+ raise LLMSettingRefusedError(msg) from refusal++# A resolution chain is at most a handful of hops (preset -> alias -> handle); this only# has to stop a malformed deck that points an alias back at itself._MAX_MODEL_RESOLUTION_HOPS = 8diff --git a/pipelex/mthds_parsing/handle_pipe_errors.py b/pipelex/mthds_parsing/handle_pipe_errors.pyindex a308a44f0..e8374f1f1 100644--- a/pipelex/mthds_parsing/handle_pipe_errors.py+++ b/pipelex/mthds_parsing/handle_pipe_errors.py@@ -205,19 +205,24 @@ def categorize_pipe_validation_with_libraries_error():required_refs = ", ".join(pipe_error.required_concept_codes)message += f" (required: {required_refs}, provided: {pipe_error.provided_concept_code})"+ # A refusal about one of the pipe's fields is located on it, as an unknown model is; any other keeps the file path+ field_path = pipe_error.file_path or ""+ if pipe_error.field_name and pipe_error.pipe_code:+ field_path = f"pipe.{pipe_error.pipe_code}.{pipe_error.field_name}"return PipesAndConceptValidationErrorData(error_type=error_type,domain_code=pipe_error.domain_code,source=pipe_error.file_path,pipe_code=pipe_error.pipe_code,concept_code=None, # This is a pipe error, not a concept error- field_name=None, # Field name is not provided in PipeValidationError+ field_name=pipe_error.field_name,message=message,- field_path=pipe_error.file_path or "",+ field_path=field_path,variable_names=pipe_error.variable_names,expected_output_ref=pipe_error.expected_output_ref,expected_inputs=pipe_error.expected_inputs,declared_inputs=pipe_error.declared_inputs,+ model_reference=pipe_error.model_reference,)diff --git a/pipelex/pipe_operators/llm/pipe_llm.py b/pipelex/pipe_operators/llm/pipe_llm.pyindex 971499e3b..e5323da9f 100644--- a/pipelex/pipe_operators/llm/pipe_llm.py+++ b/pipelex/pipe_operators/llm/pipe_llm.py@@ -5,7 +5,7 @@ from typing_extensions import overridefrom pipelex import logfrom pipelex.base_exceptions import iter_cause_chain-from pipelex.cogt.exceptions import LLMCompletionError+from pipelex.cogt.exceptions import LLMCompletionError, ModelChoiceNotFoundErrorfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSetting, LLMSettingChoicesfrom pipelex.cogt.models.model_deck_check import check_llm_choice_with_deckfrom pipelex.cogt.models.model_reference import ModelReference@@ -33,6 +33,7 @@ from pipelex.pipe_machinery.template_guard_lint import lint_authored_templatefrom pipelex.pipe_machinery.validation import is_input_used_by_variablesfrom pipelex.pipe_operators.llm.llm_prompt_blueprint import LLMPromptBlueprintfrom pipelex.pipe_operators.pipe_operator import PipeOperator+from pipelex.pipe_operators.shared.llm_setting_check import refuse_llm_setting_its_model_refusesfrom pipelex.pipe_run.pipe_run_params import (PipeRunParams,output_multiplicity_to_apply,@@ -133,10 +134,8 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):# and PipeLLM is not the only one with this kind of constraints# Allow Dynamic output concept as it's flexible and can represent anything- if NativeConceptCode.is_dynamic_concept(concept_code=self.output.concept.code):- return-- if get_concept_library().is_compatible(+ is_dynamic_output = NativeConceptCode.is_dynamic_concept(concept_code=self.output.concept.code)+ if not is_dynamic_output and get_concept_library().is_compatible(tested_concept=self.output.concept,wanted_concept=get_native_concept(native_concept=NativeConceptCode.IMAGE),):@@ -153,6 +152,65 @@ class PipeLLM(PipeOperator[PipeLLMOutput]):provided_concept_code=self.output.concept.concept_ref,)+ self._refuse_a_setting_its_model_refuses(is_dynamic_output=is_dynamic_output)++ def _refuse_a_setting_its_model_refuses(self, *, is_dynamic_output: bool) -> None:+ """Refuse the model setting this pipe generates its output with when the model it resolves to refuses it.++ A single text is generated with the `model` setting, any other output with the setting for objects:+ `model_to_structure`, else `model`, else the deck's override or default for structured outputs. A+ declared multiplicity sends any output down the object path, a `Dynamic` one included. A single+ `Dynamic` output is checked as text, its default, since the concept it stands for is only known when+ the pipe runs, and a text output a run asks to multiply is generated as objects, which only that run+ knows. A reference the deck does not define is refused when the pipe is built, so it is not looked up+ again here.+ """+ llm_for_text_choice = self.llm_choices.for_text if self.llm_choices else None+ llm_for_object_choice = self.llm_choices.for_object if self.llm_choices else None+ is_structured = not self._generates_single_text(is_dynamic_output=is_dynamic_output)+ llm_choice: LLMModelChoice | None+ field_name: str | None+ try:+ if is_structured:+ llm_setting = resolve_llm_setting_for_object(llm_choice=llm_for_object_choice, llm_choice_for_text=llm_for_text_choice)+ if llm_for_object_choice is not None:+ llm_choice, field_name = llm_for_object_choice, "model_to_structure"+ elif llm_for_text_choice is not None:+ llm_choice, field_name = llm_for_text_choice, "model"+ else:+ llm_choice, field_name = None, None+ else:+ llm_setting = resolve_llm_setting_for_text(llm_choice=llm_for_text_choice)+ llm_choice = llm_for_text_choice+ field_name = "model" if llm_for_text_choice is not None else None+ except ModelChoiceNotFoundError:+ return+ refuse_llm_setting_its_model_refuses(+ pipe_type=self.class_name,+ pipe_code=self.code,+ domain_code=self.domain_code,+ llm_setting=llm_setting,+ llm_choice=llm_choice,+ field_name=field_name,+ is_structured=is_structured,+ )++ def _generates_single_text(self, *, is_dynamic_output: bool) -> bool:+ """Whether the pipe's declared output is generated as one text, on the text path, rather than as objects.++ A single `Dynamic` output counts as text, the concept a run resolves it to when its caller names none.+ """+ is_multiple_output = output_multiplicity_to_apply(+ base_multiplicity=self.output_multiplicity, override_multiplicity=None+ ).is_multiple_outputs_enabled+ if is_multiple_output:+ return False+ return is_dynamic_output or get_concept_library().is_compatible(+ tested_concept=self.output.concept,+ wanted_concept=get_native_concept(NativeConceptCode.TEXT),+ strict=True,+ )+@overridedef needed_inputs(self, *, visited_pipes: set[str] | None = None) -> InputStuffSpecs:needed_inputs = InputStuffSpecsFactory.make_empty()diff --git a/pipelex/pipe_operators/shared/llm_setting_check.py b/pipelex/pipe_operators/shared/llm_setting_check.pynew file mode 100644index 000000000..aaad83ca9--- /dev/null+++ b/pipelex/pipe_operators/shared/llm_setting_check.py@@ -0,0 +1,71 @@+"""The load-time refusal of an LLM setting the model it resolves to refuses, shared by the operators that generate with one."""++from pipelex.cogt.exceptions import LLMCapabilityError+from pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSetting+from pipelex.cogt.models.model_reference import ensure_model_reference+from pipelex.core.pipes.exceptions import PipeValidationError, caller_facing_refusal_text+from pipelex.kernel.llm_ops import check_llm_setting_with_served_model+from pipelex.runtime_hub import get_model_deck+from pipelex.validation_error_types import PipeValidationErrorType+++def refuse_llm_setting_its_model_refuses(+ *,+ pipe_type: str,+ pipe_code: str,+ domain_code: str,+ llm_setting: LLMSetting,+ llm_choice: LLMModelChoice | None,+ field_name: str | None,+ is_structured: bool,+) -> None:+ """Refuse a step's LLM setting when the model it resolves to refuses it for the output the step generates.++ The check is the one the model's worker runs before every call, so a step that would fail at its first+ call, a structured output on a reasoning preset the model cannot take for instance, is refused when the+ method loads, before a run spends anything. A model no backend serves on this boot is left to the run.++ Args:+ pipe_type: The step's pipe type, for the message.+ pipe_code: The step's pipe code.+ domain_code: The step's domain code.+ llm_setting: The setting the step generates with, resolved from its choice or the deck's.+ llm_choice: The choice the step names in `field_name`, or None when the setting is the deck's override or default.+ field_name: The step's field that names the choice, or None when the setting is the deck's override or default.+ is_structured: Whether the step generates a structured output rather than text.++ Raises:+ PipeValidationError: An `llm_setting_refused_by_model` refusal, located on the field that names the setting.++ """+ try:+ check_llm_setting_with_served_model(llm_setting=llm_setting, is_structured=is_structured)+ except LLMCapabilityError as refusal:+ output_desc = "a structured output" if is_structured else "text"+ model_reference: str | None = None+ if llm_choice is None or field_name is None:+ # The deck's chain reads its override before its default, so the remedy names the table that supplied the setting.+ deck_overrides = get_model_deck().llm_choice_overrides+ deck_override = deck_overrides.for_object if is_structured else deck_overrides.for_text+ deck_rung, deck_table = ("override", "llm.choice_overrides") if deck_override is not None else ("default setting", "llm.choice_defaults")+ deck_key = "for_object" if is_structured else "for_text"+ output_kind = "structured outputs" if is_structured else "text"+ setting_desc = f"the model deck's {deck_rung} for {output_kind}"+ remedy = f"Name a model setting in the pipe, or change `{deck_key}` in the deck's `[{deck_table}]`."+ elif isinstance(llm_choice, LLMSetting):+ setting_desc = f"the model setting its `{field_name}` writes inline"+ remedy = f"Change the setting in `{field_name}`, or name a model that takes it."+ else:+ model_reference = ensure_model_reference(llm_choice).raw+ setting_desc = f"the model setting `{model_reference}` its `{field_name}` names"+ remedy = f"Name another setting in `{field_name}`, or one whose model takes it."+ reason = caller_facing_refusal_text(refusal=refusal).rstrip(".")+ msg = f"{pipe_type} '{pipe_code}' generates {output_desc} with {setting_desc}, which the model it resolves to refuses: {reason}. {remedy}"+ raise PipeValidationError(+ message=msg,+ error_type=PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL,+ domain_code=domain_code,+ pipe_code=pipe_code,+ field_name=field_name,+ model_reference=model_reference,+ ) from refusaldiff --git a/pipelex/pipe_operators/structure/pipe_structure.py b/pipelex/pipe_operators/structure/pipe_structure.pyindex 322d34e56..32d67a223 100644--- a/pipelex/pipe_operators/structure/pipe_structure.py+++ b/pipelex/pipe_operators/structure/pipe_structure.py@@ -3,7 +3,7 @@ from typing import Any, Literalfrom typing_extensions import overridefrom pipelex import log-from pipelex.cogt.exceptions import LLMCompletionError+from pipelex.cogt.exceptions import LLMCompletionError, ModelChoiceNotFoundErrorfrom pipelex.cogt.llm.llm_prompt import LLMPromptfrom pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSettingfrom pipelex.cogt.models.model_deck_check import check_llm_choice_with_deck@@ -22,6 +22,7 @@ from pipelex.kernel.llm_ops import concrete_llm_model_handle, derive_structure_pfrom pipelex.kernel.memory_ops import store_resultfrom pipelex.kernel.templating_style_ops import resolve_templating_stylefrom pipelex.pipe_operators.pipe_operator import PipeOperator+from pipelex.pipe_operators.shared.llm_setting_check import refuse_llm_setting_its_model_refusesfrom pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_applyfrom pipelex.runtime_hub import get_class_registryfrom pipelex.system.job_metadata import JobMetadata@@ -97,6 +98,21 @@ class PipeStructure(PipeOperator[PipeStructureOutput]):provided_concept_code=self.output.concept.concept_ref,)+ # A reference the deck does not define is refused when the pipe is built, so it is not looked up again here+ try:+ llm_setting_for_object = resolve_llm_setting_for_object(llm_choice=self.llm_choice)+ except ModelChoiceNotFoundError:+ return+ refuse_llm_setting_its_model_refuses(+ pipe_type=self.class_name,+ pipe_code=self.code,+ domain_code=self.domain_code,+ llm_setting=llm_setting_for_object,+ llm_choice=self.llm_choice,+ field_name="model" if self.llm_choice is not None else None,+ is_structured=True,+ )+@overrideasync def _live_run_operator_pipe(self,diff --git a/pipelex/plugins/inference_backend_registry.py b/pipelex/plugins/inference_backend_registry.pyindex edcf4a347..220bbe8ee 100644--- a/pipelex/plugins/inference_backend_registry.py+++ b/pipelex/plugins/inference_backend_registry.py@@ -1,12 +1,17 @@import importlib.utilfrom collections.abc import Callable, Sequence+from dataclasses import dataclassfrom enum import StrEnum-from typing import TypeAlias+from typing import TYPE_CHECKING, Protocol, TypeAliasfrom pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstractfrom pipelex.plugins.exceptions import InferenceBackendNotFoundErrorfrom pipelex.system.exceptions import MissingDependencyError+if TYPE_CHECKING:+ from pipelex.cogt.llm.llm_job_components import LLMJobParams+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+class InferenceFamily(StrEnum):LLM = "llm"@@ -28,6 +33,35 @@ class InferenceFamily(StrEnum):MakeWorkerFn: TypeAlias = Callable[..., InferenceWorkerAbstract]+class CheckLLMRequestFn(Protocol):+ """The checks the LLM worker a backend builds applies to a request before calling its provider.++ A backend plugin registers one beside the ``make_worker`` of an LLM sdk, and bundle validation calls it+ with the spec of the model a pipe's setting resolves to, so a setting the worker would refuse is refused+ when the method loads, before a run spends anything. Like ``make_worker`` it is import-light to+ reference and imports its worker only when called; it builds no SDK client. It delegates to the+ worker class's own ``check_request``, the check the worker runs before every call, so the two never+ disagree. An LLM sdk that registers none is checked against ``LLMWorkerAbstract.check_request``, the+ rule every worker shares.++ A refusal is an ``LLMCapabilityError``, and a validation verdict shows it to whoever wrote the setting.+ A built-in backend's refusal is shown with the model named by its deck handle, since this library writes+ those messages. An external plugin's refusal is shown as written only when the plugin raises it as+ caller-facing copy (``as_caller_fault()``), vouching that it names nothing the plugin keeps private;+ any other is named by its title alone.+ """++ def __call__(self, *, inference_model: "InferenceModelSpec", job_params: "LLMJobParams", is_structured: bool) -> None: ...+++@dataclass(frozen=True)+class LLMRequestCheck:+ """A registered request check, and whether a built-in plugin registered it, which decides how its refusals are shown."""++ check: CheckLLMRequestFn+ is_builtin: bool++def require_sdk(*, spec: str | Sequence[str], extra: str, msg: str, dependency_name: str | None = None) -> None:"""Raise ``MissingDependencyError`` if any of ``spec`` is not importable.@@ -69,8 +103,13 @@ class InferenceBackendRegistry:strings."""- def __init__(self, backends: dict[tuple[InferenceFamily, str], MakeWorkerFn]):+ def __init__(+ self,+ backends: dict[tuple[InferenceFamily, str], MakeWorkerFn],+ llm_request_checks: dict[str, LLMRequestCheck] | None = None,+ ):self._backends: dict[tuple[InferenceFamily, str], MakeWorkerFn] = dict(backends)+ self._llm_request_checks: dict[str, LLMRequestCheck] = dict(llm_request_checks or {})def lookup(self, *, family: InferenceFamily, sdk: str) -> MakeWorkerFn:make_worker = self._backends.get((family, sdk))@@ -78,6 +117,10 @@ class InferenceBackendRegistry:raise InferenceBackendNotFoundError(family=family, sdk=sdk)return make_worker+ def lookup_llm_request_check(self, *, sdk: str) -> LLMRequestCheck | None:+ """The request check the LLM backend serving `sdk` registered, `None` when it registered none."""+ return self._llm_request_checks.get(sdk)+def has(self, *, family: InferenceFamily, sdk: str) -> bool:return (family, sdk) in self._backends@@ -88,7 +131,7 @@ class InferenceBackendRegistry:"""kept = {key: make_worker for key, make_worker in self._backends.items() if key[0] != family}kept.update({(family, sdk): make_worker for sdk, make_worker in backends.items()})- return InferenceBackendRegistry(kept)+ return InferenceBackendRegistry(kept, llm_request_checks=self._llm_request_checks)@propertydef keys(self) -> list[tuple[InferenceFamily, str]]:diff --git a/pipelex/plugins/registrar.py b/pipelex/plugins/registrar.pyindex afe832f8f..87f0d7e3a 100644--- a/pipelex/plugins/registrar.py+++ b/pipelex/plugins/registrar.py@@ -26,7 +26,7 @@ from pipelex.plugins.exceptions import (PluginLayerViolationError,ReservedServiceErrorCodeError,)-from pipelex.plugins.inference_backend_registry import InferenceFamily, MakeWorkerFn+from pipelex.plugins.inference_backend_registry import CheckLLMRequestFn, InferenceFamily, LLMRequestCheck, MakeWorkerFnfrom pipelex.plugins.log_sink_registry import LogSinkFactoryFnfrom pipelex.plugins.model_lister_registry import ListModelsFnfrom pipelex.plugins.orchestrator_registry import OrchestratorProtocol@@ -166,6 +166,7 @@ class PluginRegistrar:# unit test can build a registrar without naming one.self.boot_orchestrator = boot_orchestratorself.inference_backends: dict[tuple[InferenceFamily, str], MakeWorkerFn] = {}+ self.llm_request_checks: dict[str, LLMRequestCheck] = {}self.model_listers: dict[str, ListModelsFn] = {}self.orchestrators: dict[OrchestrationMode, OrchestratorProtocol] = {}self.bundle_validators: dict[OrchestrationMode, BundleValidatorProtocol] = {}@@ -214,7 +215,22 @@ class PluginRegistrar:# Menu methods — the only surface a plugin's register() may call# ------------------------------------------------------------------ #- def add_inference_backend(self, *, family: InferenceFamily, sdk: str, make_worker: MakeWorkerFn) -> None:+ def add_inference_backend(+ self,+ *,+ family: InferenceFamily,+ sdk: str,+ make_worker: MakeWorkerFn,+ check_llm_request: CheckLLMRequestFn | None = None,+ ) -> None:+ """Register the worker factory serving one sdk of one inference family.++ ``check_llm_request`` is read for the LLM family only: the check the worker ``make_worker`` builds+ applies to a request before calling its provider, which bundle validation runs against the model a+ pipe's setting resolves to (see ``CheckLLMRequestFn``). The check is recorded with the registering+ plugin's origin, which decides how its refusals are shown to a caller. A duplicate backend is refused+ before its check is recorded, so a refused duplicate leaves no check behind.+ """self._add(store=self.inference_backends,sources=self._inference_sources,@@ -225,6 +241,12 @@ class PluginRegistrar:family=family, sdk=sdk, first_plugin=first_plugin, second_plugin=second_plugin),)+ match family:+ case InferenceFamily.LLM:+ if check_llm_request is not None:+ self.llm_request_checks[sdk] = LLMRequestCheck(check=check_llm_request, is_builtin=self._active.origin == PluginOrigin.BUILTIN)+ case InferenceFamily.IMG_GEN | InferenceFamily.EXTRACT | InferenceFamily.SEARCH | InferenceFamily.DOC_GEN | InferenceFamily.JUDGMENT:+ passdef add_model_lister(self, *, sdk: str, lister: ListModelsFn) -> None:self._add(diff --git a/pipelex/providers/anthropic/anthropic_llm_worker.py b/pipelex/providers/anthropic/anthropic_llm_worker.pyindex 7d52cc2c6..500f4f6a2 100644--- a/pipelex/providers/anthropic/anthropic_llm_worker.py+++ b/pipelex/providers/anthropic/anthropic_llm_worker.py@@ -120,28 +120,51 @@ class AnthropicLLMWorker(LLMWorkerAbstract):# Instance methods#########################################################- def _build_thinking_params(self, job_params: LLMJobParams, *, max_tokens: int) -> _ThinkingParams:+ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse a reasoning setting the model's thinking cannot take, or a thinking budget the call's max_tokens cannot hold."""+ requested_max_tokens = job_params.max_tokens or inference_model.max_tokens+ max_tokens = (+ None if requested_max_tokens is None else cls._sent_max_tokens(requested_max_tokens=requested_max_tokens, is_structured=is_structured)+ )+ cls._build_thinking_params(inference_model=inference_model, job_params=job_params, max_tokens=max_tokens)++ @classmethod+ def _sent_max_tokens(cls, *, requested_max_tokens: int, is_structured: bool) -> int:+ """The max_tokens a call sends: the one requested, capped on a structured output at what its timeout allows.++ A structured call sets an explicit timeout, which disables the SDK's long-request protection, so its+ max_tokens is held to what the SDK's own heuristic lets that timeout produce.+ """+ if not is_structured:+ return requested_max_tokens+ timeout_seconds = get_config().inference.llm.anthropic.structured_output_timeout_seconds+ safe_max_tokens = AnthropicFactory.calculate_safe_max_tokens_for_timeout(timeout_seconds=timeout_seconds)+ return min(requested_max_tokens, safe_max_tokens)++ @classmethod+ def _build_thinking_params(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, max_tokens: int | None) -> _ThinkingParams:"""Build thinking-related SDK parameters from job params and model spec.Args:+ inference_model: The spec of the model the request goes to.job_params: The LLM job parameters containing reasoning_effort/reasoning_budget.- max_tokens: The effective max_tokens for this request.+ max_tokens: The max_tokens this request sends, or None when no worker for the model can be built without one.Returns:A _ThinkingParams container with thinking, output_config, and suppress_temperature."""- thinking_mode = self.inference_model.thinking_mode-# Case 1: reasoning_effort is setif job_params.reasoning_effort is not None:effort = job_params.reasoning_effort- return self._build_thinking_params_for_effort(thinking_mode=thinking_mode, effort=effort, max_tokens=max_tokens)+ return cls._build_thinking_params_for_effort(inference_model=inference_model, effort=effort, max_tokens=max_tokens)# Case 2: reasoning_budget is setif job_params.reasoning_budget is not None:budget = job_params.reasoning_budget- return self._build_thinking_params_for_budget(thinking_mode=thinking_mode, budget=budget, max_tokens=max_tokens)+ return cls._build_thinking_params_for_budget(inference_model=inference_model, budget=budget, max_tokens=max_tokens)# Case 3: neither reasoning_effort nor reasoning_budget is setreturn _ThinkingParams(@@ -150,15 +173,16 @@ class AnthropicLLMWorker(LLMWorkerAbstract):suppress_temperature=False,)+ @classmethoddef _build_thinking_params_for_effort(- self,- thinking_mode: ThinkingMode,+ cls,*,+ inference_model: InferenceModelSpec,effort: ReasoningEffort,- max_tokens: int,+ max_tokens: int | None,) -> _ThinkingParams:"""Build thinking params when reasoning_effort is specified."""- match thinking_mode:+ match inference_model.thinking_mode:case ThinkingMode.ADAPTIVE:anthropic_effort = get_config().inference.llm.anthropic.get_reasoning_level(effort=effort)if anthropic_effort is None:@@ -186,15 +210,15 @@ class AnthropicLLMWorker(LLMWorkerAbstract):suppress_temperature=False,)budget = get_config().inference.llm.get_reasoning_budget(- family=self.reasoning_budget_family,+ family=cls.reasoning_budget_family,effort=effort,)safe_budget = fit_thinking_budget(budget=budget,max_tokens=max_tokens,- min_budget=self.inference_model.min_thinking_budget,- max_budget=self.inference_model.max_thinking_budget,- model_desc=self.inference_model.desc,+ min_budget=inference_model.min_thinking_budget,+ max_budget=inference_model.max_thinking_budget,+ model_desc=inference_model.desc,)log.verbose(f"Anthropic manual thinking with budget_tokens={safe_budget} (from effort={effort})")thinking_config = {"type": "enabled", "budget_tokens": safe_budget}@@ -204,21 +228,22 @@ class AnthropicLLMWorker(LLMWorkerAbstract):suppress_temperature=True,)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)+ @classmethoddef _build_thinking_params_for_budget(- self,- thinking_mode: ThinkingMode,+ cls,*,+ inference_model: InferenceModelSpec,budget: int,- max_tokens: int,+ max_tokens: int | None,) -> _ThinkingParams:"""Build thinking params when reasoning_budget is specified."""- match thinking_mode:+ match inference_model.thinking_mode:case ThinkingMode.ADAPTIVE:msg = (- f"Model '{self.inference_model.desc}' uses adaptive thinking which does not support reasoning_budget. "+ f"Model '{inference_model.desc}' uses adaptive thinking which does not support reasoning_budget. "f"Use reasoning_effort instead (e.g. reasoning_effort='high')")raise LLMCapabilityError(msg)@@ -226,9 +251,9 @@ class AnthropicLLMWorker(LLMWorkerAbstract):safe_budget = fit_thinking_budget(budget=budget,max_tokens=max_tokens,- min_budget=self.inference_model.min_thinking_budget,- max_budget=self.inference_model.max_thinking_budget,- model_desc=self.inference_model.desc,+ min_budget=inference_model.min_thinking_budget,+ max_budget=inference_model.max_thinking_budget,+ model_desc=inference_model.desc,)log.verbose(f"Anthropic thinking with explicit budget_tokens={safe_budget}")thinking_config: ThinkingConfigParam = {"type": "enabled", "budget_tokens": safe_budget}@@ -238,7 +263,7 @@ class AnthropicLLMWorker(LLMWorkerAbstract):suppress_temperature=True,)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)@override@@ -248,9 +273,9 @@ class AnthropicLLMWorker(LLMWorkerAbstract):) -> str:job_params = llm_job.applied_job_params or llm_job.job_paramsmessage = await AnthropicFactory.make_user_message(llm_job=llm_job)- max_tokens = job_params.max_tokens or self.default_max_tokens+ max_tokens = self._sent_max_tokens(requested_max_tokens=job_params.max_tokens or self.default_max_tokens, is_structured=False)- thinking_params = self._build_thinking_params(job_params=job_params, max_tokens=max_tokens)+ thinking_params = self._build_thinking_params(inference_model=self.inference_model, job_params=job_params, max_tokens=max_tokens)log.verbose(thinking_params, title="Thinking params")log.verbose(max_tokens, title="Max tokens")sends_temperature = self.inference_model.accepts_temperature and not thinking_params.suppress_temperature@@ -377,19 +402,12 @@ class AnthropicLLMWorker(LLMWorkerAbstract):job_params = llm_job.applied_job_params or llm_job.job_paramsmessages = await AnthropicFactory.make_simple_messages(llm_job=llm_job)- # Get Anthropic-specific config for structured output- anthropic_config = get_config().inference.llm.anthropic- timeout_seconds = anthropic_config.structured_output_timeout_seconds-- # Calculate safe max_tokens based on timeout- safe_max_tokens = AnthropicFactory.calculate_safe_max_tokens_for_timeout(timeout_seconds=timeout_seconds)-- # Use minimum of requested and safe limit- requested_max_tokens = job_params.max_tokens or self.default_max_tokens- effective_max_tokens = min(requested_max_tokens, safe_max_tokens)+ # The structured call sets an explicit timeout, and its max_tokens is held to what that timeout allows+ timeout_seconds = get_config().inference.llm.anthropic.structured_output_timeout_seconds+ effective_max_tokens = self._sent_max_tokens(requested_max_tokens=job_params.max_tokens or self.default_max_tokens, is_structured=True)# The thinking budget is fitted against the max_tokens this call actually sends- thinking_params = self._build_thinking_params(job_params=job_params, max_tokens=effective_max_tokens)+ thinking_params = self._build_thinking_params(inference_model=self.inference_model, job_params=job_params, max_tokens=effective_max_tokens)log.verbose(thinking_params, title="Thinking params")sends_temperature = self.inference_model.accepts_temperature and not thinking_params.suppress_temperaturediff --git a/pipelex/providers/anthropic/anthropic_plugin.py b/pipelex/providers/anthropic/anthropic_plugin.pyindex 7e9aa776a..9babdde13 100644--- a/pipelex/providers/anthropic/anthropic_plugin.py+++ b/pipelex/providers/anthropic/anthropic_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -40,6 +41,14 @@ def _make_anthropic_worker()+def _check_anthropic_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ require_sdk(spec="anthropic", extra="anthropic", msg=_ANTHROPIC_MISSING_MSG)++ from pipelex.providers.anthropic.anthropic_llm_worker import AnthropicLLMWorker # ruff: ignore[import-outside-top-level]++ AnthropicLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++async def _list_anthropic_models(*,sdk: str,@@ -67,6 +76,10 @@ class AnthropicPlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="anthropic", make_worker=_make_anthropic_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="bedrock_anthropic", make_worker=_make_anthropic_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="anthropic", make_worker=_make_anthropic_worker, check_llm_request=_check_anthropic_request+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="bedrock_anthropic", make_worker=_make_anthropic_worker, check_llm_request=_check_anthropic_request+ )registrar.add_model_lister(sdk="anthropic", lister=_list_anthropic_models)diff --git a/pipelex/providers/bedrock/bedrock_llm_worker.py b/pipelex/providers/bedrock/bedrock_llm_worker.pyindex 117129f50..62671d0ff 100644--- a/pipelex/providers/bedrock/bedrock_llm_worker.py+++ b/pipelex/providers/bedrock/bedrock_llm_worker.py@@ -43,14 +43,22 @@ class BedrockLLMWorker(LLMWorkerAbstract):raise BedrockWorkerConfigurationError(msg)self.bedrock_client_for_text = sdk_instance- def _validate_no_reasoning_params(self, job_params: LLMJobParams) -> None:- """Validate that no reasoning parameters are set for Bedrock native models."""+ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse every reasoning setting, and every structured output: Bedrock native models take neither."""if job_params.reasoning_effort is not None or job_params.reasoning_budget is not None:msg = (- f"Model '{self.inference_model.desc}' does not support reasoning parameters; "+ f"Model '{inference_model.desc}' does not support reasoning parameters; ""Bedrock native models do not support reasoning_effort or reasoning_budget")raise LLMCapabilityError(msg)+ if is_structured:+ raise LLMCapabilityError(cls._structured_output_refusal(inference_model=inference_model))++ @classmethod+ def _structured_output_refusal(cls, *, inference_model: InferenceModelSpec) -> str:+ return f"Model '{inference_model.desc}' does not support structured outputs; Bedrock native models generate text only"@overrideasync def _gen_text(@@ -58,7 +66,6 @@ class BedrockLLMWorker(LLMWorkerAbstract):llm_job: LLMJob,) -> str:job_params = llm_job.applied_job_params or llm_job.job_params- self._validate_no_reasoning_params(job_params=job_params)message = BedrockFactory.make_simple_message(llm_job=llm_job)log.verbose(self.inference_model.model_id)@@ -93,6 +100,5 @@ class BedrockLLMWorker(LLMWorkerAbstract):*,schema: type[BaseModelTypeVar],) -> BaseModelTypeVar:- # TODO: try with the newest instructor release- msg = f"It is not possible to generate objects with a {self.__class__.__name__}."- raise LLMCapabilityError(msg)+ # Refused by check_request before this is reached. TODO: try with the newest instructor release+ raise LLMCapabilityError(self._structured_output_refusal(inference_model=self.inference_model))diff --git a/pipelex/providers/bedrock/bedrock_plugin.py b/pipelex/providers/bedrock/bedrock_plugin.pyindex b49b26a44..252553521 100644--- a/pipelex/providers/bedrock/bedrock_plugin.py+++ b/pipelex/providers/bedrock/bedrock_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -49,6 +50,14 @@ async def _list_bedrock_models( # ruff: ignore[unused-async]list_bedrock_models(sdk=sdk, backend_name=backend_name, backend=backend, flat=flat, any_listed=any_listed)+def _check_bedrock_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ require_sdk(spec=["boto3", "aiobotocore"], extra="bedrock", msg=_BEDROCK_MISSING_MSG)++ from pipelex.providers.bedrock.bedrock_llm_worker import BedrockLLMWorker # ruff: ignore[import-outside-top-level]++ BedrockLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++class BedrockPlugin:"""Built-in driver for Bedrock models via boto3/aiobotocore."""@@ -56,7 +65,11 @@ class BedrockPlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="bedrock_boto3", make_worker=_make_bedrock_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="bedrock_aioboto", make_worker=_make_bedrock_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="bedrock_boto3", make_worker=_make_bedrock_worker, check_llm_request=_check_bedrock_request+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="bedrock_aioboto", make_worker=_make_bedrock_worker, check_llm_request=_check_bedrock_request+ )registrar.add_model_lister(sdk="bedrock", lister=_list_bedrock_models)registrar.add_model_lister(sdk="bedrock_aioboto", lister=_list_bedrock_models)diff --git a/pipelex/providers/google/google_llm_worker.py b/pipelex/providers/google/google_llm_worker.pyindex 05a867fc0..c2fea626f 100644--- a/pipelex/providers/google/google_llm_worker.py+++ b/pipelex/providers/google/google_llm_worker.py@@ -113,10 +113,20 @@ class GoogleLLMWorker(LLMWorkerAbstract):# Reasoning helpers#########################################################- def _build_thinking_config(self, job_params: LLMJobParams, *, max_tokens: int | None) -> genai_types.ThinkingConfig | None:+ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse a reasoning setting the model's thinking cannot take, or a thinking budget the call's max_tokens cannot hold."""+ cls._build_thinking_config(inference_model=inference_model, job_params=job_params, max_tokens=job_params.max_tokens)++ @classmethod+ def _build_thinking_config(+ cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, max_tokens: int | None+ ) -> genai_types.ThinkingConfig | None:"""Build thinking config from job params and model spec.Args:+ inference_model: The spec of the model the request goes to.job_params: The LLM job parameters containing reasoning_effort/reasoning_budget.max_tokens: The effective max_tokens for this request, used to cap the thinking budget.@@ -124,43 +134,42 @@ class GoogleLLMWorker(LLMWorkerAbstract):A ThinkingConfig for the Google GenAI SDK, or None if reasoning is not requested."""- thinking_mode = self.inference_model.thinking_mode-# Case 1: reasoning_effort is setif job_params.reasoning_effort is not None:- return self._build_thinking_config_for_effort(thinking_mode=thinking_mode, effort=job_params.reasoning_effort, max_tokens=max_tokens)+ return cls._build_thinking_config_for_effort(inference_model=inference_model, effort=job_params.reasoning_effort, max_tokens=max_tokens)# Case 2: reasoning_budget is setif job_params.reasoning_budget is not None:- return self._build_thinking_config_for_budget(thinking_mode=thinking_mode, budget=job_params.reasoning_budget, max_tokens=max_tokens)+ return cls._build_thinking_config_for_budget(inference_model=inference_model, budget=job_params.reasoning_budget, max_tokens=max_tokens)# Case 3: neither reasoning_effort nor reasoning_budget is setreturn None+ @classmethoddef _build_thinking_config_for_effort(- self,- thinking_mode: ThinkingMode,+ cls,*,+ inference_model: InferenceModelSpec,effort: ReasoningEffort,max_tokens: int | None,) -> genai_types.ThinkingConfig:"""Build thinking config when reasoning_effort is specified."""- match thinking_mode:+ match inference_model.thinking_mode:case ThinkingMode.MANUAL:google_level = get_config().inference.llm.google.get_reasoning_level(effort=effort)if google_level is None:log.verbose("Google manual thinking disabled (effort mapped to disabled)")- return self._thinking_off_config()+ return cls._thinking_off_config(inference_model=inference_model)budget = get_config().inference.llm.get_reasoning_budget(- family=self.reasoning_budget_family,+ family=cls.reasoning_budget_family,effort=effort,)budget = fit_thinking_budget(budget=budget,max_tokens=max_tokens,- min_budget=self.inference_model.min_thinking_budget,- max_budget=self.inference_model.max_thinking_budget,- model_desc=self.inference_model.desc,+ min_budget=inference_model.min_thinking_budget,+ max_budget=inference_model.max_thinking_budget,+ model_desc=inference_model.desc,)log.verbose(f"Google manual thinking with thinking_budget={budget} (from effort={effort})")return genai_types.ThinkingConfig(thinking_budget=budget)@@ -168,44 +177,46 @@ class GoogleLLMWorker(LLMWorkerAbstract):thinking_level = get_config().inference.llm.google.get_reasoning_level(effort=effort)if thinking_level is None:log.verbose("Google adaptive thinking disabled (effort=NONE)")- return self._thinking_off_config()+ return cls._thinking_off_config(inference_model=inference_model)log.verbose(f"Google adaptive thinking with thinking_level={thinking_level}")return genai_types.ThinkingConfig(thinking_level=thinking_level)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)- def _thinking_off_config(self) -> genai_types.ThinkingConfig:+ @classmethod+ def _thinking_off_config(cls, *, inference_model: InferenceModelSpec) -> genai_types.ThinkingConfig:"""Build the thinking config that turns thinking off, which a model that always thinks refuses with a 400."""- if ListedConstraint.THINKING_CANNOT_BE_DISABLED in self.inference_model.listed_constraints:+ if ListedConstraint.THINKING_CANNOT_BE_DISABLED in inference_model.listed_constraints:msg = (- f"Model '{self.inference_model.desc}' cannot turn thinking off, so it cannot take reasoning_effort 'none': "+ f"Model '{inference_model.desc}' cannot turn thinking off, so it cannot take reasoning_effort 'none': "f"set another reasoning effort, or remove the reasoning setting")raise LLMCapabilityError(msg)return genai_types.ThinkingConfig(thinking_budget=0)+ @classmethoddef _build_thinking_config_for_budget(- self,- thinking_mode: ThinkingMode,+ cls,*,+ inference_model: InferenceModelSpec,budget: int,max_tokens: int | None,) -> genai_types.ThinkingConfig:"""Build thinking config when reasoning_budget is specified."""- match thinking_mode:+ match inference_model.thinking_mode:case ThinkingMode.MANUAL | ThinkingMode.ADAPTIVE:budget = fit_thinking_budget(budget=budget,max_tokens=max_tokens,- min_budget=self.inference_model.min_thinking_budget,- max_budget=self.inference_model.max_thinking_budget,- model_desc=self.inference_model.desc,+ min_budget=inference_model.min_thinking_budget,+ max_budget=inference_model.max_thinking_budget,+ model_desc=inference_model.desc,)log.verbose(f"Google thinking with explicit thinking_budget={budget}")return genai_types.ThinkingConfig(thinking_budget=budget)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)#########################################################@@ -220,7 +231,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):contents = await GoogleFactory.prepare_user_contents(llm_prompt=llm_job.llm_prompt)- thinking_config = self._build_thinking_config(job_params=job_params, max_tokens=job_params.max_tokens)+ thinking_config = self._build_thinking_config(inference_model=self.inference_model, job_params=job_params, max_tokens=job_params.max_tokens)# Build generation configgeneration_config = genai_types.GenerateContentConfig(@@ -287,7 +298,7 @@ class GoogleLLMWorker(LLMWorkerAbstract):) -> BaseModelTypeVar:"""Generate structured output using Google Gemini API with instructor."""job_params = llm_job.applied_job_params or llm_job.job_params- thinking_config = self._build_thinking_config(job_params=job_params, max_tokens=job_params.max_tokens)+ thinking_config = self._build_thinking_config(inference_model=self.inference_model, job_params=job_params, max_tokens=job_params.max_tokens)# instructor's genai handlers read the system prompt only from `system`, and pop it only when it is not# None: a `system=None` reaches `generate_content`, which refuses the unknown keywordsystem_kwargs: dict[str, Any] = {"system": system_text} if (system_text := llm_job.llm_prompt.system_text) else {}diff --git a/pipelex/providers/google/google_plugin.py b/pipelex/providers/google/google_plugin.pyindex 9a54a7929..56a3be71f 100644--- a/pipelex/providers/google/google_plugin.py+++ b/pipelex/providers/google/google_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -36,6 +37,14 @@ def _make_google_worker()+def _check_google_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ require_sdk(spec="google.genai", dependency_name="google-genai", extra="google", msg=_GOOGLE_MISSING_MSG)++ from pipelex.providers.google.google_llm_worker import GoogleLLMWorker # ruff: ignore[import-outside-top-level]++ GoogleLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++def _make_google_img_gen_worker(*,inference_model: InferenceModelSpec,@@ -80,6 +89,8 @@ class GooglePlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="google", make_worker=_make_google_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="google", make_worker=_make_google_worker, check_llm_request=_check_google_request+ )registrar.add_inference_backend(family=InferenceFamily.IMG_GEN, sdk="google", make_worker=_make_google_img_gen_worker)registrar.add_model_lister(sdk="google", lister=_list_google_models)diff --git a/pipelex/providers/mistral/mistral_llm_worker.py b/pipelex/providers/mistral/mistral_llm_worker.pyindex e79009666..0e6dc04d7 100644--- a/pipelex/providers/mistral/mistral_llm_worker.py+++ b/pipelex/providers/mistral/mistral_llm_worker.py@@ -31,6 +31,7 @@ from pipelex.reporting.reporting_protocol import ReportingProtocolfrom pipelex.tools.typing.pydantic_utils import BaseModelTypeVarif TYPE_CHECKING:+ from instructor import Mode as InstructorModefrom mistralai.client.models import ChatCompletionResponsefrom mistralai.client.types import OptionalNullable@@ -62,35 +63,64 @@ class MistralLLMWorker(LLMWorkerAbstract):self.mistral_factory = mistral_factoryfrom instructor import from_mistral # ruff: ignore[import-outside-top-level]- if instructor_mode := self.inference_model.get_instructor_mode():- self.instructor_for_objects = from_mistral(client=sdk_instance, mode=instructor_mode, use_async=True)- else:- self.instructor_for_objects = from_mistral(client=sdk_instance, use_async=True)+ self.instructor_for_objects = from_mistral(client=sdk_instance, mode=self._instructor_mode(inference_model=inference_model), use_async=True)++ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse a reasoning setting Mistral cannot carry for the model, and one on a structured output it cannot read back.- def _resolve_reasoning_effort(self, job_params: LLMJobParams) -> "OptionalNullable[MistralReasoningEffort]":+ A reasoning reply carries its answer beside a thinking chunk in a list of content chunks, which instructor's+ JSON parsers read as one string and refuse on every attempt; its tool mode reads the tool call and validates.+ So a structured output with a reasoning setting needs the tool structure method.+ """+ reasoning_effort = cls._resolve_reasoning_effort(inference_model=inference_model, job_params=job_params)+ if not is_structured or reasoning_effort is UNSET:+ return+ from instructor import Mode as InstructorMode # ruff: ignore[import-outside-top-level]++ if cls._instructor_mode(inference_model=inference_model) != InstructorMode.TOOLS:+ msg = (+ f"Model '{inference_model.desc}' cannot reason on a structured output with structure method "+ f"'{inference_model.structure_method}': use 'instructor/mistral_tools', or remove the reasoning setting"+ )+ raise LLMCapabilityError(msg)++ @classmethod+ def _instructor_mode(cls, *, inference_model: InferenceModelSpec) -> "InstructorMode":+ """The instructor mode structured outputs use: the model's structure method's, else the tool mode."""+ from instructor import Mode as InstructorMode # ruff: ignore[import-outside-top-level]++ return inference_model.get_instructor_mode() or InstructorMode.TOOLS++ @classmethod+ def _resolve_reasoning_effort(+ cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams+ ) -> "OptionalNullable[MistralReasoningEffort]":"""Resolve reasoning parameters to a Mistral reasoning_effort value.Mistral's reasoning models take `reasoning_effort` and refuse the older `prompt_mode="reasoning"`.Args:+ inference_model: The spec of the model the request goes to.job_params: The LLM job parameters containing reasoning_effort/reasoning_budget.Returns:The Mistral reasoning_effort value, or UNSET if reasoning is not requested."""- thinking_mode = self.inference_model.thinking_mode+ thinking_mode = inference_model.thinking_modeif job_params.reasoning_budget is not None:match thinking_mode:case ThinkingMode.MANUAL:- msg = f"Model '{self.inference_model.desc}' does not support reasoning_budget; Mistral uses reasoning_effort instead"+ msg = f"Model '{inference_model.desc}' does not support reasoning_budget; Mistral uses reasoning_effort instead"raise LLMCapabilityError(msg)case ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)if job_params.reasoning_effort is not None:@@ -104,10 +134,10 @@ class MistralLLMWorker(LLMWorkerAbstract):log.verbose(f"Mistral reasoning_effort={mistral_effort}")return mistral_effortcase ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported for Mistral models"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)return UNSET@@ -119,7 +149,7 @@ class MistralLLMWorker(LLMWorkerAbstract):) -> str:job_params = llm_job.applied_job_params or llm_job.job_paramsmessages = await self.mistral_factory.make_simple_messages(llm_job=llm_job)- reasoning_effort = self._resolve_reasoning_effort(job_params=job_params)+ reasoning_effort = self._resolve_reasoning_effort(inference_model=self.inference_model, job_params=job_params)try:response: ChatCompletionResponse | None = await self.mistral_client_for_text.chat.complete_async(messages=messages,@@ -226,19 +256,10 @@ class MistralLLMWorker(LLMWorkerAbstract):schema: type[BaseModelTypeVar],) -> BaseModelTypeVar:job_params = llm_job.applied_job_params or llm_job.job_params- reasoning_effort = self._resolve_reasoning_effort(job_params=job_params)- # Deferred imports: avoid pulling heavy SDK at module-load time- from instructor import Mode as InstructorMode # ruff: ignore[import-outside-top-level]+ reasoning_effort = self._resolve_reasoning_effort(inference_model=self.inference_model, job_params=job_params)+ # Deferred import: avoid pulling heavy SDK at module-load timefrom instructor.core import InstructorRetryException # ruff: ignore[import-outside-top-level]- if reasoning_effort is not UNSET and self.instructor_for_objects.mode != InstructorMode.TOOLS:- # A reasoning reply carries its answer beside a thinking chunk in a list of content chunks, which instructor's- # JSON parsers read as one string and refuse on every attempt; its tool mode reads the tool call and validates- msg = (- f"Model '{self.inference_model.desc}' cannot reason on a structured output with structure method "- f"'{self.inference_model.structure_method}': use 'instructor/mistral_tools', or remove the reasoning setting"- )- raise LLMCapabilityError(msg)messages = await self.mistral_factory.make_simple_messages_openai_typed(llm_job=llm_job)try:diff --git a/pipelex/providers/mistral/mistral_plugin.py b/pipelex/providers/mistral/mistral_plugin.pyindex 64ecb64ea..dbad9051a 100644--- a/pipelex/providers/mistral/mistral_plugin.py+++ b/pipelex/providers/mistral/mistral_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -41,6 +42,14 @@ def _make_mistral_worker()+def _check_mistral_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ require_sdk(spec="mistralai", extra="mistral", msg=_MISTRAL_MISSING_MSG)++ from pipelex.providers.mistral.mistral_llm_worker import MistralLLMWorker # ruff: ignore[import-outside-top-level]++ MistralLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++def _make_mistral_extract_worker(*,inference_model: InferenceModelSpec,@@ -87,6 +96,8 @@ class MistralPlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="mistral", make_worker=_make_mistral_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="mistral", make_worker=_make_mistral_worker, check_llm_request=_check_mistral_request+ )registrar.add_inference_backend(family=InferenceFamily.EXTRACT, sdk="mistral", make_worker=_make_mistral_extract_worker)registrar.add_model_lister(sdk="mistral", lister=_list_mistral_models)diff --git a/pipelex/providers/openai/openai_completions_llm_worker.py b/pipelex/providers/openai/openai_completions_llm_worker.pyindex cd34c923c..a395e2fc3 100644--- a/pipelex/providers/openai/openai_completions_llm_worker.py+++ b/pipelex/providers/openai/openai_completions_llm_worker.py@@ -83,17 +83,25 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):# Reasoning helpers#########################################################- def _resolve_reasoning_effort(self, job_params: LLMJobParams) -> ChatCompletionReasoningEffort | None:+ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse a reasoning setting the Chat Completions API cannot carry for the model, on text and structured outputs alike."""+ cls._resolve_reasoning_effort(inference_model=inference_model, job_params=job_params)++ @classmethod+ def _resolve_reasoning_effort(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams) -> ChatCompletionReasoningEffort | None:"""Resolve reasoning parameters to an OpenAI Chat Completions reasoning_effort value.Args:+ inference_model: The spec of the model the request goes to.job_params: The LLM job parameters containing reasoning_effort/reasoning_budget.Returns:The OpenAI reasoning_effort string, or None if reasoning is not requested."""- thinking_mode = self.inference_model.thinking_mode+ thinking_mode = inference_model.thinking_modeif job_params.reasoning_effort is not None:effort = job_params.reasoning_effort@@ -103,22 +111,22 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):log.verbose(f"OpenAI Chat Completions reasoning_effort={openai_effort}")return openai_effortcase ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)if job_params.reasoning_budget is not None:match thinking_mode:case ThinkingMode.MANUAL:- msg = f"Model '{self.inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"+ msg = f"Model '{inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"raise LLMCapabilityError(msg)case ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Chat Completions API"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)return None@@ -131,7 +139,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):job_params = llm_job.applied_job_params or llm_job.job_paramsmessages = await self.openai_completions_factory.make_simple_messages(llm_job=llm_job)- openai_reasoning_effort = self._resolve_reasoning_effort(job_params=job_params)+ openai_reasoning_effort = self._resolve_reasoning_effort(inference_model=self.inference_model, job_params=job_params)try:extra_headers, extra_body = self.openai_completions_factory.make_extras(@@ -208,7 +216,7 @@ class OpenAICompletionsLLMWorker(LLMWorkerAbstract):schema: type[BaseModelTypeVar],) -> BaseModelTypeVar:job_params = llm_job.applied_job_params or llm_job.job_params- openai_reasoning_effort = self._resolve_reasoning_effort(job_params=job_params)+ openai_reasoning_effort = self._resolve_reasoning_effort(inference_model=self.inference_model, job_params=job_params)messages = await self.openai_completions_factory.make_simple_messages(llm_job=llm_job)# Deferred import: avoid pulling heavy SDK at module-load timefrom instructor.core import InstructorRetryException # ruff: ignore[import-outside-top-level]diff --git a/pipelex/providers/openai/openai_plugin.py b/pipelex/providers/openai/openai_plugin.pyindex 30dd192eb..f1ea00c53 100644--- a/pipelex/providers/openai/openai_plugin.py+++ b/pipelex/providers/openai/openai_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -92,6 +93,18 @@ async def _list_openai_models(await list_openai_models(sdk=sdk, backend_name=backend_name, backend=backend, flat=flat, any_listed=any_listed)+def _check_openai_completions_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ from pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker # ruff: ignore[import-outside-top-level]++ OpenAICompletionsLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)+++def _check_openai_responses_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ from pipelex.providers.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker # ruff: ignore[import-outside-top-level]++ OpenAIResponsesLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++class OpenAIPlugin:"""Always-on built-in driver for OpenAI and Azure OpenAI (no optional SDK)."""@@ -99,10 +112,27 @@ class OpenAIPlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="openai", make_worker=_make_openai_completions_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="azure_openai", make_worker=_make_openai_completions_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="openai_responses", make_worker=_make_openai_responses_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="azure_openai_responses", make_worker=_make_openai_responses_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM, sdk="openai", make_worker=_make_openai_completions_worker, check_llm_request=_check_openai_completions_request+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM,+ sdk="azure_openai",+ make_worker=_make_openai_completions_worker,+ check_llm_request=_check_openai_completions_request,+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM,+ sdk="openai_responses",+ make_worker=_make_openai_responses_worker,+ check_llm_request=_check_openai_responses_request,+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM,+ sdk="azure_openai_responses",+ make_worker=_make_openai_responses_worker,+ check_llm_request=_check_openai_responses_request,+ )registrar.add_inference_backend(family=InferenceFamily.IMG_GEN, sdk="openai_img_gen", make_worker=_make_openai_img_gen_worker)registrar.add_model_lister(sdk="openai", lister=_list_openai_models)registrar.add_model_lister(sdk="azure_openai", lister=_list_openai_models)diff --git a/pipelex/providers/openai/openai_responses_llm_worker.py b/pipelex/providers/openai/openai_responses_llm_worker.pyindex 7f4b9e843..9f00d7148 100644--- a/pipelex/providers/openai/openai_responses_llm_worker.py+++ b/pipelex/providers/openai/openai_responses_llm_worker.py@@ -88,17 +88,25 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):# Reasoning helpers#########################################################- def _resolve_reasoning(self, job_params: LLMJobParams) -> Reasoning | None:+ @classmethod+ @override+ def check_request(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ """Refuse a reasoning setting the Responses API cannot carry for the model, on text and structured outputs alike."""+ cls._resolve_reasoning(inference_model=inference_model, job_params=job_params)++ @classmethod+ def _resolve_reasoning(cls, *, inference_model: InferenceModelSpec, job_params: LLMJobParams) -> Reasoning | None:"""Resolve reasoning parameters to an OpenAI Responses API reasoning dict.Args:+ inference_model: The spec of the model the request goes to.job_params: The LLM job parameters containing reasoning_effort/reasoning_budget.Returns:A Reasoning dict for the OpenAI Responses API, or None if reasoning is not requested."""- thinking_mode = self.inference_model.thinking_mode+ thinking_mode = inference_model.thinking_modeif job_params.reasoning_effort is not None:effort = job_params.reasoning_effort@@ -110,22 +118,22 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):log.verbose(f"OpenAI Responses reasoning effort={openai_effort}")return Reasoning(effort=openai_effort)case ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)if job_params.reasoning_budget is not None:match thinking_mode:case ThinkingMode.MANUAL:- msg = f"Model '{self.inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"+ msg = f"Model '{inference_model.desc}' does not support reasoning_budget; OpenAI uses reasoning_effort instead"raise LLMCapabilityError(msg)case ThinkingMode.ADAPTIVE:- msg = f"Model '{self.inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"+ msg = f"Model '{inference_model.desc}' has thinking_mode=adaptive which is not supported by the OpenAI Responses API"raise LLMCapabilityError(msg)case ThinkingMode.NONE:- msg = f"Model '{self.inference_model.desc}' does not support reasoning (thinking_mode=none)"+ msg = f"Model '{inference_model.desc}' does not support reasoning (thinking_mode=none)"raise LLMCapabilityError(msg)return None@@ -138,7 +146,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):job_params = llm_job.applied_job_params or llm_job.job_paramsinput_items = await self.openai_responses_factory.make_input_items(llm_job=llm_job)- openai_reasoning = self._resolve_reasoning(job_params=job_params)+ openai_reasoning = self._resolve_reasoning(inference_model=self.inference_model, job_params=job_params)try:extra_headers, extra_body = self.openai_responses_factory.make_extras(@@ -189,7 +197,7 @@ class OpenAIResponsesLLMWorker(LLMWorkerAbstract):schema: type[BaseModelTypeVar],) -> BaseModelTypeVar:job_params = llm_job.applied_job_params or llm_job.job_params- openai_reasoning = self._resolve_reasoning(job_params=job_params)+ openai_reasoning = self._resolve_reasoning(inference_model=self.inference_model, job_params=job_params)from instructor.core import InstructorRetryException # ruff: ignore[import-outside-top-level]if not hasattr(self.instructor_for_objects, "responses"):diff --git a/pipelex/providers/portkey/portkey_plugin.py b/pipelex/providers/portkey/portkey_plugin.pyindex da872a94b..949cce881 100644--- a/pipelex/providers/portkey/portkey_plugin.py+++ b/pipelex/providers/portkey/portkey_plugin.py@@ -1,4 +1,5 @@from pipelex.cogt.inference.inference_worker_abstract import InferenceWorkerAbstract+from pipelex.cogt.llm.llm_job_components import LLMJobParamsfrom pipelex.cogt.model_backends.backend import InferenceBackendfrom pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.plugins.contract import PLUGIN_API_VERSION@@ -55,6 +56,18 @@ def _make_portkey_responses_worker()+def _check_portkey_completions_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ from pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker # ruff: ignore[import-outside-top-level]++ OpenAICompletionsLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)+++def _check_portkey_responses_request(*, inference_model: InferenceModelSpec, job_params: LLMJobParams, is_structured: bool) -> None:+ from pipelex.providers.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker # ruff: ignore[import-outside-top-level]++ OpenAIResponsesLLMWorker.check_request(inference_model=inference_model, job_params=job_params, is_structured=is_structured)++class PortkeyPlugin:"""Built-in driver for Portkey (OpenAI-compatible substrate)."""@@ -62,5 +75,15 @@ class PortkeyPlugin:targets_api = PLUGIN_API_VERSIONdef register(self, registrar: PluginRegistrar) -> None:- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="portkey_completions", make_worker=_make_portkey_completions_worker)- registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="portkey_responses", make_worker=_make_portkey_responses_worker)+ registrar.add_inference_backend(+ family=InferenceFamily.LLM,+ sdk="portkey_completions",+ make_worker=_make_portkey_completions_worker,+ check_llm_request=_check_portkey_completions_request,+ )+ registrar.add_inference_backend(+ family=InferenceFamily.LLM,+ sdk="portkey_responses",+ make_worker=_make_portkey_responses_worker,+ check_llm_request=_check_portkey_responses_request,+ )diff --git a/pipelex/runtime_boot.py b/pipelex/runtime_boot.pyindex 422de6618..f1d9ff9c7 100644--- a/pipelex/runtime_boot.py+++ b/pipelex/runtime_boot.py@@ -559,7 +559,9 @@ If you need help, drop by our Discord: we're happy to assist: {URLs.discord}.# The orchestrator and bundle-validator registries are interpreter-contributed and therefore# empty on a kernel-only boot. That is fine and deliberate: nothing here resolves out of them,# they are looked up at run time by the interpreter.- self.runtime_hub.set_inference_backend_registry(InferenceBackendRegistry(plugin_registrar.inference_backends))+ self.runtime_hub.set_inference_backend_registry(+ InferenceBackendRegistry(plugin_registrar.inference_backends, llm_request_checks=plugin_registrar.llm_request_checks)+ )self.runtime_hub.set_model_lister_registry(ModelListerRegistry(plugin_registrar.model_listers))self.runtime_hub.set_service_error_vocabulary(service_error_vocabulary=ServiceErrorVocabulary(plugin_registrar.service_error_codes))self.runtime_hub.set_orchestrator_registry(OrchestratorRegistry(plugin_registrar.orchestrators))diff --git a/pipelex/test_extras/mthds_corpus/vocabulary.toml b/pipelex/test_extras/mthds_corpus/vocabulary.tomlindex c8791f584..562599db1 100644--- a/pipelex/test_extras/mthds_corpus/vocabulary.toml+++ b/pipelex/test_extras/mthds_corpus/vocabulary.toml@@ -132,6 +132,10 @@ fails_at = "runtime"code = "llm_output_cannot_be_image"fails_at = "runtime"+[error.llm_setting_refused_by_model]+code = "llm_setting_refused_by_model"+excluded = "It refuses a model setting the model it resolves to refuses, such as reasoning on a model that does not think, so the bundle that produces it must name a model the deck defines with that particular capability. The corpus rule that an entry names no model forbids exactly that: whether a model takes a setting is a fact of each consumer's deck, not of the language. Revisit if the corpus ever grows a deck axis."+[error.invalid_pipe_code_syntax]code = "invalid_pipe_code_syntax"fails_at = "runtime"diff --git a/pipelex/validation_error_types.py b/pipelex/validation_error_types.pyindex 77bee856f..7a0c6cff3 100644--- a/pipelex/validation_error_types.py+++ b/pipelex/validation_error_types.py@@ -47,6 +47,12 @@ class PipeValidationErrorType(StrEnum):INADEQUATE_OUTPUT_MULTIPLICITY = "inadequate_output_multiplicity"LLM_OUTPUT_CANNOT_BE_IMAGE = "llm_output_cannot_be_image"+ # A PipeLLM or a PipeStructure whose model setting the model it resolves to refuses for the output it+ # generates: a reasoning setting the model's thinking mode refuses, a reasoning budget where it takes only+ # an effort, a thinking budget its max_tokens cannot hold, or a structured output its worker cannot+ # generate. Detected when the pipe is validated against the library, by the request check the model's+ # worker runs before every call, so a run never starts only to fail at its first call.+ LLM_SETTING_REFUSED_BY_MODEL = "llm_setting_refused_by_model"INVALID_PIPE_CODE_SYNTAX = "invalid_pipe_code_syntax"# An input name that is not a plain snake_case identifier, a dotted name (`invoice.total`) included,# on any pipe's `inputs` or as a PipeBatch's `input_list_name`; or a name taking the `_bound_` prefix@@ -140,6 +146,7 @@ class PipeValidationErrorType(StrEnum):PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -176,6 +183,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.EXTRANEOUS_INPUT_VARIABLE| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -219,6 +227,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INPUT_STUFF_SPEC_MISMATCH| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -257,6 +266,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPE@@ -299,6 +309,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPE| PipeValidationErrorType.MISSING_PIPE_TYPE@@ -341,6 +352,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.UNKNOWN_PIPE_TYPE| PipeValidationErrorType.MISSING_PIPE_TYPE@@ -378,6 +390,7 @@ class PipeValidationErrorType(StrEnum):| PipeValidationErrorType.INADEQUATE_OUTPUT_CONCEPT| PipeValidationErrorType.INADEQUATE_OUTPUT_MULTIPLICITY| PipeValidationErrorType.LLM_OUTPUT_CANNOT_BE_IMAGE+ | PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL| PipeValidationErrorType.INVALID_PIPE_CODE_SYNTAX| PipeValidationErrorType.INVALID_INPUT_NAME| PipeValidationErrorType.UNKNOWN_PIPE_TYPEdiff --git a/subject_grants.toml b/subject_grants.tomlindex df68fc84f..ac94dd903 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -4768,18 +4768,6 @@ rationale = "Verb–object: renders the model list; single operand."param = "models"rationale = "Verb–object: renders the model list; single operand."-["pipelex/providers/anthropic/anthropic_llm_worker.py::AnthropicLLMWorker._build_thinking_params"]-param = "job_params"-rationale = "Builds provider thinking params from the job_params; single operand."--["pipelex/providers/anthropic/anthropic_llm_worker.py::AnthropicLLMWorker._build_thinking_params_for_budget"]-param = "thinking_mode"-rationale = "Builds provider thinking params from the thinking_mode; single operand."--["pipelex/providers/anthropic/anthropic_llm_worker.py::AnthropicLLMWorker._build_thinking_params_for_effort"]-param = "thinking_mode"-rationale = "Builds provider thinking params from the thinking_mode; single operand."-["pipelex/providers/anthropic/anthropic_llms.py::anthropic_list_available_models"]param = "model_handle"rationale = "Lists the available models for the model handle; single operand."@@ -4816,10 +4804,6 @@ rationale = "Verb–object: renders the model list; single operand."param = "models"rationale = "Verb–object: renders the model list; single operand."-["pipelex/providers/bedrock/bedrock_llm_worker.py::BedrockLLMWorker._validate_no_reasoning_params"]-param = "job_params"-rationale = "Validates the job params carry no unsupported reasoning settings; single operand."-["pipelex/providers/bedrock/bedrock_llms.py::bedrock_list_available_models"]param = "model_handle"rationale = "Lists the available models for the model handle; single operand."@@ -4904,18 +4888,6 @@ rationale = "Verb–object: renders the model list; single operand."param = "models"rationale = "Verb–object: renders the model list; single operand."-["pipelex/providers/google/google_llm_worker.py::GoogleLLMWorker._build_thinking_config"]-param = "job_params"-rationale = "Builds provider thinking params from the job_params; single operand."--["pipelex/providers/google/google_llm_worker.py::GoogleLLMWorker._build_thinking_config_for_budget"]-param = "thinking_mode"-rationale = "Builds provider thinking params from the thinking_mode; single operand."--["pipelex/providers/google/google_llm_worker.py::GoogleLLMWorker._build_thinking_config_for_effort"]-param = "thinking_mode"-rationale = "Builds provider thinking params from the thinking_mode; single operand."-["pipelex/providers/google/google_plugin.py::GooglePlugin.register"]param = "registrar"rationale = "Plugin protocol register: the registrar is the sole sink the plugin populates."@@ -5016,10 +4988,6 @@ rationale = "Verb–object: renders the model list; single operand."param = "models"rationale = "Verb–object: renders the model list; single operand."-["pipelex/providers/mistral/mistral_llm_worker.py::MistralLLMWorker._resolve_reasoning_effort"]-param = "job_params"-rationale = "Resolves the reasoning effort from the job params; single operand."-["pipelex/providers/mistral/mistral_plugin.py::MistralPlugin.register"]param = "registrar"rationale = "Plugin protocol register: the registrar is the sole sink the plugin populates."@@ -5044,10 +5012,6 @@ rationale = "Factory from source: builds the result from the llm_job; single opeparam = "img_gen_job"rationale = "Builds the messages payload from the img-gen job; single operand."-["pipelex/providers/openai/openai_completions_llm_worker.py::OpenAICompletionsLLMWorker._resolve_reasoning_effort"]-param = "job_params"-rationale = "Resolves the reasoning effort from the job params; single operand."-["pipelex/providers/openai/openai_config.py::OpenAIConfig.get_reasoning_level"]param = "effort"rationale = "Maps the reasoning effort to a provider reasoning level; single operand."@@ -5084,10 +5048,6 @@ rationale = "Factory from source: builds the result from the llm_job; single opeparam = "usage"rationale = "Factory from source: builds the result from the usage; single operand."-["pipelex/providers/openai/openai_responses_llm_worker.py::OpenAIResponsesLLMWorker._resolve_reasoning"]-param = "job_params"-rationale = "Resolves the reasoning config from the job params; single operand."-["pipelex/providers/openai/vertexai_factory.py::VertexAIFactory._make_api_key"]param = "gcp_credentials_file_path"rationale = "Factory from source: builds the result from the gcp_credentials_file_path; single operand."diff --git a/tests/data/errors/error_identity.txt b/tests/data/errors/error_identity.txtindex 44b6caca3..fd320523d 100644--- a/tests/data/errors/error_identity.txt+++ b/tests/data/errors/error_identity.txt@@ -154,6 +154,7 @@ LLMHandleNotFoundError | LLM handle not found | https://docs.pipelex.com/latest/LLMModelNotFoundError | LLM model not found | https://docs.pipelex.com/latest/errors/llm-model-not-found-error/LLMPromptParameterError | LLM prompt parameter | https://docs.pipelex.com/latest/errors/llm-prompt-parameter-error/LLMPromptSpecError | LLM prompt spec | https://docs.pipelex.com/latest/errors/llm-prompt-spec-error/+LLMSettingRefusedError | LLM setting refused | https://docs.pipelex.com/latest/errors/llm-setting-refused-error/LLMSettingsValidationError | LLM settings validation | https://docs.pipelex.com/latest/errors/llm-settings-validation-error/LangfuseCredentialsError | Langfuse credentials | https://docs.pipelex.com/latest/errors/langfuse-credentials-error/LibraryError | Library error | https://docs.pipelex.com/latest/errors/library-error/diff --git a/tests/integration/pipelex/pipes/operator/pipe_llm/test_data.py b/tests/integration/pipelex/pipes/operator/pipe_llm/test_data.pynew file mode 100644index 000000000..f6b03ff7a--- /dev/null+++ b/tests/integration/pipelex/pipes/operator/pipe_llm/test_data.py@@ -0,0 +1,51 @@+class LLMSettingCheckTestData:+ """Bundles whose one step generates with a model setting the model it resolves to may refuse.++ The models are the dev configuration's OpenAI entries, on the Responses SDK: one declares no thinking+ (`thinking_mode = "none"`), so it takes no reasoning setting, and the other thinks under a reasoning+ effort but takes no reasoning budget, which only Anthropic and Gemini take.+ """++ MODEL_WITHOUT_THINKING = "gpt-4o-mini"+ MODEL_WITH_EFFORT = "gpt-5.4-mini"++ @classmethod+ def pipe_llm_bundle(cls, *, output: str, model_fields: str) -> str:+ return f"""+domain = "llm_setting_check"+description = "A step generating with a model setting"++[concept.Verdict]+description = "A verdict on a question"++[concept.Verdict.structure]+answer = {{ type = "text", description = "The answer", required = true }}++[pipe.answer_it]+type = "PipeLLM"+description = "Answer the question"+inputs = {{ question = "Text" }}+output = "{output}"+prompt = "Answer this question: $question"+{model_fields}+"""++ @classmethod+ def pipe_structure_bundle(cls, *, model_fields: str) -> str:+ return f"""+domain = "llm_setting_check"+description = "A step structuring a text with a model setting"++[concept.Verdict]+description = "A verdict on a question"++[concept.Verdict.structure]+answer = {{ type = "text", description = "The answer", required = true }}++[pipe.structure_it]+type = "PipeStructure"+description = "Structure the answer"+inputs = {{ draft = "Text" }}+output = "Verdict"+{model_fields}+"""diff --git a/tests/integration/pipelex/pipes/operator/pipe_llm/test_pipe_llm_setting_refusals.py b/tests/integration/pipelex/pipes/operator/pipe_llm/test_pipe_llm_setting_refusals.pynew file mode 100644index 000000000..6a96d57d1--- /dev/null+++ b/tests/integration/pipelex/pipes/operator/pipe_llm/test_pipe_llm_setting_refusals.py@@ -0,0 +1,127 @@+import pytest++from pipelex.base_exceptions import ValidationErrorItem+from pipelex.pipeline.exceptions import ValidateBundleError+from pipelex.pipeline.validate_bundle import validate_bundle+from pipelex.validation_error_types import PipeValidationErrorType+from tests.integration.pipelex.pipes.operator.pipe_llm.test_data import LLMSettingCheckTestData++_WITHOUT_THINKING = LLMSettingCheckTestData.MODEL_WITHOUT_THINKING+_WITH_EFFORT = LLMSettingCheckTestData.MODEL_WITH_EFFORT+++async def _the_refusal(bundle: str) -> ValidationErrorItem:+ with pytest.raises(ValidateBundleError) as exc_info:+ await validate_bundle(mthds_contents=[bundle])+ items = exc_info.value.validation_error_items()+ assert len(items) == 1, items+ item = items[0]+ assert item.error_type == PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL+ return item++[email protected](loop_scope="class")+class TestPipeLLMSettingRefusals:+ @pytest.mark.parametrize(+ ("output", "output_desc"),+ [+ pytest.param("Verdict", "a structured output", id="structured_output"),+ pytest.param("Text", "text", id="text_output"),+ pytest.param("Text[]", "a structured output", id="list_of_texts"),+ ],+ )+ async def test_a_reasoning_effort_on_a_model_without_thinking_is_refused_on_its_field(self, output: str, output_desc: str) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output=output,+ model_fields=f'model = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "high" }}',+ )+ item = await _the_refusal(bundle)+ assert item.pipe_code == "answer_it"+ assert item.field_name == "model"+ assert item.field_path == "pipe.answer_it.model"+ assert f"PipeLLM 'answer_it' generates {output_desc} with the model setting its `model` writes inline" in item.message+ assert f"Model '{_WITHOUT_THINKING}' does not support reasoning (thinking_mode=none). " in item.message+ assert "SDK" not in item.message+ assert "Backend" not in item.message++ async def test_a_reasoning_budget_on_a_model_taking_an_effort_is_refused(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output="Verdict",+ model_fields=f'model = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_budget = 2048 }}',+ )+ item = await _the_refusal(bundle)+ assert "does not support reasoning_budget; OpenAI uses reasoning_effort instead" in item.message++ async def test_the_structuring_setting_is_checked_on_model_to_structure(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output="Verdict",+ model_fields=(+ f'model = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "high" }}\n'+ f'model_to_structure = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "low" }}'+ ),+ )+ item = await _the_refusal(bundle)+ assert item.field_name == "model_to_structure"+ assert item.field_path == "pipe.answer_it.model_to_structure"++ async def test_a_text_output_is_not_checked_against_its_structuring_setting(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output="Text",+ model_fields=(+ f'model = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "high" }}\n'+ f'model_to_structure = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "low" }}'+ ),+ )+ await validate_bundle(mthds_contents=[bundle])++ async def test_a_list_of_dynamic_outputs_is_checked_against_its_structuring_setting(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output="Dynamic[]",+ model_fields=(+ f'model = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "high" }}\n'+ f'model_to_structure = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "low" }}'+ ),+ )+ item = await _the_refusal(bundle)+ assert item.field_name == "model_to_structure"+ assert "PipeLLM 'answer_it' generates a structured output" in item.message++ @pytest.mark.parametrize("output", ["Dynamic", "Text"])+ async def test_a_single_dynamic_or_text_output_is_checked_against_its_text_setting(self, output: str) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output=output,+ model_fields=(+ f'model = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "high" }}\n'+ f'model_to_structure = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "low" }}'+ ),+ )+ item = await _the_refusal(bundle)+ assert item.field_name == "model"+ assert "PipeLLM 'answer_it' generates text" in item.message++ async def test_a_list_of_dynamic_outputs_is_not_checked_against_its_text_setting(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output="Dynamic[]",+ model_fields=(+ f'model = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "high" }}\n'+ f'model_to_structure = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "low" }}'+ ),+ )+ await validate_bundle(mthds_contents=[bundle])++ @pytest.mark.parametrize("output", ["Verdict", "Text"])+ async def test_a_reasoning_effort_the_model_takes_validates(self, output: str) -> None:+ bundle = LLMSettingCheckTestData.pipe_llm_bundle(+ output=output,+ model_fields=f'model = {{ model = "{_WITH_EFFORT}", temperature = 1, reasoning_effort = "high" }}',+ )+ await validate_bundle(mthds_contents=[bundle])++ async def test_a_pipe_structure_setting_is_refused_on_its_field(self) -> None:+ bundle = LLMSettingCheckTestData.pipe_structure_bundle(+ model_fields=f'model = {{ model = "{_WITHOUT_THINKING}", temperature = 1, reasoning_effort = "medium" }}',+ )+ item = await _the_refusal(bundle)+ assert item.pipe_code == "structure_it"+ assert item.field_name == "model"+ assert "PipeStructure 'structure_it' generates a structured output" in item.messagediff --git a/tests/unit/pipelex/cogt/llm/test_llm_worker_constrained_job_params.py b/tests/unit/pipelex/cogt/llm/test_llm_worker_constrained_job_params.pynew file mode 100644index 000000000..ae26d8f53--- /dev/null+++ b/tests/unit/pipelex/cogt/llm/test_llm_worker_constrained_job_params.py@@ -0,0 +1,62 @@+from typing import Any++from pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffort+from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract+from pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.cogt.model_backends.constraints import ListedConstraint, ValuedConstraint+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.usage.cost_category import CostCategory+++def _make_model(+ *,+ thinking_mode: ThinkingMode,+ max_tokens: int | None = None,+ listed_constraints: list[ListedConstraint] | None = None,+ valued_constraints: dict[ValuedConstraint, Any] | None = None,+) -> InferenceModelSpec:+ return InferenceModelSpec(+ backend_name="openai",+ name="gpt-test",+ sdk="openai",+ model_type=ModelType.LLM,+ model_id="gpt-test-id",+ inputs=["text"],+ outputs=["text", "structured"],+ costs={CostCategory.INPUT: 1, CostCategory.OUTPUT: 2},+ thinking_mode=thinking_mode,+ max_tokens=max_tokens,+ max_prompt_images=None,+ listed_constraints=listed_constraints or [],+ valued_constraints=valued_constraints or {},+ )+++class TestConstrainedJobParams:+ def test_a_model_without_constraints_changes_nothing(self) -> None:+ job_params = LLMJobParams(temperature=0.5, max_tokens=None)+ assert LLMWorkerAbstract.constrained_job_params(inference_model=_make_model(thinking_mode=ThinkingMode.NONE), job_params=job_params) is None++ def test_a_scaled_temperature_doubles_and_takes_the_model_max_tokens(self) -> None:+ inference_model = _make_model(+ thinking_mode=ThinkingMode.NONE, max_tokens=8000, listed_constraints=[ListedConstraint.TEMPERATURE_MUST_BE_MULTIPLIED_BY_2]+ )+ constrained = LLMWorkerAbstract.constrained_job_params(inference_model=inference_model, job_params=LLMJobParams(temperature=0.25))+ assert constrained is not None+ assert constrained.temperature == 0.5+ assert constrained.max_tokens == 8000++ def test_a_fixed_temperature_replaces_the_one_asked_for(self) -> None:+ inference_model = _make_model(thinking_mode=ThinkingMode.MANUAL, valued_constraints={ValuedConstraint.FIXED_TEMPERATURE: 1})+ constrained = LLMWorkerAbstract.constrained_job_params(+ inference_model=inference_model, job_params=LLMJobParams(temperature=0.2, max_tokens=500, reasoning_effort=ReasoningEffort.HIGH)+ )+ assert constrained is not None+ assert constrained.temperature == 1+ assert constrained.max_tokens == 500+ assert constrained.reasoning_effort == ReasoningEffort.HIGH++ def test_a_fixed_temperature_already_asked_for_changes_nothing(self) -> None:+ inference_model = _make_model(thinking_mode=ThinkingMode.MANUAL, valued_constraints={ValuedConstraint.FIXED_TEMPERATURE: 1})+ assert LLMWorkerAbstract.constrained_job_params(inference_model=inference_model, job_params=LLMJobParams(temperature=1)) is Nonediff --git a/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.py b/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.pynew file mode 100644index 000000000..47faba9e2--- /dev/null+++ b/tests/unit/pipelex/cogt/llm/test_llm_worker_request_check.py@@ -0,0 +1,117 @@+from __future__ import annotations++from typing import TYPE_CHECKING++import pytest+from pydantic import BaseModel+from typing_extensions import override++from pipelex.cogt.exceptions import LLMCapabilityError+from pipelex.cogt.llm.llm_job import LLMJob+from pipelex.cogt.llm.llm_job_components import LLMJobConfig, LLMJobParams, ReasoningEffort+from pipelex.cogt.llm.llm_prompt import LLMPrompt+from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract+from pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.usage.cost_category import CostCategory+from pipelex.system.job_metadata import JobMetadata, RunMetadata++if TYPE_CHECKING:+ from pipelex.tools.typing.pydantic_utils import BaseModelTypeVar+++class _Answer(BaseModel):+ text: str+++class _RecordingLLMWorker(LLMWorkerAbstract):+ """A worker whose provider half records each call it is asked to make."""++ def __init__(self, *, inference_model: InferenceModelSpec) -> None:+ LLMWorkerAbstract.__init__(self, inference_model=inference_model, reporting_delegate=None)+ self.calls: list[str] = []++ @override+ async def _gen_text(self, llm_job: LLMJob) -> str:+ self.calls.append("text")+ return "answer"++ @override+ async def _gen_object(self, llm_job: LLMJob, *, schema: type[BaseModelTypeVar]) -> BaseModelTypeVar:+ self.calls.append("object")+ return schema.model_validate({"text": "answer"})+++def _make_model(*, thinking_mode: ThinkingMode) -> InferenceModelSpec:+ return InferenceModelSpec(+ backend_name="openai",+ name="gpt-test",+ sdk="openai",+ model_type=ModelType.LLM,+ model_id="gpt-test-id",+ inputs=["text"],+ outputs=["text", "structured"],+ costs={CostCategory.INPUT: 1, CostCategory.OUTPUT: 2},+ thinking_mode=thinking_mode,+ max_tokens=None,+ max_prompt_images=None,+ )+++def _make_llm_job(*, job_params: LLMJobParams) -> LLMJob:+ return LLMJob(+ job_metadata=JobMetadata(+ run_metadata=RunMetadata(user_id="pytest", pipeline_run_id="plr-check", storage_scope="test/scope", read_scope=None)+ ),+ llm_prompt=LLMPrompt(user_text="hello"),+ job_params=job_params,+ job_config=LLMJobConfig(schema_reask_max_attempts=1),+ )+++class TestLLMWorkerRequestCheck:+ @pytest.mark.parametrize(+ "job_params",+ [+ pytest.param(LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH), id="effort"),+ pytest.param(LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE), id="effort_none"),+ pytest.param(LLMJobParams(temperature=0.5, reasoning_budget=2048), id="budget"),+ ],+ )+ @pytest.mark.parametrize("is_structured", [False, True])+ def test_a_model_without_thinking_refuses_every_reasoning_setting(self, job_params: LLMJobParams, is_structured: bool) -> None:+ with pytest.raises(LLMCapabilityError, match=r"does not support reasoning \(thinking_mode=none\)"):+ LLMWorkerAbstract.check_request(+ inference_model=_make_model(thinking_mode=ThinkingMode.NONE), job_params=job_params, is_structured=is_structured+ )++ @pytest.mark.parametrize(+ ("thinking_mode", "job_params"),+ [+ pytest.param(ThinkingMode.NONE, LLMJobParams(temperature=0.5), id="no_thinking_no_setting"),+ pytest.param(ThinkingMode.MANUAL, LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH), id="manual_effort"),+ pytest.param(ThinkingMode.ADAPTIVE, LLMJobParams(temperature=0.5, reasoning_budget=2048), id="adaptive_budget"),+ ],+ )+ def test_the_shared_rule_passes_every_other_request(self, thinking_mode: ThinkingMode, job_params: LLMJobParams) -> None:+ LLMWorkerAbstract.check_request(inference_model=_make_model(thinking_mode=thinking_mode), job_params=job_params, is_structured=True)++ @pytest.mark.asyncio+ @pytest.mark.parametrize("is_structured", [False, True])+ async def test_a_refused_request_never_reaches_the_provider(self, is_structured: bool) -> None:+ worker = _RecordingLLMWorker(inference_model=_make_model(thinking_mode=ThinkingMode.NONE))+ llm_job = _make_llm_job(job_params=LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.LOW))+ invocation = worker.gen_object(llm_job=llm_job, schema=_Answer) if is_structured else worker.gen_text(llm_job=llm_job)+ with pytest.raises(LLMCapabilityError) as exc_info:+ await invocation+ assert worker.calls == []+ assert exc_info.value.to_error_report().model == "gpt-test"++ @pytest.mark.asyncio+ async def test_an_accepted_request_reaches_the_provider(self) -> None:+ worker = _RecordingLLMWorker(inference_model=_make_model(thinking_mode=ThinkingMode.MANUAL))+ llm_job = _make_llm_job(job_params=LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.LOW))+ await worker.gen_text(llm_job=llm_job)+ await worker.gen_object(llm_job=llm_job, schema=_Answer)+ assert worker.calls == ["text", "object"]diff --git a/tests/unit/pipelex/cogt/test_worker_error_enrichment.py b/tests/unit/pipelex/cogt/test_worker_error_enrichment.pyindex 61299b4fd..fe3ce4268 100644--- a/tests/unit/pipelex/cogt/test_worker_error_enrichment.py+++ b/tests/unit/pipelex/cogt/test_worker_error_enrichment.py@@ -27,6 +27,7 @@ from pipelex.cogt.exceptions import (from pipelex.cogt.extract.extract_worker_abstract import ExtractWorkerAbstractfrom pipelex.cogt.img_gen.img_gen_worker_abstract import ImgGenWorkerAbstractfrom pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract+from pipelex.cogt.llm.thinking_mode import ThinkingModefrom pipelex.cogt.search.search_worker_abstract import SearchWorkerAbstractif TYPE_CHECKING:@@ -139,6 +140,7 @@ def _make_inference_model(backend_name: str = WORKER_PROVIDER) -> SimpleNamespacdesc="stub-desc",max_tokens=None,max_prompt_images=None,+ thinking_mode=ThinkingMode.MANUAL,listed_constraints=[],valued_constraints={},is_img2img_supported=True,diff --git a/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.py b/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.pynew file mode 100644index 000000000..642945b3d--- /dev/null+++ b/tests/unit/pipelex/kernel/test_check_llm_setting_with_served_model.py@@ -0,0 +1,124 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Any++import pytest++from pipelex.base_exceptions import DisclosureMode+from pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedError, ModelWaterfallError+from pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffort+from pipelex.cogt.llm.llm_setting import LLMSetting+from pipelex.cogt.llm.thinking_mode import ThinkingMode+from pipelex.cogt.model_backends.constraints import ValuedConstraint+from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+from pipelex.cogt.model_backends.model_type import ModelType+from pipelex.cogt.usage.cost_category import CostCategory+from pipelex.kernel.llm_ops import check_llm_setting_with_served_model+from pipelex.plugins.inference_backend_registry import LLMRequestCheck+from pipelex.system.exceptions import MissingDependencyError++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++_SETTING = LLMSetting(model="@some-alias", temperature=0.2, reasoning_effort=ReasoningEffort.HIGH)+++def _make_model(*, thinking_mode: ThinkingMode, valued_constraints: dict[ValuedConstraint, Any] | None = None) -> InferenceModelSpec:+ return InferenceModelSpec(+ backend_name="some_backend",+ name="some-model",+ sdk="some_sdk",+ model_type=ModelType.LLM,+ model_id="some-model-id",+ inputs=["text"],+ outputs=["text", "structured"],+ costs={CostCategory.INPUT: 1, CostCategory.OUTPUT: 2},+ thinking_mode=thinking_mode,+ max_tokens=4096,+ max_prompt_images=None,+ valued_constraints=valued_constraints or {},+ )+++def _serve(mocker: MockerFixture, *, served: InferenceModelSpec | Exception | None, check: Any, is_builtin: bool = True) -> Any:+ """Patch the deck to serve `served` for any handle, and the registry to hand out `check` for any sdk; return the deck lookup."""+ deck = mocker.MagicMock()+ if isinstance(served, Exception):+ deck.get_optional_inference_model.side_effect = served+ else:+ deck.get_optional_inference_model.return_value = served+ mocker.patch("pipelex.kernel.llm_ops.get_model_deck", return_value=deck)+ registry = mocker.MagicMock()+ registry.lookup_llm_request_check.return_value = LLMRequestCheck(check=check, is_builtin=is_builtin) if check else None+ mocker.patch("pipelex.kernel.llm_ops.get_inference_backend_registry", return_value=registry)+ return deck.get_optional_inference_model+++class TestCheckLLMSettingWithServedModel:+ @pytest.mark.parametrize("is_structured", [False, True])+ def test_the_backend_check_runs_with_the_constrained_job_params(self, mocker: MockerFixture, is_structured: bool) -> None:+ """The registered check sees the job params the worker would send, the model's fixed temperature applied."""+ inference_model = _make_model(thinking_mode=ThinkingMode.MANUAL, valued_constraints={ValuedConstraint.FIXED_TEMPERATURE: 1})+ check = mocker.MagicMock()+ lookup = _serve(mocker, served=inference_model, check=check)++ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=is_structured)++ lookup.assert_called_once_with(model_handle="@some-alias", model_type=ModelType.LLM)+ check.assert_called_once_with(+ inference_model=inference_model,+ job_params=LLMJobParams(temperature=1, max_tokens=4096, reasoning_effort=ReasoningEffort.HIGH),+ is_structured=is_structured,+ )++ def test_a_backend_without_a_check_is_held_to_the_shared_rule(self, mocker: MockerFixture) -> None:+ """A model with no thinking takes no reasoning setting, whatever plugin serves it."""+ _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=None)+ with pytest.raises(LLMSettingRefusedError, match=r"does not support reasoning \(thinking_mode=none\)"):+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=True)++ def test_a_refusal_names_the_model_by_its_handle_and_is_shown_under_strict_disclosure(self, mocker: MockerFixture) -> None:+ """A worker names the model with its SDK, backend and provider id, which only its operator may see."""+ _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=None)+ with pytest.raises(LLMSettingRefusedError) as exc_info:+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)+ message = str(exc_info.value)+ assert message.startswith("Model 'some-model' does not support reasoning")+ for internal_name in ("some_sdk", "some_backend", "some-model-id"):+ assert internal_name not in message+ assert exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == message++ def test_an_external_plugin_s_refusal_is_raised_as_it_wrote_it(self, mocker: MockerFixture) -> None:+ """Its text may carry what the plugin keeps private, so it stays internal under strict disclosure."""+ refusal = LLMCapabilityError("Model 'some-model' is refused by tenant 1234 at internal.example")+ _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=mocker.MagicMock(side_effect=refusal), is_builtin=False)+ with pytest.raises(LLMCapabilityError) as exc_info:+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)+ assert exc_info.value is refusal+ assert "tenant 1234" not in exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"]++ def test_an_external_plugin_s_refusal_it_vouches_for_is_shown_under_strict_disclosure(self, mocker: MockerFixture) -> None:+ refusal = LLMCapabilityError("Model 'some-model' takes no reasoning").as_caller_fault()+ _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.NONE), check=mocker.MagicMock(side_effect=refusal), is_builtin=False)+ with pytest.raises(LLMCapabilityError) as exc_info:+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=False)+ assert exc_info.value.to_error_report().to_dict(disclosure_mode=DisclosureMode.STRICT)["message"] == "Model 'some-model' takes no reasoning"++ @pytest.mark.parametrize(+ "served",+ [+ pytest.param(None, id="not_served"),+ pytest.param(ModelWaterfallError(message="none served", model_handle="~some-waterfall", fallback_list=["a", "b"]), id="waterfall"),+ ],+ )+ def test_a_model_no_backend_serves_is_left_to_the_run(self, mocker: MockerFixture, served: InferenceModelSpec | Exception | None) -> None:+ check = mocker.MagicMock()+ _serve(mocker, served=served, check=check)+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=True)+ check.assert_not_called()++ def test_a_backend_whose_sdk_is_missing_is_left_to_the_run(self, mocker: MockerFixture) -> None:+ check = mocker.MagicMock(side_effect=MissingDependencyError("some-sdk", "some-extra"))+ _serve(mocker, served=_make_model(thinking_mode=ThinkingMode.MANUAL), check=check)+ check_llm_setting_with_served_model(llm_setting=_SETTING, is_structured=True)+ check.assert_called_once()diff --git a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py b/tests/unit/pipelex/kernel/test_kernel_boot_contract.pyindex 395432691..63c06904e 100644--- a/tests/unit/pipelex/kernel/test_kernel_boot_contract.py+++ b/tests/unit/pipelex/kernel/test_kernel_boot_contract.py@@ -17,8 +17,8 @@ what makes this test strictly stronger than the import-time one it complements.**Every kernel entry point is called, not a representative one** — the operator arms and thememory-boundary ops (`shape_inputs` and the extraction helpers), with the deck-reading helpers-(`resolve_*_setting`, `concrete_llm_model_handle`) the sole exception, for the deck reason given-below. The blind spot this test+(`resolve_*_setting`, `served_*_model`, `check_llm_setting_with_served_model`,+`concrete_llm_model_handle`) the sole exception, for the deck reason given below. The blind spot this testexists for is per-function, so covering one op says nothing about the next: a function-local importinside `run_search` is caught only by calling `run_search`. That also makes this the only gate theops modules other than `llm_ops` have — `PipelexKernel` is an LLM-era façade that does not importdiff --git a/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.py b/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.pynew file mode 100644index 000000000..0eb4e74bf--- /dev/null+++ b/tests/unit/pipelex/pipe_operators/shared/test_llm_setting_check.py@@ -0,0 +1,178 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING++import pytest++from pipelex.cogt.exceptions import LLMCapabilityError, LLMSettingRefusedError+from pipelex.cogt.llm.llm_job_components import ReasoningEffort+from pipelex.cogt.llm.llm_setting import LLMModelChoice, LLMSetting+from pipelex.cogt.models.model_reference import ModelReference+from pipelex.core.pipes.exceptions import PipeValidationError+from pipelex.pipe_operators.shared.llm_setting_check import refuse_llm_setting_its_model_refuses+from pipelex.validation_error_types import PipeValidationErrorType++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++_SETTING = LLMSetting(model="@some-alias", temperature=0.2, reasoning_effort=ReasoningEffort.HIGH)+_WORKER_REFUSAL = "Model 'some-model' does not support reasoning (thinking_mode=none)"+++class TestLLMSettingCheck:+ @classmethod+ def _patch_deck_overrides(cls, mocker: MockerFixture, *, for_text: LLMModelChoice | None, for_object: LLMModelChoice | None) -> None:+ deck = SimpleNamespace(llm_choice_overrides=SimpleNamespace(for_text=for_text, for_object=for_object))+ mocker.patch("pipelex.pipe_operators.shared.llm_setting_check.get_model_deck", return_value=deck)++ @pytest.mark.parametrize(+ ("llm_choice", "field_name", "is_structured", "expected_message", "expected_model_reference"),+ [+ pytest.param(+ ModelReference.parse("$deep-analysis"),+ "model",+ True,+ "PipeLLM 'answer_it' generates a structured output with the model setting `$deep-analysis` its `model` names, "+ f"which the model it resolves to refuses: {_WORKER_REFUSAL}. Name another setting in `model`, or one whose model takes it.",+ "$deep-analysis",+ id="preset_reference",+ ),+ pytest.param(+ _SETTING,+ "model_to_structure",+ True,+ "PipeLLM 'answer_it' generates a structured output with the model setting its `model_to_structure` writes inline, "+ f"which the model it resolves to refuses: {_WORKER_REFUSAL}. "+ "Change the setting in `model_to_structure`, or name a model that takes it.",+ None,+ id="inline_setting",+ ),+ pytest.param(+ None,+ None,+ False,+ "PipeLLM 'answer_it' generates text with the model deck's default setting for text, "+ f"which the model it resolves to refuses: {_WORKER_REFUSAL}. "+ "Name a model setting in the pipe, or change `for_text` in the deck's `[llm.choice_defaults]`.",+ None,+ id="deck_default_for_text",+ ),+ pytest.param(+ None,+ None,+ True,+ "PipeLLM 'answer_it' generates a structured output with the model deck's default setting for structured outputs, "+ f"which the model it resolves to refuses: {_WORKER_REFUSAL}. "+ "Name a model setting in the pipe, or change `for_object` in the deck's `[llm.choice_defaults]`.",+ None,+ id="deck_default_for_structured_outputs",+ ),+ ],+ )+ def test_a_refusal_names_the_pipe_the_setting_and_the_model_s_reason(+ self,+ mocker: MockerFixture,+ llm_choice: LLMModelChoice | None,+ field_name: str | None,+ is_structured: bool,+ expected_message: str,+ expected_model_reference: str | None,+ ) -> None:+ self._patch_deck_overrides(mocker, for_text=None, for_object=None)+ check = mocker.patch(+ "pipelex.pipe_operators.shared.llm_setting_check.check_llm_setting_with_served_model",+ side_effect=LLMSettingRefusedError(_WORKER_REFUSAL),+ )+ with pytest.raises(PipeValidationError) as exc_info:+ refuse_llm_setting_its_model_refuses(+ pipe_type="PipeLLM",+ pipe_code="answer_it",+ domain_code="some_domain",+ llm_setting=_SETTING,+ llm_choice=llm_choice,+ field_name=field_name,+ is_structured=is_structured,+ )+ check.assert_called_once_with(llm_setting=_SETTING, is_structured=is_structured)+ refusal = exc_info.value+ assert str(refusal) == expected_message+ assert refusal.error_type == PipeValidationErrorType.LLM_SETTING_REFUSED_BY_MODEL+ assert refusal.pipe_code == "answer_it"+ assert refusal.domain_code == "some_domain"+ assert refusal.field_name == field_name+ assert refusal.model_reference == expected_model_reference++ def test_a_setting_the_model_takes_passes(self, mocker: MockerFixture) -> None:+ mocker.patch("pipelex.pipe_operators.shared.llm_setting_check.check_llm_setting_with_served_model", return_value=None)+ refuse_llm_setting_its_model_refuses(+ pipe_type="PipeStructure",+ pipe_code="structure_it",+ domain_code="some_domain",+ llm_setting=_SETTING,+ llm_choice=_SETTING,+ field_name="model",+ is_structured=True,+ )++ @pytest.mark.parametrize(+ ("is_structured", "expected_setting", "expected_remedy"),+ [+ pytest.param(+ False,+ "the model deck's override for text",+ "change `for_text` in the deck's `[llm.choice_overrides]`.",+ id="text",+ ),+ pytest.param(+ True,+ "the model deck's override for structured outputs",+ "change `for_object` in the deck's `[llm.choice_overrides]`.",+ id="structured_output",+ ),+ ],+ )+ def test_a_deck_override_is_named_as_the_source_of_the_setting(+ self, mocker: MockerFixture, is_structured: bool, expected_setting: str, expected_remedy: str+ ) -> None:+ """The deck's chain reads its override before its default, so changing the default would not move the setting."""+ self._patch_deck_overrides(mocker, for_text=_SETTING, for_object=_SETTING)+ mocker.patch(+ "pipelex.pipe_operators.shared.llm_setting_check.check_llm_setting_with_served_model",+ side_effect=LLMSettingRefusedError(_WORKER_REFUSAL),+ )+ with pytest.raises(PipeValidationError) as exc_info:+ refuse_llm_setting_its_model_refuses(+ pipe_type="PipeLLM",+ pipe_code="answer_it",+ domain_code="some_domain",+ llm_setting=_SETTING,+ llm_choice=None,+ field_name=None,+ is_structured=is_structured,+ )+ message = str(exc_info.value)+ assert expected_setting in message+ assert message.endswith(expected_remedy)+ assert "choice_defaults" not in message++ def test_a_refusal_not_worded_for_the_caller_is_named_by_its_title(self, mocker: MockerFixture) -> None:+ """A worker's own refusal names the SDK and the backend, which a verdict kept under strict disclosure must not show."""+ self._patch_deck_overrides(mocker, for_text=None, for_object=None)+ mocker.patch(+ "pipelex.pipe_operators.shared.llm_setting_check.check_llm_setting_with_served_model",+ side_effect=LLMCapabilityError("Model 'some-model → SDK[internal]•Backend[internal]' refuses"),+ )+ with pytest.raises(PipeValidationError) as exc_info:+ refuse_llm_setting_its_model_refuses(+ pipe_type="PipeLLM",+ pipe_code="answer_it",+ domain_code="some_domain",+ llm_setting=_SETTING,+ llm_choice=_SETTING,+ field_name="model",+ is_structured=False,+ )+ message = str(exc_info.value)+ assert "internal" not in message+ assert "which the model it resolves to refuses: LLM capability. " in messagediff --git a/tests/unit/pipelex/plugins/test_llm_request_checks.py b/tests/unit/pipelex/plugins/test_llm_request_checks.pynew file mode 100644index 000000000..1e6a55bb9--- /dev/null+++ b/tests/unit/pipelex/plugins/test_llm_request_checks.py@@ -0,0 +1,98 @@+from __future__ import annotations++from types import SimpleNamespace+from typing import TYPE_CHECKING, cast++import pytest++from pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffort+from pipelex.interpreter_plugins.builtins import BUILTIN_PLUGINS+from pipelex.plugins.inference_backend_registry import InferenceBackendRegistry, InferenceFamily, LLMRequestCheck+from pipelex.plugins.registrar import PluginOrigin, PluginRegistrar+from pipelex.providers.anthropic.anthropic_llm_worker import AnthropicLLMWorker+from pipelex.providers.bedrock.bedrock_llm_worker import BedrockLLMWorker+from pipelex.providers.google.google_llm_worker import GoogleLLMWorker+from pipelex.providers.mistral.mistral_llm_worker import MistralLLMWorker+from pipelex.providers.openai.openai_completions_llm_worker import OpenAICompletionsLLMWorker+from pipelex.providers.openai.openai_responses_llm_worker import OpenAIResponsesLLMWorker++if TYPE_CHECKING:+ from pytest_mock import MockerFixture++ from pipelex.cogt.llm.llm_worker_abstract import LLMWorkerAbstract+ from pipelex.cogt.model_backends.model_spec import InferenceModelSpec+ from pipelex.system.configuration.configs import PipelexConfig+++def _build_registrar() -> PluginRegistrar:+ registrar = PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace()))+ for plugin in BUILTIN_PLUGINS:+ plugin.register(registrar)+ return registrar+++class TestLLMRequestChecks:+ def test_every_built_in_llm_backend_registers_its_check(self) -> None:+ """Validation can check a model on any built-in LLM sdk against the worker that serves it."""+ registrar = _build_registrar()+ llm_sdks = {sdk for family, sdk in registrar.inference_backends if family == InferenceFamily.LLM}+ assert llm_sdks+ assert set(registrar.llm_request_checks) == llm_sdks+ assert all(registered_check.is_builtin for registered_check in registrar.llm_request_checks.values())++ @pytest.mark.parametrize(+ ("sdk", "worker_class"),+ [+ ("openai", OpenAICompletionsLLMWorker),+ ("azure_openai", OpenAICompletionsLLMWorker),+ ("openai_responses", OpenAIResponsesLLMWorker),+ ("azure_openai_responses", OpenAIResponsesLLMWorker),+ ("portkey_completions", OpenAICompletionsLLMWorker),+ ("portkey_responses", OpenAIResponsesLLMWorker),+ ("anthropic", AnthropicLLMWorker),+ ("bedrock_anthropic", AnthropicLLMWorker),+ ("mistral", MistralLLMWorker),+ ("google", GoogleLLMWorker),+ ("bedrock_boto3", BedrockLLMWorker),+ ("bedrock_aioboto", BedrockLLMWorker),+ ],+ )+ def test_each_check_is_the_check_of_the_worker_its_backend_builds(+ self, mocker: MockerFixture, sdk: str, worker_class: type[LLMWorkerAbstract]+ ) -> None:+ """The registered check delegates to the worker class's own check_request, which the worker runs before every call."""+ registrar = _build_registrar()+ registry = InferenceBackendRegistry(registrar.inference_backends, llm_request_checks=registrar.llm_request_checks)+ registered_check = registry.lookup_llm_request_check(sdk=sdk)+ assert registered_check is not None+ check_request = registered_check.check+ worker_check = mocker.patch.object(worker_class, "check_request")+ inference_model = cast("InferenceModelSpec", mocker.MagicMock())+ job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)++ check_request(inference_model=inference_model, job_params=job_params, is_structured=True)++ worker_check.assert_called_once_with(inference_model=inference_model, job_params=job_params, is_structured=True)++ def test_a_check_outlives_a_family_swap_and_only_the_llm_family_records_one(self, mocker: MockerFixture) -> None:+ """Standing stub workers in for a family keeps the checks; a check registered on another family is never read."""+ registrar = PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace()))+ llm_check = mocker.MagicMock()+ registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="some_llm", make_worker=mocker.MagicMock(), check_llm_request=llm_check)+ registrar.add_inference_backend(+ family=InferenceFamily.IMG_GEN, sdk="some_img_gen", make_worker=mocker.MagicMock(), check_llm_request=mocker.MagicMock()+ )+ assert registrar.llm_request_checks == {"some_llm": LLMRequestCheck(check=llm_check, is_builtin=True)}++ registry = InferenceBackendRegistry(registrar.inference_backends, llm_request_checks=registrar.llm_request_checks)+ swapped = registry.with_family(family=InferenceFamily.LLM, backends={})+ assert swapped.lookup_llm_request_check(sdk="some_llm") == LLMRequestCheck(check=llm_check, is_builtin=True)+ assert swapped.lookup_llm_request_check(sdk="unregistered") is None++ def test_an_external_plugin_s_check_is_recorded_as_not_built_in(self, mocker: MockerFixture) -> None:+ """Its refusals reach a caller only when it vouches for them, so validation must know who registered it."""+ registrar = PluginRegistrar(config=cast("PipelexConfig", SimpleNamespace()))+ registrar.begin_plugin(name="some_plugin", origin=PluginOrigin.EXTERNAL, targets_api=1, group=None)+ llm_check = mocker.MagicMock()+ registrar.add_inference_backend(family=InferenceFamily.LLM, sdk="some_llm", make_worker=mocker.MagicMock(), check_llm_request=llm_check)+ assert registrar.llm_request_checks == {"some_llm": LLMRequestCheck(check=llm_check, is_builtin=False)}diff --git a/tests/unit/pipelex/providers/anthropic/test_anthropic_reasoning.py b/tests/unit/pipelex/providers/anthropic/test_anthropic_reasoning.pyindex 97f323d1d..17046591f 100644--- a/tests/unit/pipelex/providers/anthropic/test_anthropic_reasoning.py+++ b/tests/unit/pipelex/providers/anthropic/test_anthropic_reasoning.py@@ -67,7 +67,7 @@ class TestAnthropicReasoning:budget_mock = mocker.MagicMock(return_value=expected_budget)_mock_config(mocker, budget_mock=budget_mock)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": expected_budget}assert result.suppress_temperature is Truebudget_mock.assert_called_once_with(family="anthropic", effort=effort)@@ -77,13 +77,13 @@ class TestAnthropicReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)_mock_config(mocker, budget_mock=mocker.MagicMock(return_value=512))job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.MINIMAL)- result = worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": 1024}def test_explicit_budget_under_the_minimum_is_raised_to_it(self, mocker: MockerFixture):worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=200)- result = worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": 1024}def test_max_tokens_too_small_for_the_minimum_budget_is_refused(self, mocker: MockerFixture):@@ -92,14 +92,54 @@ class TestAnthropicReasoning:_mock_config(mocker, budget_mock=mocker.MagicMock(return_value=1024))job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.LOW)with pytest.raises(LLMCapabilityError, match="max_tokens=1200"):- worker._build_thinking_params(job_params=job_params, max_tokens=1200) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=1200) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]++ @pytest.mark.parametrize("is_structured", [False, True])+ @pytest.mark.parametrize(+ ("job_max_tokens", "model_max_tokens"),+ [+ pytest.param(1200, 64000, id="the_job_s_max_tokens"),+ pytest.param(None, 1200, id="the_model_s_max_tokens"),+ ],+ )+ def test_check_request_fits_the_budget_against_the_max_tokens_the_call_sends(+ self, mocker: MockerFixture, is_structured: bool, job_max_tokens: int | None, model_max_tokens: int+ ):+ """The request check refuses what the call would: a minimum budget the call's max_tokens cannot hold beside the answer."""+ worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)+ worker.inference_model.max_tokens = model_max_tokens+ _mock_config(mocker, budget_mock=mocker.MagicMock(return_value=1024))+ job_params = LLMJobParams(temperature=0.5, max_tokens=job_max_tokens, reasoning_effort=ReasoningEffort.LOW)+ with pytest.raises(LLMCapabilityError, match="max_tokens=1200"):+ AnthropicLLMWorker.check_request(inference_model=worker.inference_model, job_params=job_params, is_structured=is_structured)++ def test_check_request_without_any_max_tokens_fits_no_budget(self, mocker: MockerFixture):+ """A model declaring no max_tokens cannot be built a worker for, so its check fits no budget and leaves the refusal to the build."""+ worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)+ worker.inference_model.max_tokens = None+ _mock_config(mocker, budget_mock=mocker.MagicMock(return_value=65536))+ job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.MAX)+ AnthropicLLMWorker.check_request(inference_model=worker.inference_model, job_params=job_params, is_structured=True)++ @pytest.mark.parametrize(+ ("is_structured", "expected_max_tokens"),+ [+ pytest.param(False, 64000, id="text_sends_what_it_asks"),+ pytest.param(True, 42666, id="structured_is_held_to_its_timeout"),+ ],+ )+ def test_a_structured_call_sends_the_max_tokens_its_timeout_allows(self, mocker: MockerFixture, is_structured: bool, expected_max_tokens: int):+ """A structured call's explicit 1,200-second timeout holds its max_tokens to what the SDK's heuristic lets that timeout produce."""+ _mock_config(mocker)+ sent_max_tokens = AnthropicLLMWorker._sent_max_tokens(requested_max_tokens=64000, is_structured=is_structured) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ assert sent_max_tokens == expected_max_tokensdef test_a_model_declaring_no_minimum_is_sent_the_fitted_budget(self, mocker: MockerFixture):"""A server behind the anthropic SDK that declares no minimum, MiniMax among them, is neither raised nor refused."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL, min_thinking_budget=None)_mock_config(mocker, budget_mock=mocker.MagicMock(return_value=1024))job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.LOW)- result = worker._build_thinking_params(job_params=job_params, max_tokens=1200) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=1200) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": 900}def test_manual_mode_effort_none_disables_thinking(self, mocker: MockerFixture):@@ -108,7 +148,7 @@ class TestAnthropicReasoning:budget_mock = mocker.MagicMock()_mock_config(mocker, budget_mock=budget_mock)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE)- result = worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking is Noneassert result.suppress_temperature is Falsebudget_mock.assert_not_called()@@ -119,14 +159,14 @@ class TestAnthropicReasoning:budget_mock = mocker.MagicMock(return_value=16384)_mock_config(mocker, budget_mock=budget_mock)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)- result = worker._build_thinking_params(job_params=job_params, max_tokens=2000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=2000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": 1500}def test_explicit_budget_passes_through(self, mocker: MockerFixture):"""Explicit reasoning_budget passes through directly as budget_tokens in MANUAL mode."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=8192)- result = worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result.thinking == {"type": "enabled", "budget_tokens": 8192}assert result.suppress_temperature is True@@ -135,4 +175,4 @@ class TestAnthropicReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._build_thinking_params(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_params(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]diff --git a/tests/unit/pipelex/providers/bedrock/test_bedrock_reasoning.py b/tests/unit/pipelex/providers/bedrock/test_bedrock_reasoning.pyindex a41768cba..fe0df3d3c 100644--- a/tests/unit/pipelex/providers/bedrock/test_bedrock_reasoning.py+++ b/tests/unit/pipelex/providers/bedrock/test_bedrock_reasoning.py@@ -1,28 +1,26 @@+from typing import cast+import pytestfrom pytest_mock import MockerFixturefrom pipelex.cogt.exceptions import LLMCapabilityErrorfrom pipelex.cogt.llm.llm_job_components import LLMJobParams, ReasoningEffort+from pipelex.cogt.model_backends.model_spec import InferenceModelSpecfrom pipelex.providers.bedrock.bedrock_llm_worker import BedrockLLMWorker-def _make_worker(mocker: MockerFixture) -> BedrockLLMWorker:- """Create a minimal BedrockLLMWorker with a mocked inference_model."""- worker = object.__new__(BedrockLLMWorker)+def _make_model(mocker: MockerFixture) -> InferenceModelSpec:+ """A mocked spec, for a check that reads nothing but the model's description."""mock_model = mocker.MagicMock()mock_model.desc = "test-bedrock-model"- worker.inference_model = mock_model- return worker+ return cast("InferenceModelSpec", mock_model)class TestBedrockReasoning:- """Tests for reasoning parameter validation on BedrockLLMWorker."""-def test_no_reasoning_params_passes(self, mocker: MockerFixture):- """Validation passes when no reasoning params are set."""- worker = _make_worker(mocker)+ """A text request with no reasoning setting passes."""job_params = LLMJobParams(temperature=0.5)- worker._validate_no_reasoning_params(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ BedrockLLMWorker.check_request(inference_model=_make_model(mocker), job_params=job_params, is_structured=False)@pytest.mark.parametrize("effort",@@ -37,14 +35,18 @@ class TestBedrockReasoning:)def test_reasoning_effort_raises_capability_error(self, mocker: MockerFixture, effort: ReasoningEffort):"""Any reasoning_effort value should raise LLMCapabilityError for Bedrock."""- worker = _make_worker(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)with pytest.raises(LLMCapabilityError, match="does not support reasoning parameters"):- worker._validate_no_reasoning_params(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ BedrockLLMWorker.check_request(inference_model=_make_model(mocker), job_params=job_params, is_structured=False)def test_reasoning_budget_raises_capability_error(self, mocker: MockerFixture):"""reasoning_budget should raise LLMCapabilityError for Bedrock."""- worker = _make_worker(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning parameters"):- worker._validate_no_reasoning_params(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ BedrockLLMWorker.check_request(inference_model=_make_model(mocker), job_params=job_params, is_structured=False)++ def test_structured_output_raises_capability_error(self, mocker: MockerFixture):+ """A structured output is refused, with or without a reasoning setting: the worker cannot generate objects."""+ job_params = LLMJobParams(temperature=0.5)+ with pytest.raises(LLMCapabilityError, match="Model 'test-bedrock-model' does not support structured outputs"):+ BedrockLLMWorker.check_request(inference_model=_make_model(mocker), job_params=job_params, is_structured=True)diff --git a/tests/unit/pipelex/providers/google/test_google_reasoning.py b/tests/unit/pipelex/providers/google/test_google_reasoning.pyindex d87c72453..2b3a2ac0a 100644--- a/tests/unit/pipelex/providers/google/test_google_reasoning.py+++ b/tests/unit/pipelex/providers/google/test_google_reasoning.py@@ -91,7 +91,7 @@ class TestGoogleReasoning:),)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == expected_budgetbudget_mock.assert_called_once_with(family="gemini", effort=effort)@@ -117,7 +117,7 @@ class TestGoogleReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE)_mock_config_for_adaptive(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_level == expected_level@@ -136,7 +136,7 @@ class TestGoogleReasoning:),)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 0@@ -145,7 +145,7 @@ class TestGoogleReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE)_mock_config_for_adaptive(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 0@@ -156,13 +156,13 @@ class TestGoogleReasoning:_mock_config_for_adaptive(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE)with pytest.raises(LLMCapabilityError, match="cannot turn thinking off"):- worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_another_effort_still_thinks_on_a_model_that_cannot_turn_thinking_off(self, mocker: MockerFixture):worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE, listed_constraints=[ListedConstraint.THINKING_CANNOT_BE_DISABLED])_mock_config_for_adaptive(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.LOW)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_level == genai_types.ThinkingLevel.LOW@@ -178,7 +178,7 @@ class TestGoogleReasoning:"""Explicit reasoning_budget passes through directly as thinking_budget."""worker = _make_worker(mocker, thinking_mode=thinking_mode)job_params = LLMJobParams(temperature=0.5, reasoning_budget=8192)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 8192@@ -186,7 +186,7 @@ class TestGoogleReasoning:"""When neither reasoning_effort nor reasoning_budget is set, returns None."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5)- result = worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is Nonedef test_thinking_mode_none_raises_capability_error(self, mocker: MockerFixture):@@ -194,20 +194,20 @@ class TestGoogleReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_reasoning_budget_with_thinking_mode_none_raises(self, mocker: MockerFixture):"""reasoning_budget with thinking_mode=none should raise LLMCapabilityError."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._build_thinking_config(job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=100000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_explicit_budget_capped_by_max_tokens(self, mocker: MockerFixture):"""Explicit reasoning_budget is capped to leave a quarter of max_tokens for the answer."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=8192)- result = worker._build_thinking_config(job_params=job_params, max_tokens=4000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=4000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 3000@@ -227,7 +227,7 @@ class TestGoogleReasoning:),)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)- result = worker._build_thinking_config(job_params=job_params, max_tokens=2000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=2000) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 1500@@ -258,7 +258,7 @@ class TestGoogleReasoning:mocker, thinking_mode=ThinkingMode.MANUAL, min_thinking_budget=min_thinking_budget, max_thinking_budget=max_thinking_budget)job_params = LLMJobParams(temperature=0.5, reasoning_budget=reasoning_budget)- result = worker._build_thinking_config(job_params=job_params, max_tokens=max_tokens) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=max_tokens) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == expected_budget@@ -278,7 +278,7 @@ class TestGoogleReasoning:),)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.MAX)- result = worker._build_thinking_config(job_params=job_params, max_tokens=None) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=None) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.thinking_budget == 32768@@ -287,4 +287,4 @@ class TestGoogleReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL, min_thinking_budget=512, max_thinking_budget=24576)job_params = LLMJobParams(temperature=0.5, reasoning_budget=1024)with pytest.raises(LLMCapabilityError, match="max_tokens=600"):- worker._build_thinking_config(job_params=job_params, max_tokens=600) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._build_thinking_config(inference_model=worker.inference_model, job_params=job_params, max_tokens=600) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]diff --git a/tests/unit/pipelex/providers/mistral/test_mistral_reasoning.py b/tests/unit/pipelex/providers/mistral/test_mistral_reasoning.pyindex 789284189..c4f394f58 100644--- a/tests/unit/pipelex/providers/mistral/test_mistral_reasoning.py+++ b/tests/unit/pipelex/providers/mistral/test_mistral_reasoning.py@@ -52,14 +52,14 @@ class TestMistralReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_reasoning_budget_with_thinking_mode_manual_raises(self, mocker: MockerFixture):"""reasoning_budget with thinking_mode=manual raises with 'reasoning_effort' guidance."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning_budget; Mistral uses reasoning_effort instead"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]@pytest.mark.parametrize(("effort", "expected_mistral_effort"),@@ -82,7 +82,7 @@ class TestMistralReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)_mock_config(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result == expected_mistral_effortdef test_thinking_mode_none_raises_capability_error(self, mocker: MockerFixture):@@ -90,14 +90,14 @@ class TestMistralReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_thinking_mode_adaptive_raises_capability_error(self, mocker: MockerFixture):"""Adaptive thinking mode is not applicable to Mistral models."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="adaptive"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_none_effort_omits_the_parameter(self, mocker: MockerFixture):"""NONE maps to disabled, so the parameter is left out and the model does not reason."""@@ -106,7 +106,7 @@ class TestMistralReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)_mock_config(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.NONE)- result = worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is UNSETdef test_no_reasoning_params_returns_unset(self, mocker: MockerFixture):@@ -115,5 +115,5 @@ class TestMistralReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5)- result = worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is UNSETdiff --git a/tests/unit/pipelex/providers/mistral/test_mistral_structured_request.py b/tests/unit/pipelex/providers/mistral/test_mistral_structured_request.pyindex 61031ead9..0933a2114 100644--- a/tests/unit/pipelex/providers/mistral/test_mistral_structured_request.py+++ b/tests/unit/pipelex/providers/mistral/test_mistral_structured_request.py@@ -63,7 +63,10 @@ class TestMistralStructuredRequest:complete_async.assert_not_awaited()async def test_a_json_structure_method_refuses_reasoning(self, mocker: MockerFixture) -> None:- """A reasoning reply's content is a list of chunks, which instructor's JSON parsers cannot read, so the call is refused up front."""+ """A reasoning reply's content is a list of chunks, which instructor's JSON parsers cannot read, so the request check refuses it.++ The worker runs its request check before every call (``gen_object``), and validation runs the same one.+ """worker, complete_async = make_worker(mocker,thinking_mode=ThinkingMode.MANUAL,@@ -74,5 +77,6 @@ class TestMistralStructuredRequest:llm_job.job_params.reasoning_effort = ReasoningEffort.HIGHwith pytest.raises(LLMCapabilityError, match="instructor/mistral_tools"):- await worker._gen_object(llm_job=llm_job, schema=DummySchema) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker.check_request(inference_model=worker.inference_model, job_params=llm_job.job_params, is_structured=True)+ worker.check_request(inference_model=worker.inference_model, job_params=llm_job.job_params, is_structured=False)complete_async.assert_not_awaited()diff --git a/tests/unit/pipelex/providers/openai/test_openai_completions_reasoning.py b/tests/unit/pipelex/providers/openai/test_openai_completions_reasoning.pyindex a0b391b6d..15a9d40ea 100644--- a/tests/unit/pipelex/providers/openai/test_openai_completions_reasoning.py+++ b/tests/unit/pipelex/providers/openai/test_openai_completions_reasoning.py@@ -69,14 +69,14 @@ class TestOpenAICompletionsReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)_mock_config(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result == expected_openai_effortdef test_no_reasoning_params_returns_none(self, mocker: MockerFixture):"""When neither reasoning_effort nor reasoning_budget is set, returns None."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5)- result = worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is Nonedef test_reasoning_budget_raises_capability_error(self, mocker: MockerFixture):@@ -84,25 +84,25 @@ class TestOpenAICompletionsReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="reasoning_budget"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_thinking_mode_none_raises_capability_error(self, mocker: MockerFixture):"""Models with thinking_mode=none should raise LLMCapabilityError."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_thinking_mode_adaptive_raises_capability_error(self, mocker: MockerFixture):"""Adaptive thinking mode is not applicable to OpenAI models."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="adaptive"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_reasoning_budget_with_thinking_mode_none_raises(self, mocker: MockerFixture):"""reasoning_budget with thinking_mode=none gives an accurate 'does not support reasoning' error."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning_effort(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning_effort(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]diff --git a/tests/unit/pipelex/providers/openai/test_openai_responses_reasoning.py b/tests/unit/pipelex/providers/openai/test_openai_responses_reasoning.pyindex 25486e525..38aa2d518 100644--- a/tests/unit/pipelex/providers/openai/test_openai_responses_reasoning.py+++ b/tests/unit/pipelex/providers/openai/test_openai_responses_reasoning.py@@ -69,7 +69,7 @@ class TestOpenAIResponsesReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)_mock_config(mocker)job_params = LLMJobParams(temperature=0.5, reasoning_effort=effort)- result = worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is not Noneassert result.get("effort") == expected_openai_effort@@ -77,7 +77,7 @@ class TestOpenAIResponsesReasoning:"""When neither reasoning_effort nor reasoning_budget is set, returns None."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5)- result = worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ result = worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]assert result is Nonedef test_reasoning_budget_raises_capability_error(self, mocker: MockerFixture):@@ -85,25 +85,25 @@ class TestOpenAIResponsesReasoning:worker = _make_worker(mocker, thinking_mode=ThinkingMode.MANUAL)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="reasoning_budget"):- worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_thinking_mode_none_raises_capability_error(self, mocker: MockerFixture):"""Models with thinking_mode=none should raise LLMCapabilityError."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_thinking_mode_adaptive_raises_capability_error(self, mocker: MockerFixture):"""Adaptive thinking mode is not applicable to OpenAI models."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.ADAPTIVE)job_params = LLMJobParams(temperature=0.5, reasoning_effort=ReasoningEffort.HIGH)with pytest.raises(LLMCapabilityError, match="adaptive"):- worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]def test_reasoning_budget_with_thinking_mode_none_raises(self, mocker: MockerFixture):"""reasoning_budget with thinking_mode=none gives an accurate 'does not support reasoning' error."""worker = _make_worker(mocker, thinking_mode=ThinkingMode.NONE)job_params = LLMJobParams(temperature=0.5, reasoning_budget=4096)with pytest.raises(LLMCapabilityError, match="does not support reasoning"):- worker._resolve_reasoning(job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ worker._resolve_reasoning(inference_model=worker.inference_model, job_params=job_params) # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]