Repository navigation
fix(py)!: typed model config raises before the turn, not as a failed response - #6675
Conversation
There was a problem hiding this comment.
Code Review
This pull request implements upfront validation for model configurations when a model function is typed with ModelRequest[Cfg]. Instead of returning a failed response during execution, invalid configurations now raise an INVALID_ARGUMENT error before the model runs. This is accompanied by updated and new tests verifying the validation behavior. There are no review comments, so I have no additional feedback to provide.
b838ac7 to
fe4c39a
Compare
|
Double check: Checked: they don't match, here or on main. A dict schema is never checked, so Fixed in 7e41899, same contract for both, matching Go:
|
|
TODO: Done in a1f38d7: |
…heck # Conflicts: # py/packages/genkit/src/genkit/_ai/_prompt.py
…s to the model action Addresses review on #6675: - The annotation check moves from resolve_for_generate to run_generate, so /util/generate gets it too. check_config= is gone, and generate_operation no longer checks twice. - A missing top-level field passes the pre-turn check on both paths: wrap_model middleware can still fill it. The model action reports it if nothing does, so one class gives one outcome however it was registered. - Prompt alias folding falls back to the annotation class (config_class_for_generate), so the call's max_output_tokens wins. - The MiddlewareConfigCheck site uses annotated_config_class.
check_config_dict -> check_config_values, layer -> values, and the docstring states the rule: only fields the config sets are judged; a required field it leaves out is left to middleware and the model action. The missing-field filter gets a comment saying what Pydantic reports and why those errors are dropped. No behavior change.
Models publish their config schema as customOptions from config_schema=. ModelInfo.configSchema was a second, unread slot for the same thing.
…ON-schema dict Before the turn, the values a call sets are checked against a JSON-schema dict too, not only a class. Inside the model action, the whole config is checked after middleware, so a required field nothing filled fails the turn. Go validates config at the same point.
The config checks move to _core/_config_check.py. model() and a background model's start action both call check_request_config, so a required field nothing filled never reaches start(), and the two paths share one implementation.
Every case runs over both model kinds and the four ways to declare config, so the two kinds can't drift without a failing test. The table caught generate_operation re-raising a failed start without its details; it now passes them through.
Missing required fields wait for middleware, as #6675 does on main: the call-time check judges only the keys the caller set, and the action boundary judges the merged config. generate reports a boundary failure as the turn's error; every other entry point raises. - _config_check is the only validator. It keeps this PR's rules (a key that's present is judged, explicit None included; spellings fold) and main's coverage (JSON-schema dicts, undeclared ModelRef.version ignored). - Action.run checks every kind with a config schema, class or dict, typed fn or not, in the same words. Action.__init__ checks a JSON-schema dict. - Drop check_merged_config, check_config_dict, validate_config_dict, and the background start wrapper's separate check.
A
config=value the model's config schema can't take now raisesINVALID_ARGUMENTbefore the turn starts, whichever way the model declared that schema. Before, onlyconfig_schema=SomeClassraised. A model typedModelRequest[YourConfig]started the turn and handed back an emptyfinish_reason='failed'response, and aconfig_schema=JSON-schema dict was never checked at all:{'temperature': 'hot'}reached the model function.The contract from #6255: anything that fails before the turn starts raises; once the turn starts, you get a
ModelResponse. The turn starts when generate enters its hooks (wrap_generate,wrap_model), the same line Go draws: before it, Go returns only an error; after it, a partial response with the error.What checks a call, and where:
config_schema=class (veneer, as before), theModelRequest[...]annotation class (new), or theconfig_schema=JSON-schema dict (new). The annotation and dict checks run inrun_generate, so every entry point gets them once:ai.generate,ai.generate_stream, prompts,generate_operation, and/util/generate(Dev UI, reflection).wrap_modelmiddleware. New forconfig_schema=models and for a background model's start action; annotated models already got this from the action's input validation. generate returns the failure as the turn's error.generate_operationhas no response to put it in, so it raises, the same as any failed start.ModelRequest, noconfig_schema=): nothing checks, as before.Also drops
ModelInfo.config_schema(the!). Models publish their config schema ascustomOptionsfromconfig_schema=;ModelInfo.configSchemawas a second slot for the same thing that nothing read.schema_to_typing.pyomits it, soModelInfo(config_schema=...)now fails validation.Decisions
One module for the checks: The config checks moved from
_ai/_model.pyinto_core/_config_check.py.model()and the background model's start action both callcheck_request_config, so the two can't drift apart. They had already drifted once: background models were missing the in-action check._core/_background.pycan't import from_ai, which is why the checks live in_core.Raise, don't return a failed turn, for a bad value: The turn never started. The model can't take this config, and no history exists to resend beyond what the caller just passed. A caller reading
response.textwithout checkingfinish_reasonsaw''and no error. Three tests ingenerate_request_construction_test.pyflip from failed-response to raise; they pinned the old boxing, which contradicts fix(py): generate returns completed history instead of raising when a turn dies #6255.A JSON-schema dict is checked like a class: Previously the dict only fed the Dev UI form. We chose to validate with
jsonschema(already a genkit dependency) under the same rules as the class, because one model should behave the same however its author wrote the schema, and Go validates against JSON schema for every model.A missing required field is the model action's call:
wrap_modelmiddleware runs after the pre-turn check and can still fill a field, so the pre-turn check skips missing top-level fields. Previously nothing in core caught one that stayed missing; only plugins that validate their own config did. The model action now checks the whole config, the same point Go validates (core/action.go, insidem.Run, after middleware).test_generate_missing_required_top_level_field_*flips from "still runs" to a failed turn.One test table for both model kinds:
typed_config_required_test.pyruns each case (complete, bad value, missing field, middleware fills it) over regular and background models times the four ways to declare config. A new case covers all eight combinations, so the two kinds can't drift without a failing test. The table found one real gap:generate_operationre-raised a failed start without itsdetails, so for an annotated background model the missing field wasn't named anywhere. It now passesdetailsthrough.Foreign config objects still convert on the annotation path:
test_foreign_config_class_normalizes_to_conforming(feat(py): accept ModelRef on generate, prompt, agent, and Genkit constructor #6074) stays green. Only values the annotation's class rejects raise.versionisn't judged unless the schema names it:ModelRef.versionrides in config, and Genkit puts it there, not the caller. Previously no check saw it on aconfig_schema=model's merged config. We chose to skip it for a schema that doesn't declare it, because a strict user class (extra='forbid') or a dict withadditionalProperties: falsewould otherwise reject a key it never asked for. Every shipped plugin class declaresversionalready.Prompt alias folding uses the annotation class too: Folding looked only at
config_schema=, so on the annotation pathmaxOutputTokensin the prompt andmax_output_tokensin the call stayed two keys and the prompt's value reached the model.config_class_for_generatefalls back to the annotation class, so the call wins.Known edges
Invalid input for model 'acme/sketch') and names the field inerror.details. Theconfig_schema=paths name it in the message.SomeConfig.model_json_schema()lists camelCase aliases, so withadditionalProperties: falsethe call has to usemaxTokens, notmax_tokens. The class path folds aliases; a JSON schema has no aliases to fold, and the schema says the snake key isn't allowed.define_modelrunscheck_schemaand raisesINVALID_ARGUMENT. A$refto nowhere only shows up at generate, asFAILED_PRECONDITIONnaming the model.