Skip to content

refactor(py/anthropic)!: flat AnthropicConfig; tool choice from generate(tool_choice=) - #6699

Merged
huangjeff5 merged 69 commits into
mainfrom
fix/py-plugin-tool-choice
Oct 30, 2026
Merged

huangjeff5 merged 69 commits into
mainfrom
fix/py-plugin-tool-choice

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack: 3/3 · previous #6698

AnthropicConfig is flat and tool choice comes from Genkit's ai.generate(tool_choice=...). Choices are exported Literals (ThinkingMode, ThinkingDisplay, Effort), and the plugin builds Anthropic's nested thinking, output_config, metadata and tool_choice objects. For equivalent configs, request bodies and anthropic-beta headers are byte-identical to main (except disable_parallel_tool_use=True with generate(tool_choice='required'), where main dropped the flag when request.tool_choice overwrote config.tool_choice and 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, AnthropicConfig nested four SDK-shaped classes (ThinkingConfig, OutputConfig, TaskBudget, RequestMetadata), had three spellings of the thinking mode (enabled, adaptive, type), and mirrored Anthropic's raw tool_choice object with five classes that clashed with genkit.ToolChoice. Some settings were silently dropped: generate's tool_choice='none', a budget with thinking disabled, or a display with no mode.

from genkit_anthropic import Anthropic, AnthropicConfig

# --- BEFORE ---
AnthropicConfig(
    thinking=ThinkingConfig(type='enabled', budget_tokens=2048),
    output_config=OutputConfig(effort='high', task_budget=TaskBudget(total=20000)),
    tool_choice=AnyToolChoice(type='any', disable_parallel_tool_use=True),
)
await ai.generate(
    model='anthropic/claude-sonnet-4-6',
    prompt='Is the pho in stock?',
    tools=['lookup_menu'],
    tool_choice='none',
)
# => body has no tool_choice, so Claude can still call lookup_menu

# --- AFTER ---
# 1. Flat config; tool choice is a generate option
await ai.generate(
    model=Anthropic.claude('claude-sonnet-4-6'),
    prompt='Is the pho in stock?',
    tools=['lookup_menu'],
    tool_choice='auto',
    config=AnthropicConfig(
        thinking='enabled',
        thinking_budget=2048,
        effort='high',
        task_budget=20000,
        disable_parallel_tool_use=True,
    ),
)
# => {'thinking': {'type': 'enabled', 'budget_tokens': 2048},
#     'output_config': {'effort': 'high', 'task_budget': {'type': 'tokens', 'total': 20000}},
#     'tool_choice': {'type': 'auto', 'disable_parallel_tool_use': True}, ...}

# 2. An old nested key names its replacement
AnthropicConfig.model_validate({'output_config': {'effort': 'high'}})
# => GenkitError: INVALID_ARGUMENT: anthropic: output_config was flattened; use effort= and task_budget=

Decisions

  • Flat fields and exported Literals; the plugin builds the wire shape. The fields are thinking (ThinkingMode), thinking_budget, thinking_display (ThinkingDisplay), effort (Effort), task_budget, user_id and disable_parallel_tool_use. They map to thinking, output_config (merged with the structured-output format), metadata.user_id and tool_choice. thinking= is the single spelling of the mode.
  • Tool choice uses Genkit's tool_choice option. 'auto' maps to {'type': 'auto'}, 'required' maps to {'type': 'any'}, 'none' maps to {'type': 'none'}, and unset sends nothing. Anthropic carries disable_parallel_tool_use only inside that object, so it is a flat flag: with no tool_choice it sends {'type': 'auto', ...}, the API default with tools, and it is never sent with 'none'.
  • Ambiguous thinking settings raise instead of being dropped. A budget alone means enabled, and 'enabled' requires one. 'adaptive' accepts and ignores a budget, as before. 'disabled' with a budget or thinking_display, thinking_display with no mode, and thinking='enabled' or 'adaptive' with tool_choice='required' now raise INVALID_ARGUMENT.
  • extra covers what has no Genkit equivalent. extra={'tool_choice': {'type': 'tool', 'name': 'lookup_menu'}} pins one named tool when tools are present, so tool_choice left Anthropic's managed body fields. extra={'thinking': {...}} or extra={'metadata': {...}} goes out whole. output_config stays managed, because replacing it would drop the structured-output format Genkit merges in.

Breaking changes

  • Removed ThinkingConfig, OutputConfig, TaskBudget, RequestMetadata, ToolChoice, AutoToolChoice, AnyToolChoice, SpecificToolChoice and ToolChoiceNone. thinking={...}, output_config=, metadata= and tool_choice= raise INVALID_ARGUMENT naming the replacement. The enabled / adaptive bools are gone.
  • thinking='disabled' with a budget or thinking_display, thinking_display with no mode, and thinking='enabled' or 'adaptive' with tool_choice='required' now raise INVALID_ARGUMENT.
  • thinking_budget must be an integer; 'adaptive' used to accept a fractional budget.
  • Dev UI schema: the thinking, output_config, metadata and tool_choice objects are replaced by thinking (enum), thinkingBudget, thinkingDisplay, effort, taskBudget, userId and disableParallelToolUse.

Known follow-ups

  • JS: the Anthropic config still takes the nested thinking, output_config, metadata and tool_choice objects (js/plugins/anthropic/src/types.ts).

Verification

  • Wire: intercepted the real HTTP requests for 11 config cases, old nested config on main vs 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-beta headers and bodies are byte-identical; task_budget still selects the beta API with the default betas.
  • Anthropic HTTP matrix: each tool_choice x disable_parallel_tool_use, no tools, extra override, and the old config key.
  • Vertex Model Garden Claude uses AnthropicConfig, so it gets the same surface; its tests pass.
  • ruff format and ruff check --preview, pyright, pyrefly, ty, and pytest pass.

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.

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

@huangjeff5
huangjeff5 requested a review from hilariie October 9, 2026 15:46
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.
…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.
Base automatically changed from feat/py-google-genai-config-surface to main October 29, 2026 21:14
@huangjeff5
huangjeff5 requested a review from a team as a code owner October 29, 2026 21:14
…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
huangjeff5 merged commit b53cb03 into main Oct 30, 2026
26 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-plugin-tool-choice branch October 30, 2026 00:48
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation fix python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants