Repository navigation
feat(py/google-genai)!: flat Gemini config with exported Literals - #6698
Merged
Merged
Conversation
Gemini, Veo, Lyria, Anthropic ThinkingConfig and a2ui SurfacesConfig declared camelCase wire names with per-field alias= and, in the Gemini nested classes, a positional Field(None, ...) default. pyright ignores a positional default, so every field looked required, and with alias= no single spelling passes pyright, ty and pyrefly. Drop alias= where it equals to_camel(field) and take the wire name from alias_generator=to_camel, the pattern core GenerationCommonConfig uses. Defaults are keyword. SurfacesConfig.validation keeps the 'validate' wire name via validation_alias/serialization_alias because a field named validate would shadow BaseModel.validate. Wire JSON, model_json_schema and Dev UI customOptions are byte-identical before and after. Field names are unchanged, so SDK request bodies (dumped with by_alias=False) are unchanged.
populate_by_name lets pydantic accept a field's own name, but pyrefly doesn't read it: a class with an explicit alias (core OutputConfig's json_schema -> 'schema') rejects the field name as a constructor kwarg, which is why three call sites carried ignore[unexpected-keyword]. validate_by_name=True, validate_by_alias=True is the 2.11 spelling of the same runtime behavior, and pyrefly honors it. - Raise the pydantic floor to >=2.11 in every pyproject that pins it. - Swap populate_by_name for validate_by_name + validate_by_alias in all package sources, the agents sample, and the _typing.py generator (scripts/schema_to_typing.py); _typing.py is regenerated. - Drop the three pyrefly suppressions in _prompt.py and _generate.py. model_json_schema (validation and serialization) for all 208 pydantic models in the Genkit packages, config dumps, Dev UI customOptions and outgoing Gemini/Anthropic HTTP bodies are byte-identical before and after. uv.lock changes only the pydantic specifiers.
SurfacesConfig.validation now uses validation_alias='validate' and
serialization_alias='validate', and drops the AliasChoices. The JSON key
stays validate, to match js/plugins/a2ui/src/middleware.ts. The field
can't be named validate because that would shadow BaseModel.validate.
- model_json_schema and model_dump(by_alias=True) are byte-identical to
main.
- Runtime still accepts validation=, validate= and {'validate': ...}.
BREAKING (typing only): SurfacesConfig(validate=...) used to type-check
under pyright. Now pyright, pyrefly and ty all reject it; use
validation=. Before, no spelling passed all three checkers: pyright read
alias=, ty and pyrefly read the field name.
Surfaces(...) forwards **kwargs: Any from BaseMiddleware, so checkers
accept any kwarg there. Tests and the docstring now use validation=.
Building a typed nested config (thinking_config=ThinkingConfig(...), speech_config=SpeechConfig(...)) meant importing from the private _models._gemini module. Export every pydantic type reachable from an exported config class: the Gemini nested settings and their enums, plus Deep Research's McpServerConfig and FileSearchConfig. The latter is exported as DeepResearchFileSearchConfig because Gemini's FileSearchConfig owns the bare name. Typed-construction tests for Gemini and Anthropic now import only from the package root and assert the HTTP body the plugin sends. READMEs gain a short typed config example.
…hoice fields - Merge Deep Research FileSearchConfig into the Gemini class. Both send the same Interactions/Gemini file_search tool (store names, metadata filter, top_k). Drop the DeepResearchFileSearchConfig export. Deep Research behavior changes: - file_search_store_names is now optional. - extra keys are rejected (extra=forbid) instead of passed through. The create body for the store-names-only case is byte-identical. - Rename SafetySettingsSchema to SafetySetting. - Make FunctionCallingMode, HarmBlockThreshold, HarmCategory, ImageAspectRatio, ImageSize, ThinkingLevel Literal aliases instead of StrEnums. Add a HarmBlockMethod Literal for SafetySetting.method so callers don't import google.genai. Export all seven from the package root for annotating caller code; values stay plain strings. Value sets are unchanged; Dev UI schemas use get_args(). - Tests: Literal fields are asserted with assert_type for all three checkers, a helper typed with the exported aliases type-checks, and thinking_level='ULTRA' fails validation at runtime; Deep Research create body covers store-only and top_k/metadata_filter; Literal values are checked against the google-genai SDK enums.
Add the values google-genai 2.21 accepts that the config Literals were missing: - HarmCategory: CIVIC_INTEGRITY, JAILBREAK, IMAGE_HATE, IMAGE_DANGEROUS_CONTENT, IMAGE_HARASSMENT, IMAGE_SEXUALLY_EXPLICIT - HarmBlockThreshold: OFF - FunctionCallingMode: VALIDATED - ImageAspectRatio: 1:4, 1:8, 4:1, 8:1. The SDK types aspect_ratio as str, so this follows the Gemini image generation docs (Gemini 3.1 Flash Image) and matches the JS googleai plugin. The *_UNSPECIFIED handling is unchanged. HARM_BLOCK_THRESHOLD_UNSPECIFIED and THINKING_LEVEL_UNSPECIFIED stay out, since leaving the field unset already gets the server default. New tests pin each Literal to its SDK enum, so a google-genai bump that adds a value fails. ImageAspectRatio and ImageSize are pinned to the documented lists instead. The Dev UI schemas only gain the new enum values; HTTP bodies are unchanged.
Exported config inputs are Literals, not enums. ImageConfig.prominent_people was typed genai_types.ProminentPeople, so callers had to import google.genai to set it. It now uses an exported ProminentPeople Literal holding the SDK's values, including PROMINENT_PEOPLE_UNSPECIFIED, which the Dev UI schema already listed. The Dev UI schema reads the set with get_args, and the SDK-parity test pins it to genai_types.ProminentPeople. HTTP bodies and the Dev UI customOptions are unchanged. Standalone ImageConfig.model_json_schema() now inlines the enum where it used to $ref it.
Every exported Gemini/Veo config field that referenced a google.genai type now takes a Genkit model or Literal. The plugin converts to the SDK type when it builds the request, so the HTTP body is unchanged. New nested models, each declaring every field of the SDK type it is sent as (pinned by googlegenai_gemini_test.py): - ImageOutputOptions (ImageConfigImageOutputOptions) - ReplicatedVoiceConfig, VoiceConsentSignature - CodeExecution (ToolCodeExecution), UrlContext - GoogleSearch, SearchTypes, WebSearch, ImageSearch, Interval New Literals, pinned to the SDK enums: PhishBlockThreshold, VideoCompressionQuality, ImageResizeMode. code_execution, google_search and url_context keep the bool shorthand. The nested models set from_attributes=True, so a google.genai object passed at runtime still validates into its mirror.
This was referenced Oct 8, 2026
Contributor
There was a problem hiding this comment.
Code Review
This pull request refactors configuration typing across the Anthropic and Google GenAI Python packages. It replaces various enums with closed Literal type aliases to allow users to pass plain strings while maintaining static type checking, exports nested configuration models from the package roots, and adds comprehensive tests verifying that typed configurations correctly serialize into request bodies. A review comment suggests a safety improvement in _gemini.py to prevent a potential TypeError when filtering safety_settings if the list is None.
Add PluginConfig to genkit.plugin_api as the base model for plugin and middleware options. Inherits from BaseModel with extra='forbid', alias_generator=to_camel, validate_by_name=True, and validate_by_alias=True, without overriding model_dump(). - Adopt PluginConfig across plugin options: SurfacesConfig (genkit-a2ui), ThinkingConfig (genkit-anthropic), VeoConfig (genkit-google-genai), and strict nested Gemini configs (SafetySettingsSchema, PrebuiltVoiceConfig, FunctionCallingConfig, ThinkingConfig, FileSearchConfig, ImageConfig, VoiceConfig, SpeakerVoiceConfig, MultiSpeakerVoiceConfig, SpeechConfig). - Pin Surfaces(validate='strict') in genkit-a2ui config typing test. - Include packages/*/tests/config_typing_test.py in pyright CI workflow.
…ames ModelConfig inherited GenkitModel through the generated GenerationCommonConfig, so every plugin config's model_dump() returned camelCase. Provider SDKs take snake_case, so each plugin patched the dump its own way (by_alias=False, to_snake), and one that didn't silently dropped settings: OpenAI TTS/STT sent responseFormat and timestampGranularities, which _audio.py never read. - PluginConfig moves to _core/_base.py beside GenkitModel (re-exported from genkit.plugin_api) so _model.py can use it without an import cycle. - ModelConfig subclasses PluginConfig and declares the common fields. A test pins them to the generated GenerationCommonConfig. - Drop the workarounds: by_alias=False in Anthropic and the Gemini SDK dump, to_snake on Ollama's ModelConfig path. Generic boundaries that take any BaseModel keep the explicit flag. - The echo test model asks for the wire shape explicitly. JSON schema, Dev UI customOptions and configs nested in ModelRequest / GenerateActionOptions are byte-identical for all 13 ModelConfig subclasses. Only a direct config.model_dump() changes. BREAKING: ModelConfig(...).model_dump() returns field names and keeps None values, like any pydantic model. Pass by_alias=True, exclude_none=True for the old output. ModelConfig is no longer a GenerationCommonConfig.
…ass extras Undeclared extras on a ModelConfig subclass with extra='allow' keep the caller's spelling (keepAlive), so build_request_kwargs still snake-cases them. The dumped-dict test asks for the wire shape explicitly now that the default dump returns field names.
…checkers pyproject.toml now owns the scope: pyright include, pyrefly project_includes, and a ty override that re-enables invalid-argument-type and no-matching-overload under **/tests/typecheck/** (the tests/** override muted the two rules a contract exists to catch). CI runs plain pyright. Before, only pyright gated these files, through a CLI glob; pyrefly never opened them. A canary with a wrong type and a camelCase kwarg now fails all three. pyright checks the same 192 files as the old explicit command.
The alias existed only to mirror JS's option name. SurfacesConfig is in-process middleware config, not a cross-SDK wire format, and the split validation_alias/serialization_alias was the last special case on a PluginConfig. The field is now plain validation everywhere: kwarg, wire key and Dev UI schema.
BREAKING: validate= and {'validate': ...} now raise; use validation.
The base covers model, middleware and nested settings, not just plugins: ModelConfig(PluginConfig) read as "a model config is a plugin config". GenkitConfig names the role, settings handed to Genkit whose JSON is Genkit's shared camelCase shape, and pairs with the internal GenkitModel wire base. BaseConfig was out because pydantic still exports a deprecated pydantic.BaseConfig. - Exported from genkit.plugin_api and genkit.middleware. - Docstring records why the JSON is camelCase: the Dev UI builds its form from the schema and pre-fills it from traces and .prompt files by exact key. - Test: two spellings of one key in one input raise (extra='forbid').
…ubclasses it again schema_to_typing emits GenerationCommonConfig on GenkitConfig with no model_config of its own, so it inherits extra='forbid' and the stock dump. ModelConfig drops its copied common fields and only adds extra. Top-level plugin configs stop re-declaring flags they inherit; their JSON schemas are unchanged.
The swap to validate_by_name is runtime-identical and only matters for pyrefly on classes with explicit aliases. Internal models (errors, action responses, embedder/evaluator refs, Firestore docs, ClientOptions, cache metadata) aren't config or wire types, so they stay as on main.
…re GenkitConfig Unknown keys now raise instead of passing through to the create body.
Enum fields become Literals with the SDK values; SDK model fields become GenkitConfig mirrors (ImageOutputOptions, ReplicatedVoiceConfig, GoogleSearchConfig, ...). A drift test pins each Literal to its SDK enum and _NESTED_SDK_MIRRORS fails CI when the SDK adds a field.
Contributor
Author
|
TODO: Minimize exports and flatten GeminiConfig |
cabljac
approved these changes
Oct 12, 2026
…config-surface # Conflicts: # py/packages/genkit-google-genai/tests/models/model_refs_test.py
… a2ui validate, and OpenAI image tests
…and None safety method
apascal07
approved these changes
Oct 12, 2026
…kwargs # Conflicts: # py/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py # py/packages/genkit-google-genai/src/genkit_google_genai/_models/_lyria.py # py/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py
…config-surface # Conflicts: # py/packages/genkit-google-genai/src/genkit_google_genai/__init__.py # py/packages/genkit-google-genai/src/genkit_google_genai/_google.py # py/packages/genkit-google-genai/src/genkit_google_genai/_models/_model_refs.py # py/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py # py/packages/genkit-google-genai/tests/models/googlegenai_gemini_test.py # py/packages/genkit-google-genai/tests/models/model_refs_test.py # py/packages/genkit-google-genai/tests/typecheck/config_test.py
- README and GeminiTtsConfig/GeminiImageConfig examples use gemini_tts()/gemini_image() - README headline example drops tool_choice='required', which loops until the tool-call cap - ImageSize accepts '512', as JS does - google_search_end_time rounds up, so the window never shrinks or collapses - speech_config/image_config on a plain GeminiConfig point at the subclass that has the fields - Deep Research shares flattened_key_error and file_search_fields with Gemini - backend checks and tool building share present_items for empty Dev UI lists
- instantiate turns any config ValidationError into INVALID_ARGUMENT naming the middleware - accepted keys list the serialization alias (validate, not validation) - key spellings reuse config_field_names, the walk model config folding uses - prompt use metadata dumps inline config with _dump_middleware_ref_config - FilesystemConfig wire key is rootDirectory, as in JS and Go - metadata.cache ttlSeconds: bad values are INVALID_ARGUMENT; a null camel key no longer hides ttl_seconds - drop always-empty passthrough splat in Antigravity, Deep Research and Lyria
Resolves import conflicts across genkit-google-genai (_antigravity, _deep_research, _interactions_lyria, _veo) using ModelContext and GenkitConfig.
…config-surface Resolves import conflicts in __init__.py and _gemini.py; aligns ModelContext usage in tests.
huangjeff5
added a commit
that referenced
this pull request
Oct 30, 2026
candidate_count left GeminiConfig in #6698, but extra={'generationConfig': {'candidateCount': N}} still reached the API, which billed N candidates while the plugin read only candidate 0. It now raises INVALID_ARGUMENT before the call, as Go does for any count but 1.
huangjeff5
added a commit
that referenced
this pull request
Oct 30, 2026
The stack under this PR (#6697, #6698, #6699) landed on main as squash commits, so this merge takes main and reapplies only this PR's changes (e4e07ed..260e048) on top. Adapts to #6757/#6766/#6777: Veo uses _create_veo_background_model and ModelContext, _runtime_client is a @loop_local_client method built from per-loop client kwargs, and GENKIT_CLIENT_HEADER is now GENKIT_USER_AGENT.
huangjeff5
added a commit
that referenced
this pull request
Oct 30, 2026
…onfig-strict Main landed #6697 (GenkitConfig, extra='forbid'), #6698 (flat Deep Research config, McpServerConfig TypedDict), #6757/#6766/#6777 (Model/BackgroundModel classes, ModelContext). Conflicts were only in this PR's files. Resolution: take main's version of _antigravity.py, _deep_research.py and _interactions_lyria.py, then re-apply this PR's net change on top: the `extra` field (EXTRA_DESCRIPTION), the class docstrings, and deep_merge(create_kwargs, extra) at create_interaction. The model() / background_model() builder and persist() removal from the PR are superseded by main's Model/BackgroundModel. Tests: keep main's test_lyria_rejects_unknown_config_fields; drop the PR's nested-key typo test (main's McpServerConfig deliberately passes unknown keys through, and nested file_search is now rejected by main's reject_nested_file_search with its own tests) and the PR's top-level `extra={'temperature': ...}` Lyria test (covered by the generation_config one).
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.
Stack: 2/3 · previous #6697 · next #6699
GeminiConfigand its TTS and image variants are flat, and plugin model ref constructors drop the_modelsuffix (GoogleAI.gemini(...),VertexAI.gemini(...),Anthropic.claude(...),OpenAI.gpt(...)). The Google GenAI plugin builds Gemini's nestedthinkingConfig,speechConfig,imageConfigandtoolswhen it sends the request, so HTTP bodies are byte-identical to the nested config for equivalent settings. This follows the same rule #6699 applies to Anthropic: provider configs are designed Genkit surfaces, not mirrors of the SDK.Previously, a typed nested config meant importing
ThinkingConfig,SpeechConfigand friends from the private_models._geminimodule, and a TTS voice was four constructors deep.Decisions
TypedDict. Thinking, image, speech, File Search and Google Search options map 1:1 onto fields named<group>_<sdk_field>, with the prefix dropped when the name is already unambiguous (thinking_level,voice,aspect_ratio).safety_settingsand Deep Researchmcp_serversare lists, so their entries areSafetySettingandMcpServerConfigTypedDicts: a dict literal type-checks with no import, the constructor call still works, and the Dev UI safety widget still renders. A test pins every flattened group to itsgoogle-genaifield set, so an SDK bump that adds a field fails until it gets a flat name or is left out on purpose.ModelRef, prompt, call) on its own, then the merged one. Pairs that cannot both be set (thinking_level+thinking_budget,voice+speakers,google_search=False+google_search_*) are config validators, so a single call fails on the constructor line and a default plus a call fails ingenerate(). Settings that need a companion (search start and end time, File Search options without store names) and Vertex-only settings on the Gemini API are checked when the request is built, because one layer may set half.google-genaialready rejects the Vertex-only ones on the Gemini API; the plugin raises first so the error names the flat field.Literals, exported for annotations; model names are not.ThinkingLevel,HarmCategory,HarmBlockThreshold,HarmBlockMethod,ImageAspectRatio,ImageSize,PersonGeneration,ProminentPeople,PhishBlockThreshold,SearchType,ResponseModality, and Veo'sImageResizeModeandVideoCompressionQualityare exported fromgenkit_google_genai. Callers pass plain strings. The root exports 25 names, against 10 onmain, and none of them is a nested config class;main's nested classes were reachable only through a private module..promptfiles. Go and JS have no shared Gemini config format: Go usesgenai.GenerateContentConfigas-is and JS has its own nested schema, and tool configs already differ between them. A nested key raises with the flat replacement instead of being reinterpreted, and.promptfiles use the flatcamelCasenames (thinkingLevel: MEDIUM).generate(tool_choice=), not config.tool_choice'auto'/'required'/'none'maps tofunctionCallingConfig'AUTO'/'ANY'/'NONE'when the request has function tools, and'required'also names those tools asallowedFunctionNames, as the Go plugin does. A config field for the mode would compete withtool_choice; to limit which functions are callable, pass fewertools._modelsuffix across plugins:GoogleAI.gemini/gemini_tts/gemini_image/gemma/veo/lyria/deep_research/antigravity,VertexAI.gemini/gemini_tts/gemini_image/gemma/veo,Anthropic.claude, andOpenAI.gpt(chat models only; OpenAI has no other model ref constructors). The plugin class already scopes the call, and embedder refs already useembedding().extra. A cloned (replicated) TTS voice carries audio bytes and consent, so it does not fitvoice: str; it goes inextra={'generationConfig': {'speechConfig': {...}}}. The plugin readsextra: it skips the defaultKorevoice whenextranames one, and raises whenvoiceorspeakersis also set, since the deep merge would send both.Breaking changes
thinking_config,speech_config,image_config,file_search,function_calling_config,candidate_count, and the dict form ofgoogle_search/code_execution/url_context. Flattened keys raiseINVALID_ARGUMENTnaming their replacement;function_calling_configpoints atgenerate(tool_choice=)._modelsuffix from plugin model ref constructors (GoogleAI.gemini_model->GoogleAI.gemini,Anthropic.claude_model->Anthropic.claude,OpenAI.gpt_model->OpenAI.gpt, etc.).VALIDATEDfunction calling mode,allowed_function_names,stream_function_call_arguments(Python has no partial tool-call stitching yet),candidate_count, andimage_output_options(the same two settings asoutput_mime_type/output_compression_quality).google_search=Falsewithgoogle_search_*options raises; to turn off a default's search, passNonefor each option too.response_modalitiestakesTEXT/IMAGE/AUDIO; other casings are upper-cased.SafetySettingis aTypedDict: entries are dicts (s['category']), and agoogle.genaiSafetySettingobject no longer validates.file_searchis nowfile_search_store_names/file_search_metadata_filter/file_search_top_k.speakersis a map, which the Dev UI form does not render;speechConfigwas not rendered either.Also fixed
generate(tool_choice=), sotool_choice='none'still let the model call tools.datetime.now()used to fail as sent.Known follow-ups
applyGeminiPartialArgsand set the flag for Vertex streaming once something consumes partial tool requests.snake_case(e.g.thinkingConfig.thinking_budget) becausegoogle-genaidumps nested dicts withoutby_alias; Proto JSON accepts it.Verification
8f3142412vs flat config here: thinking level, budget + include thoughts, safety with and withoutmethod, Google Search plain / options / time range / search types on both backends, File Search, code execution, URL context, TTS voice + language and two speakers, image aspect ratio + size, image output options on Vertex, Deep Research File Search + MCP. All 19 bodies and URLs are identical.datetime.now(), URL context, code execution, TTS voice and two speakers, image aspect ratio all succeed.google_search_exclude_domainson the Gemini API fails in Genkit before sending. Sent raw,thinking_level+thinking_budgetgets400 You can only set only one of thinking budget and thinking level, which Genkit now raises first.packages/genkit-google-genai/tests/typecheck/config_test.py: 0 errors, including dict-literal andSafetySetting(...)entries.ruff check --preview: clean. pytest onpackages/genkit-google-genai: 1037 passed.