Repository navigation
fix(py): middleware sees the model's config class; a swapped-in config fails naming the middleware - #6632
Merged
huangjeff5 merged 18 commits intoOct 8, 2026
Conversation
Contributor
There was a problem hiding this comment.
Code Review
This pull request introduces middleware config validation to ensure that middleware edits the existing config object in-place rather than replacing it with an incompatible type, and that any field modifications are properly validated. It also updates the fallback middleware to correctly handle backup models sharing the same config class. The review feedback suggests optimizing the fallback request creation by directly instantiating ModelRequest to avoid validation overhead, and improving the robustness of the config validation logic in _model.py to support Pydantic models configured with slots=True.
…g fails naming the middleware
huangjeff5
force-pushed
the
fix/py-middleware-config-one-shape
branch
from
October 7, 2026 07:13
3bf547f to
7620e33
Compare
huangjeff5
changed the base branch from
fix/py-model-config-any-model
to
fix/py-define-returns-ref
October 7, 2026 07:13
Pydantic rejects typing.TypedDict before 3.12, so a model function annotated request: ModelRequest[Cfg] with a stdlib TypedDict raised PydanticUserError when the function was defined. ModelRequest.__class_getitem__ now swaps in a typing_extensions copy (same name, module, fields, required keys; nested TypedDicts too) before Pydantic builds the parametrized class. No-op on 3.12+.
…on < 3.12" This reverts commit 3ad605d.
ModelRequest[X] raises GenkitError(INVALID_ARGUMENT) when X isn't a pydantic BaseModel subclass (TypedDict, dict, unions). The check runs in __class_getitem__, where the annotation is evaluated, so it fires when the model function is defined and reads the same on every Python version; before, typing.TypedDict crashed inside Pydantic on 3.10/3.11. Bare ModelRequest and ModelRequest[Any] still take config as a mapping. declared_config_type now returns only pydantic classes, so generate drops is_model_class and ModelRequest drops the dict branch.
apascal07
approved these changes
Oct 7, 2026
…est[TypedDict] under deferred annotations - MiddlewareConfigCheck: each handoff compares a model_dump snapshot by value and validates the whole dump on change, so edits inside a field and model validators are checked; changed fields are written back parsed. - A rejection is remembered with the values it saw, so a retry that fixes the value reaches the model and one that doesn't still names the inner layer. - _resolve_one leaves only NameError as a string, so define_model raises the ModelRequest[X] config-type error under from __future__ / Python 3.14.
…fix/py-middleware-config-one-shape # Conflicts: # py/packages/genkit-middleware/src/genkit_middleware/_fallback.py # py/packages/genkit-middleware/tests/fallback_test.py
…fix/py-middleware-config-one-shape
…g-one-shape # Conflicts: # py/packages/genkit/src/genkit/_ai/_generate.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
generate turns the call's config into the model's config class once. Middleware and the model now get that same object. A middleware that puts a different shape back fails the turn and the error names that middleware.
Stacked on #6598 (config stack: #6587 → #6592 → #6593 → #6595 → #6596 → #6597 → #6598).
Main Changes
request.configwent straight to the plugin. Now each time a middleware callsnext_fn, the config must still be the model's class, or the turn fails naming that middleware. We reject instead of re-translating because re-translating would let the outer middleware and the model see different objects again.config.temperature = 'hot',model_copy(update=...), or edits inside a field (config.stop_sequences.append(5),config.thinking.budget_tokens = 10). Each handoff dumps the config and compares it with the dump from the last passing check. If anything differs, the whole dump goes throughmodel_validate, so nested bounds and model validators (Anthropic's_check_thinking,_check_api_surface) run on the config the next layer gets. Fields that changed are written back parsed, soconfig.task_budget = {'total': 1}reaches the model asTaskBudget. Untouched fields keep their objects, so a non-idempotent validator doesn't compound across layers and aField(frozen=True)field passes.model_fields_setdoesn't change, soexclude_unsetdumps are unaffected.next_fnwith those values unchanged gets the same error naming the inner layer. One that fixes the value and retries reaches the model.validate_assignmentonModelConfig: That was the first try. Errors inside the generate loop come back boxed asfinish_reason=FAILED, and a raw pydanticValidationErrorsurfaces as "internal error". The handoff check raises aGenkitErrorwith the model, middleware, and field in the message.next_fn, with a copy of the primary's typed request. When both models share a config class, the backup got a dict orNone. It now builds a plainModelRequest, so the backup parses its config like any other call.ModelRequestare unchanged: The check runs only when generate built a pydantic config. If the model takes plainModelRequest, or the config didn't fit and generate fell back, middleware dicts pass through and the action reports the problem itself.ModelRequest[X]takes a pydantic model only:ModelRequest[SomeTypedDict]orModelRequest[dict]now raisesGenkitError(INVALID_ARGUMENT)where the annotation is evaluated: atdeffor eager annotations, atdefine_modelwithfrom __future__ import annotationsor on 3.14. The message is the same either way. Annotation resolution leaves only a missing name (NameError) as a string, so this error isn't swallowed. Before, a TypedDict config skipped the handoff check, andtyping.TypedDictcrashed inside Pydantic on 3.10/3.11. Take config as a dict with bareModelRequest.Breaking: middleware that assigned a dict or
Nonetorequest.configon a typed model now fails the turn. Change fields on the config object instead.ModelRequest[X]whereXisn't a pydantic model now raises at definition.Tests
middleware_config_shape_test.py: same class in every layer, in-place andmodel_copyedits, dict/None/other-class rejection, bad values, nested dicts, edits inside a list or nested model, model validators, unknown keys, blame on the inner layer (also when an outer layer retriesnext_fn), an outer retry after fixing the value reaches the model, untouched fields not re-validated, plain-ModelRequestmodels.model_definition_contract_test.py:ModelRequest[X]rejectstyping.TypedDict,typing_extensions.TypedDict,dict,dict[str, Any], and unions; a TypedDict config is rejected throughdefine_modelunder deferred annotations (future import; lazy on 3.14);ModelRequest[Any]still registers.anthropic_generate_test.py: middleware edits insidethinking/output_confighitge=1024,_check_thinking, and_check_api_surface; nothing is sent.fallback_test.py: a backup that shares the primary's class gets that class for ref and string entries.