Repository navigation
refactor(py/anthropic)!: flat AnthropicConfig; tool choice from generate(tool_choice=) - #6699
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 tool choice handling in the Anthropic and Google GenAI (Gemini) plugins, moving tool_choice from a model configuration field to a standard Genkit generation option (ai.generate(tool_choice=...)). It introduces disable_parallel_tool_use as a flat configuration flag for Anthropic, and maps Genkit's standard tool_choice values (auto, required, none) to the respective API-specific structures for both Anthropic and Gemini. The review feedback correctly identifies that the translation logic in both plugins assumes tool_choice is always one of the standard string values, which will cause runtime errors if a dictionary or a specific tool name is passed as allowed by Genkit.
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.
… a2ui validate, and OpenAI image tests
…and None safety method
… with required tool_choice, and toolless extra tool_choice
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
…; config allowlist - the thinking/tool_choice guard covers 'adaptive' and raises GenkitError INVALID_ARGUMENT - _build_params passes only AnthropicConfig.CREATE_KWARGS to create(); a test pins every field's class - document that a toolless extra tool_choice is dropped - refresh test comments that compared against the old plugin
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.
…d display Config merges key by key across the ModelRef default, prompt and call, so a call that set thinking='disabled' over a default with thinking_budget raised. The mode now decides which thinking fields apply, matching 'adaptive'. Each flattened group documents how it behaves under layered merging.
…nfig Model validators also ran on each config layer alone, so thinking='enabled' in a call failed even when the ModelRef default or prompt supplied the budget. The rules now live in AnthropicConfig.check_merged(), which generate calls on the merged config after middleware edits. The class docstring states the three layering rules: judge cross-field rules on the merged config; a switch wins over settings it doesn't use; two peer settings that conflict fail and name the None that clears one.
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.
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: 3/3 · previous #6698
AnthropicConfigis flat and tool choice comes from Genkit'sai.generate(tool_choice=...). Choices are exportedLiterals (ThinkingMode,ThinkingDisplay,Effort), and the plugin builds Anthropic's nestedthinking,output_config,metadataandtool_choiceobjects. For equivalent configs, request bodies andanthropic-betaheaders are byte-identical tomain(exceptdisable_parallel_tool_use=Truewithgenerate(tool_choice='required'), wheremaindropped the flag whenrequest.tool_choiceoverwroteconfig.tool_choiceand this PR preserves it). This folds in #6700 and follows the same rule #6698 applies to Gemini: provider configs are designed Genkit surfaces, not mirrors of the SDK.Previously,
AnthropicConfignested four SDK-shaped classes (ThinkingConfig,OutputConfig,TaskBudget,RequestMetadata), had three spellings of the thinking mode (enabled,adaptive,type), and mirrored Anthropic's rawtool_choiceobject with five classes that clashed withgenkit.ToolChoice. Some settings were silently dropped:generate'stool_choice='none', a budget with thinking disabled, or a display with no mode.Decisions
Literals; the plugin builds the wire shape. The fields arethinking(ThinkingMode),thinking_budget,thinking_display(ThinkingDisplay),effort(Effort),task_budget,user_idanddisable_parallel_tool_use. They map tothinking,output_config(merged with the structured-output format),metadata.user_idandtool_choice.thinking=is the single spelling of the mode.tool_choiceoption.'auto'maps to{'type': 'auto'},'required'maps to{'type': 'any'},'none'maps to{'type': 'none'}, and unset sends nothing. Anthropic carriesdisable_parallel_tool_useonly inside that object, so it is a flat flag: with notool_choiceit sends{'type': 'auto', ...}, the API default with tools, and it is never sent with'none'.'enabled'requires one.'adaptive'accepts and ignores a budget, as before.'disabled'with a budget orthinking_display,thinking_displaywith no mode, andthinking='enabled'or'adaptive'withtool_choice='required'now raiseINVALID_ARGUMENT.extracovers what has no Genkit equivalent.extra={'tool_choice': {'type': 'tool', 'name': 'lookup_menu'}}pins one named tool whentoolsare present, sotool_choiceleft Anthropic's managed body fields.extra={'thinking': {...}}orextra={'metadata': {...}}goes out whole.output_configstays managed, because replacing it would drop the structured-output format Genkit merges in.Breaking changes
ThinkingConfig,OutputConfig,TaskBudget,RequestMetadata,ToolChoice,AutoToolChoice,AnyToolChoice,SpecificToolChoiceandToolChoiceNone.thinking={...},output_config=,metadata=andtool_choice=raiseINVALID_ARGUMENTnaming the replacement. Theenabled/adaptivebools are gone.thinking='disabled'with a budget orthinking_display,thinking_displaywith no mode, andthinking='enabled'or'adaptive'withtool_choice='required'now raiseINVALID_ARGUMENT.thinking_budgetmust be an integer;'adaptive'used to accept a fractional budget.thinking,output_config,metadataandtool_choiceobjects are replaced bythinking(enum),thinkingBudget,thinkingDisplay,effort,taskBudget,userIdanddisableParallelToolUse.Known follow-ups
thinking,output_config,metadataandtool_choiceobjects (js/plugins/anthropic/src/types.ts).Verification
mainvs flat config here: thinking enabled, budget only, adaptive, disabled, display with enabled and adaptive, effort,task_budget,effort+task_budget+ structured output,user_id, and all of them together. URLs,anthropic-betaheaders and bodies are byte-identical;task_budgetstill selects the beta API with the default betas.tool_choicexdisable_parallel_tool_use, no tools,extraoverride, and the old config key.AnthropicConfig, so it gets the same surface; its tests pass.ruff check --preview, pyright, pyrefly, ty, and pytest pass.