Skip to content

fix(py)!: typed model config raises before the turn, not as a failed response - #6675

Merged
huangjeff5 merged 9 commits into
mainfrom
fix/py-typed-config-check
Oct 12, 2026
Merged

huangjeff5 merged 9 commits into
mainfrom
fix/py-typed-config-check

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

A config= value the model's config schema can't take now raises INVALID_ARGUMENT before the turn starts, whichever way the model declared that schema. Before, only config_schema=SomeClass raised. A model typed ModelRequest[YourConfig] started the turn and handed back an empty finish_reason='failed' response, and a config_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.

class SketchConfig(BaseModel):
    quality: Literal['low', 'high']
    seed: int = 0

async def sketch(request: ModelRequest, ctx: ActionRunContext) -> ModelResponse: ...

# Same outcome with config_schema=SketchConfig or a ModelRequest[SketchConfig] annotation.
ai.define_model('acme/sketch', sketch, config_schema=SketchConfig.model_json_schema())

# 1. A value the schema rejects raises before the turn.
await ai.generate(model='acme/sketch', prompt='a lighthouse', config={'quality': 'ultra'})
# => GenkitError: INVALID_ARGUMENT: acme/sketch: config 'quality': 'ultra' is not one of ['low', 'high']
#    (before: no exception; the model function got 'ultra')

# 2. A required field nothing filled fails the turn.
response = await ai.generate(model='acme/sketch', prompt='a lighthouse', config={'seed': 7})
# => response.finish_reason == 'failed'
#    response.error.status == 'INVALID_ARGUMENT'
#    response.error.message == "acme/sketch: config 'quality': Field required"
#    (before: the model function ran without quality)

What checks a call, and where:

  • Before the turn: only the values the caller set. Checked against the config_schema= class (veneer, as before), the ModelRequest[...] annotation class (new), or the config_schema= JSON-schema dict (new). The annotation and dict checks run in run_generate, so every entry point gets them once: ai.generate, ai.generate_stream, prompts, generate_operation, and /util/generate (Dev UI, reflection).
  • Inside the model action: the whole config, missing required fields included, after every wrap_model middleware. New for config_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_operation has no response to put it in, so it raises, the same as any failed start.
  • No schema at all (plain ModelRequest, no config_schema=): nothing checks, as before.

Also drops ModelInfo.config_schema (the !). Models publish their config schema as customOptions from config_schema=; ModelInfo.configSchema was a second slot for the same thing that nothing read. schema_to_typing.py omits it, so ModelInfo(config_schema=...) now fails validation.

Decisions

  • One module for the checks: The config checks moved from _ai/_model.py into _core/_config_check.py. model() and the background model's start action both call check_request_config, so the two can't drift apart. They had already drifted once: background models were missing the in-action check. _core/_background.py can'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.text without checking finish_reason saw '' and no error. Three tests in generate_request_construction_test.py flip 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_model middleware 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, inside m.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.py runs 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_operation re-raised a failed start without its details, so for an annotated background model the missing field wasn't named anywhere. It now passes details through.

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

  • version isn't judged unless the schema names it: ModelRef.version rides in config, and Genkit puts it there, not the caller. Previously no check saw it on a config_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 with additionalProperties: false would otherwise reject a key it never asked for. Every shipped plugin class declares version already.

  • Prompt alias folding uses the annotation class too: Folding looked only at config_schema=, so on the annotation path maxOutputTokens in the prompt and max_output_tokens in the call stayed two keys and the prompt's value reached the model. config_class_for_generate falls back to the annotation class, so the call wins.

Known edges

  • Annotation-path message: on the annotation path, the in-action failure keeps the action's existing message (Invalid input for model 'acme/sketch') and names the field in error.details. The config_schema= paths name it in the message.
  • Dict schemas see wire keys: a dict from SomeConfig.model_json_schema() lists camelCase aliases, so with additionalProperties: false the call has to use maxTokens, not max_tokens. The class path folds aliases; a JSON schema has no aliases to fold, and the schema says the snake key isn't allowed.
  • A broken dict schema: define_model runs check_schema and raises INVALID_ARGUMENT. A $ref to nowhere only shows up at generate, as FAILED_PRECONDITION naming the model.

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

@huangjeff5
huangjeff5 added this pull request to stack #6676 October 8, 2026 08:32
@huangjeff5
huangjeff5 force-pushed the fix/py-typed-config-check branch from b838ac7 to fe4c39a Compare October 8, 2026 18:06
@github-actions github-actions Bot added the js label Oct 8, 2026
@huangjeff5
huangjeff5 deleted the branch main October 8, 2026 18:07
@huangjeff5 huangjeff5 closed this Oct 8, 2026
@huangjeff5 huangjeff5 reopened this Oct 8, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #6676 October 8, 2026 18:08
@huangjeff5
huangjeff5 changed the base branch from fix/py-model-config-form-custom-options to main October 8, 2026 18:08
@huangjeff5
huangjeff5 requested a review from apascal07 October 8, 2026 22:05
@huangjeff5

huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

Double check:
The behavior when ai.define_model(..., config_schema=SomeBaseModel) behavior matches ai.define_model(..., config_schema=json_schema_dict) when the ai.generate request fails config validation.

Checked: they don't match, here or on main. A dict schema is never checked, so {"temperature": "hot"} reaches the model fn. The class raises INVALID_ARGUMENT before the turn. Also, nothing in core rejects a missing required field for a define_model fn; only plugins that validate their own config do.

Fixed in 7e41899, same contract for both, matching Go:

  • before the turn: set values are checked, a bad one raises INVALID_ARGUMENT, missing fields are skipped (middleware can still fill them)
  • inside the model action: the whole config is checked, missing required fields included, and generate boxes the failure as the turn's error

@huangjeff5

huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor Author

TODO:
Decided to suppress config_schema from ModelInfo at _typing.py generation time. That was created for a Cross SDK purpose that was never adopted fully and caused a bunch of confusion.

Done in a1f38d7: ModelInfo gets omit: [configSchema] in schema_to_typing.py; the regenerated _typing.py drops one line. Nothing read the field; models publish their config as customOptions from config_schema=. ModelInfo forbids extra fields, so ModelInfo(config_schema=...) now fails validation, hence the ! on the title.

…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.
@huangjeff5 huangjeff5 changed the title fix(py): typed model config raises before the turn, not as a failed response fix(py)!: typed model config raises before the turn, not as a failed response Oct 12, 2026
…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.
@huangjeff5
huangjeff5 merged commit 14b2187 into main Oct 12, 2026
27 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-typed-config-check branch October 12, 2026 01:42
huangjeff5 added a commit that referenced this pull request Oct 12, 2026
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.
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