Skip to content

fix(py): middleware sees the model's config class; a swapped-in config fails naming the middleware - #6632

Merged
huangjeff5 merged 18 commits into
fix/py-define-returns-reffrom
fix/py-middleware-config-one-shape
Oct 8, 2026
Merged

huangjeff5 merged 18 commits into
fix/py-define-returns-reffrom
fix/py-middleware-config-one-shape

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

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).

class Clamp(BaseMiddleware):
    async def wrap_model(self, params, ctx, next_fn):
        cfg = params.request.config
        # => OpenAIConfig(temperature=0.9, ...), the plugin's class, same as the model sees

        # 1. Change fields in place: reaches inner middleware and the model
        cfg.temperature = min(cfg.temperature or 1.0, 0.5)

        # 2. Swap in a dict: before, the model got a dict (or None); now the turn fails
        params.request.config = {'temperature': 0.5}
        return await next_fn(params, ctx)

res = await ai.generate(model='openai/gpt-4o', prompt='hi', config={'temperature': 0.9}, use=[Clamp()])
res.finish_message
# => openai/gpt-4o: middleware 'Clamp' replaced request.config with dict; change fields on request.config instead

Main Changes

  • Translate once, check at each handoff: Previously, generate typed the config before middleware ran, but the action only re-parses a request that isn't already its typed class. Pydantic skips revalidating an instance of the right class, so a dict a middleware assigned to request.config went straight to the plugin. Now each time a middleware calls next_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.
  • Checked by value at each handoff, stored parsed: Pydantic doesn't validate 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 through model_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, so config.task_budget = {'total': 1} reaches the model as TaskBudget. Untouched fields keep their objects, so a non-idempotent validator doesn't compound across layers and a Field(frozen=True) field passes. model_fields_set doesn't change, so exclude_unset dumps are unaffected.
  • Blame stays with the layer that made the change: a failed check is remembered with the config values it saw. An outer layer that retries next_fn with those values unchanged gets the same error naming the inner layer. One that fixes the value and retries reaches the model.
  • No validate_assignment on ModelConfig: That was the first try. Errors inside the generate loop come back boxed as finish_reason=FAILED, and a raw pydantic ValidationError surfaces as "internal error". The handoff check raises a GenkitError with the model, middleware, and field in the message.
  • Fallback builds a plain request for the backup: Fallback calls the backup action directly, not through next_fn, with a copy of the primary's typed request. When both models share a config class, the backup got a dict or None. It now builds a plain ModelRequest, so the backup parses its config like any other call.
  • Models typed as plain ModelRequest are unchanged: The check runs only when generate built a pydantic config. If the model takes plain ModelRequest, 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] or ModelRequest[dict] now raises GenkitError(INVALID_ARGUMENT) where the annotation is evaluated: at def for eager annotations, at define_model with from __future__ import annotations or 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, and typing.TypedDict crashed inside Pydantic on 3.10/3.11. Take config as a dict with bare ModelRequest.

Breaking: middleware that assigned a dict or None to request.config on a typed model now fails the turn. Change fields on the config object instead. ModelRequest[X] where X isn't a pydantic model now raises at definition.

Tests

  • middleware_config_shape_test.py: same class in every layer, in-place and model_copy edits, 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 retries next_fn), an outer retry after fixing the value reaches the model, untouched fields not re-validated, plain-ModelRequest models.
  • model_definition_contract_test.py: ModelRequest[X] rejects typing.TypedDict, typing_extensions.TypedDict, dict, dict[str, Any], and unions; a TypedDict config is rejected through define_model under deferred annotations (future import; lazy on 3.14); ModelRequest[Any] still registers.
  • anthropic_generate_test.py: middleware edits inside thinking / output_config hit ge=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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@huangjeff5
huangjeff5 force-pushed the fix/py-middleware-config-one-shape branch from 3bf547f to 7620e33 Compare October 7, 2026 07:13
@huangjeff5
huangjeff5 changed the base branch from fix/py-model-config-any-model to fix/py-define-returns-ref October 7, 2026 07:13
@huangjeff5
huangjeff5 added this pull request to stack #6624 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+.
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.
…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
…g-one-shape

# Conflicts:
#	py/packages/genkit/src/genkit/_ai/_generate.py
@huangjeff5
huangjeff5 merged commit 43f012d into main Oct 8, 2026
26 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-middleware-config-one-shape branch October 8, 2026 05:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants