Repository navigation
fix(py)!: plugin config classes type-check with snake_case kwargs - #6694
huangjeff5 wants to merge 10 commits into
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.
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.
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.
…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.
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=.
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.
…oice
Anthropic:
- Remove AnthropicConfig.tool_choice and the ToolChoice, AutoToolChoice,
AnyToolChoice, SpecificToolChoice and ToolChoiceNone exports. This also
removes the clash with genkit.ToolChoice.
- Map request.tool_choice: 'auto' -> {'type': 'auto'}, 'required' ->
{'type': 'any'}, 'none' -> {'type': 'none'}, None -> omitted. 'none'
was silently dropped before, so Claude could still call the tools.
- Add a flat disable_parallel_tool_use flag. Anthropic carries it only
inside tool_choice, so with no tool_choice it sends {'type': 'auto', ...}.
It is never sent with 'none'.
- extra={'tool_choice': {...}} now overrides the translated value; it is
how a caller pins one named tool.
- A config with tool_choice raises INVALID_ARGUMENT that names
ai.generate(tool_choice=...).
Gemini ignored request.tool_choice while advertising support for it.
Map it to toolConfig.functionCallingConfig.mode (AUTO, ANY, NONE). An
explicit function_calling_config wins, as in the JS plugin.
AnthropicConfig no longer nests Anthropic's request objects. The plugin
builds them from flat fields:
- thinking (ThinkingMode: 'enabled' | 'adaptive' | 'disabled'),
thinking_budget and thinking_display (ThinkingDisplay) -> thinking
- effort (Effort: 'low' ... 'max') and task_budget -> output_config,
sent as {'effort': ..., 'task_budget': {'type': 'tokens', 'total': N}}
and merged with the structured-output format
- user_id -> metadata.user_id
Remove ThinkingConfig, OutputConfig, TaskBudget and RequestMetadata, and
the legacy enabled/adaptive bools. Export Effort, ThinkingMode and
ThinkingDisplay.
Rules: a thinking_budget alone means enabled; 'enabled' requires one;
'disabled' now rejects one (it was silently dropped); 'adaptive' accepts
and ignores it, as before. thinking_display with no mode now raises (it
was silently dropped).
The old nested keys (thinking={...}, output_config, metadata) raise
INVALID_ARGUMENT naming the flat replacement. extra={'thinking': ...}
and extra={'metadata': ...} still replace the built object;
output_config stays managed because it carries the structured-output
format.
Request bodies and anthropic-beta headers are byte-identical to main for
equivalent configs. task_budget still selects the beta API.
There was a problem hiding this comment.
Code Review
This pull request updates the codebase to Pydantic v2.11, replacing populate_by_name=True with validate_by_name=True and validate_by_alias=True across multiple packages. It also flattens the configuration schemas for AnthropicConfig and refactors Google GenAI configurations to use Literal types instead of Enums for better type-checking support. Feedback on the changes highlights potential KeyError bugs in both the Anthropic and Gemini plugins when tool_choice is configured with a specific tool name instead of a standard mode, suggesting safer fallback handling to map specific tool names correctly.
| def _to_anthropic_tool_choice(tool_choice: str | None, disable_parallel_tool_use: bool) -> dict[str, Any] | None: | ||
| """Translate Genkit's tool_choice into Anthropic's object; None sends nothing. | ||
|
|
||
| Anthropic carries disable_parallel_tool_use only inside tool_choice, so | ||
| the flag alone sends {'type': 'auto', ...}, the API's default with tools. | ||
| The 'none' variant has no such field. | ||
| """ | ||
| if tool_choice is None: | ||
| return {'type': 'auto', 'disable_parallel_tool_use': True} if disable_parallel_tool_use else None | ||
| choice: dict[str, Any] = {'type': _TOOL_CHOICE_TYPES[tool_choice]} | ||
| if disable_parallel_tool_use and tool_choice != 'none': | ||
| choice['disable_parallel_tool_use'] = True | ||
| return choice |
There was a problem hiding this comment.
The _to_anthropic_tool_choice function assumes that tool_choice is always one of the predefined modes in _TOOL_CHOICE_TYPES ('auto', 'required', 'none'). However, in Genkit, tool_choice can also be a specific tool name (e.g., 'lookup_menu') to force the model to use that specific tool.
If a user specifies a specific tool name, _TOOL_CHOICE_TYPES[tool_choice] will raise a KeyError at runtime.
To fix this, we should check if tool_choice is in _TOOL_CHOICE_TYPES, and if not, treat it as a specific tool name by mapping it to {'type': 'tool', 'name': tool_choice}.
| def _to_anthropic_tool_choice(tool_choice: str | None, disable_parallel_tool_use: bool) -> dict[str, Any] | None: | |
| """Translate Genkit's tool_choice into Anthropic's object; None sends nothing. | |
| Anthropic carries disable_parallel_tool_use only inside tool_choice, so | |
| the flag alone sends {'type': 'auto', ...}, the API's default with tools. | |
| The 'none' variant has no such field. | |
| """ | |
| if tool_choice is None: | |
| return {'type': 'auto', 'disable_parallel_tool_use': True} if disable_parallel_tool_use else None | |
| choice: dict[str, Any] = {'type': _TOOL_CHOICE_TYPES[tool_choice]} | |
| if disable_parallel_tool_use and tool_choice != 'none': | |
| choice['disable_parallel_tool_use'] = True | |
| return choice | |
| def _to_anthropic_tool_choice(tool_choice: str | None, disable_parallel_tool_use: bool) -> dict[str, Any] | None: | |
| """Translate Genkit's tool_choice into Anthropic's object; None sends nothing. | |
| Anthropic carries disable_parallel_tool_use only inside tool_choice, so | |
| the flag alone sends {'type': 'auto', ...}, the API's default with tools. | |
| The 'none' variant has no such field. | |
| """ | |
| if tool_choice is None: | |
| return {'type': 'auto', 'disable_parallel_tool_use': True} if disable_parallel_tool_use else None | |
| if tool_choice in _TOOL_CHOICE_TYPES: | |
| choice: dict[str, Any] = {'type': _TOOL_CHOICE_TYPES[tool_choice]} | |
| else: | |
| choice = {'type': 'tool', 'name': tool_choice} | |
| if disable_parallel_tool_use and tool_choice != 'none': | |
| choice['disable_parallel_tool_use'] = True | |
| return choice |
| if request.tool_choice and request.tools and cfg.tool_config is None: | ||
| cfg.tool_config = genai_types.ToolConfig( | ||
| function_calling_config=genai_types.FunctionCallingConfig( | ||
| mode=_FUNCTION_CALLING_MODES[request.tool_choice] | ||
| ) | ||
| ) |
There was a problem hiding this comment.
The tool choice mapping assumes that request.tool_choice is always one of the predefined modes in _FUNCTION_CALLING_MODES ('auto', 'required', 'none'). However, in Genkit, tool_choice can also be a specific tool name (e.g., 'lookup_menu') to force the model to use that specific tool.
If a user specifies a specific tool name, _FUNCTION_CALLING_MODES[request.tool_choice] will raise a KeyError at runtime.
To fix this, we should check if request.tool_choice is in _FUNCTION_CALLING_MODES, and if not, treat it as a specific tool name by setting the mode to ANY and providing the tool name in allowed_function_names.
if request.tool_choice and request.tools and cfg.tool_config is None:
if request.tool_choice in _FUNCTION_CALLING_MODES:
cfg.tool_config = genai_types.ToolConfig(
function_calling_config=genai_types.FunctionCallingConfig(
mode=_FUNCTION_CALLING_MODES[request.tool_choice]
)
)
else:
cfg.tool_config = genai_types.ToolConfig(
function_calling_config=genai_types.FunctionCallingConfig(
mode=genai_types.FunctionCallingConfigMode.ANY,
allowed_function_names=[request.tool_choice],
)
)
Plugin config classes now type-check with snake_case keyword arguments and typed nested values under pyright, pyrefly and ty. Config fields take Genkit types and exported Literals, never google-genai or Anthropic SDK types. For equivalent configs, request bodies are byte-identical to main.
Previously, every checker rejected some valid call. Pydantic fields declared
alias='thinkingBudget'. pyright readsalias=and accepted only the camelCase kwarg. ty and pyrefly read the field name and accepted only snake_case. So no spelling passed all three, and nested Gemini types weren't importable from the package root.Decisions
alias=: I removed 66alias=declarations that equaledto_camel(field): Gemini, Veo, Vertex Lyria, Anthropic, and a2uisurface_id. The classes take camelCase fromalias_generator=to_camelinstead. All three checkers then see the field name as the kwarg, and runtime still accepts both spellings.validate_by_name: pyrefly ignorespopulate_by_name, so it kept rejecting snake_case kwargs on aliased classes. pydantic 2.11 addedvalidate_by_name=True, validate_by_alias=True, which pyrefly does honor. I switched every class over and updated the_typing.pygenerator. Three pyrefly suppressions in core are gone. There's noserialize_by_alias, and explicitby_alias=Truedumps stay as they were.AnthropicConfigdropsThinkingConfig,OutputConfig,TaskBudgetandRequestMetadatafor flatthinking,thinking_budget,thinking_display,effort,task_budgetanduser_id, with exportedThinkingMode,ThinkingDisplayandEffortLiterals. The plugin buildsthinking,output_config(merged with the structured-output format) andmetadata. A budget alone means enabled,'enabled'requires one,'adaptive'ignores one as before, and'disabled'now rejects one instead of dropping it.extra={'thinking': {...}}orextra={'metadata': {...}}still replaces the built object.output_configstays managed because it carries the structured-output format.google.genaitypes now take Genkit models:ImageOutputOptions,ReplicatedVoiceConfig,VoiceConsentSignature,CodeExecution,UrlContext,GoogleSearch,SearchTypes,WebSearch,ImageSearchandInterval, plus thePhishBlockThreshold,VideoCompressionQualityandImageResizeModeLiterals. A test pins each mirror's field set to the SDK type it's sent as. The nested models setfrom_attributes=True, so agoogle.genaiobject passed at runtime still validates.Literalaliases, not StrEnums or SDK enums, so callers pass plain strings,thinking_level='HIGH', without importing anything. We export a Literal only when its values are API setting values that stay stable, never model lists likeKnownClaude.*_UNSPECIFIEDstays only where Genkit already offered it. A test pins each set to its google-genai enum, so an SDK bump that adds a value fails loudly. This PR addsOFF,VALIDATED, the six newer harm categories and four aspect ratios.tool_choiceoption; the plugin translates it to Anthropic's shape.AnthropicConfig.tool_choicemirrored Anthropic's object and clashed withgenkit.ToolChoice. Now'auto'→{'type': 'auto'},'required'→{'type': 'any'},'none'→{'type': 'none'}, and the flatdisable_parallel_tool_userides inside that object. This fixes a bug: Anthropic silently droppedtool_choice='none', and Gemini ignoredtool_choiceentirely while advertising support, so both models could still call tools. Gemini now maps it tofunctionCallingConfig.mode, and an explicittool_configwins.extra={'tool_choice': {...}}overrides the translated value; that's how a caller pins one named tool.FileSearchConfig, andSafetySettinginstead ofSafetySettingsSchema: Deep Research had its own FileSearchConfig for the same Interactionsfile_searchtool, so two classes competed for one exported name. The merged class takes optionalfile_search_store_names,metadata_filterandtop_k, and rejects unknown keys. That's a Deep Research behavior change: store names become optional, and a typo liketop_kknow raises instead of reaching the API.SafetySettingmatchesgenai_types.SafetySetting.SurfacesConfigusesvalidation=: a field namedvalidatewould shadowBaseModel.validate. With the field namedvalidationandalias='validate', pyright accepted onlyvalidate=and the other two accepted onlyvalidation=. The field now usesvalidation_alias='validate', serialization_alias='validate'. The JSON key staysvalidateto match JS, and the schema and dumps are byte-identical to main. Runtime still accepts both spellings.Breaking changes
genkit_anthropic: removedThinkingConfig,OutputConfig,TaskBudgetandRequestMetadata.thinking={...},output_config=andmetadata=raiseINVALID_ARGUMENTnaming the flat field. The legacyenabled/adaptivebools are gone;thinking=is the one spelling.genkit_anthropic: removedToolChoice,AutoToolChoice,AnyToolChoice,SpecificToolChoiceandToolChoiceNone, and theAnthropicConfig.tool_choicefield. A config withtool_choiceraisesINVALID_ARGUMENTnamingai.generate(tool_choice=...).genkit_anthropic:thinking='disabled'with a budget, andthinking_displaywith no mode, now raise. Both were silently dropped.genkit_google_genai:SafetySettingsSchema→SafetySetting. Deep ResearchFileSearchConfigmerged with the Gemini one.genkit_a2ui:SurfacesConfig(validate=...)no longer type-checks under any checker; usevalidation=.Dev UI schema
thinking,output_configandmetadataobjects are replaced bythinking(enum),thinkingBudget,thinkingDisplay,effort,taskBudgetanduserId.toolChoiceis replaced bydisableParallelToolUse.CI gap
The new
config_typing_test.pyfiles are the type-checker contract: no suppressions,assert_typeon the exported Literals, and the HTTP body is asserted. Today only ty gates them: CI pyright runs onpackages/*/srconly, and CI pyreflyproject_includescovers core src only. The follow-up is to addpackages/*/tests/config_typing_test.pyto both. pyright, pyrefly and ty report 0 errors on these files today.Known follow-ups
Surfaces(**kwargs)is untyped becauseBaseMiddleware.__init__takes**kwargs: Any, so checkers accept any kwarg there, includingvalidate=.thinkingConfig.thinking_budget) because google-genai dumps nested objects withoutby_alias; Proto JSON accepts it.anyOffields, sonote: str | Nonedisappears from tool and response schemas.tool_choiceobject and nestedthinking/output_config, and JSeffortlacks'max'.Overlap
This PR touches one line in
py/packages/genkit/src/genkit/_ai/_evaluator.py, which #6671 also touches:EvaluatorRef.model_config,populate_by_name=True→validate_by_name=True, validate_by_alias=True. If #6671 lands first, keep its version and redo that swap.Verification
packages/*/src, ty,generate_schema_typing --cianduv lock --check: all clean. pyright, pyrefly and ty onpackages/*/tests/config_typing_test.py: 0 errors.anthropic-betaheaders match too;task_budgetstill selects the beta API with the default betas.