Skip to content

feat(py)!: model types use Go's names; drop Candidate and model_ref - #6766

Merged
huangjeff5 merged 30 commits into
mainfrom
feat/py-model-surface
Oct 30, 2026
Merged

huangjeff5 merged 30 commits into
mainfrom
feat/py-model-surface

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

genkit.model aligns capability and usage types with Go (ModelSupports, ConstrainedSupport, ModelStage, GenerationUsage) and drops Candidate / ModelResponse.candidates and model_ref() in favor of direct ModelRef(...).

Stacked on #6757.

# --- BEFORE ---
from genkit.model import (
    Candidate,
    Constrained,
    ModelInfo,
    ModelResponse,
    ModelUsage,
    Stage,
    Supports,
    get_basic_usage_stats,
    model_ref,
)

ref = model_ref('menu-writer', namespace='bistro', config_schema=BistroConfig)
info = ModelInfo(
    stage=Stage.STABLE,
    supports=Supports(multiturn=True, tools=True, constrained=Constrained.ALL),
)
resp = ModelResponse(candidates=[Candidate(index=0, message=msg, finish_reason=FinishReason.STOP)])
usage = get_basic_usage_stats(messages)

# --- AFTER ---
from genkit.model import (
    ConstrainedSupport,
    FinishReason,
    GenerationUsage,
    ModelInfo,
    ModelRef,
    ModelResponse,
    ModelStage,
    ModelSupports,
)

# 1. Construct ModelRef directly with the full namespaced identifier
ref = ModelRef(name='bistro/menu-writer', config_schema=BistroConfig)

# 2. Declare model capabilities with Go-aligned types
info = ModelInfo(
    stage=ModelStage.STABLE,
    supports=ModelSupports(multiturn=True, tools=True, constrained=ConstrainedSupport.ALL),
)

# 3. Populate the primary reply directly on ModelResponse
resp = ModelResponse(message=msg, finish_reason=FinishReason.STOP)
usage = GenerationUsage.from_messages(messages)
if resp.finish_reason and resp.finish_reason.is_abnormal():
    ...

Main Changes

  • Candidate, ModelResponse.candidates, and ModelRequest.candidates are removed. Previously, ModelResponse carried both a top-level message and an optional candidates: list[Candidate] list that ai.generate(), streaming, and the Dev UI ignored after index 0. Every plugin now populates ModelResponse(message=..., finish_reason=..., finish_message=..., custom=...) directly, matching Go and JS. Gemini reads only candidate 0, so extra={'generationConfig': {'candidateCount': N}} is rejected with INVALID_ARGUMENT before the call instead of billing N candidates and returning one. Go refuses anything but 1 the same way.
  • Supports, Constrained, Stage, and ModelUsage are renamed to ModelSupports, ConstrainedSupport, ModelStage, and GenerationUsage (preserving wire JSON field aliases and enum values).
  • model_ref() is removed in favor of constructing ModelRef(name='namespace/model', ...) directly to match EmbedderRef and EvaluatorRef.
  • GenerationUsage.from_messages(messages) replaces the standalone get_basic_usage_stats() function, and FinishReason.is_abnormal() replaces the ABNORMAL_FINISH_REASONS constant.
  • Regular models reject ModelSupports(long_running=True) at construction time with INVALID_ARGUMENT and direct callers to BackgroundModel / define_background_model.

It's a handle over a background model's start, check and cancel actions,
not an Action subclass, and start() takes a ModelRequest. The new name
matches Go's ai.BackgroundModel and pairs with background_model() /
define_background_model(), the way Tool pairs with tool().
resolve_operation_model, create_deep_research_background_model and the
Veo builders return a BackgroundModel, so they drop the old action name.
stamp_operation_action keeps its name: it sets Operation.action.
@github-actions github-actions Bot added docs Improvements or additions to documentation python Python labels Oct 12, 2026

@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 model-related types in the Python SDK to align with Go's naming conventions, renaming ModelUsage to GenerationUsage, Supports to ModelSupports, Constrained to ConstrainedSupport, and Stage to ModelStage. Additionally, the helper function model_ref has been removed in favor of direct ModelRef instantiation, and model_action_metadata now expects a ModelInfo instance instead of a raw dictionary. Feedback on the changes suggests adding a backward-compatibility layer in _model_options to gracefully coerce dictionaries to ModelInfo instances, preventing runtime errors in existing third-party plugins or user code.

@huangjeff5 huangjeff5 changed the title feat(py)!: model types use Go's names; model_ref is gone; model_action_metadata takes ModelInfo feat(py)!: align genkit.model with Model, BackgroundModel, and Go type names; drop Candidate Oct 12, 2026
@huangjeff5 huangjeff5 changed the title feat(py)!: align genkit.model with Model, BackgroundModel, and Go type names; drop Candidate feat(py)!: model types use Go's names; drop Candidate and model_ref; model_action_metadata takes ModelInfo Oct 12, 2026
…d-model-name

# Conflicts:
#	py/packages/genkit/src/genkit/_ai/_model.py
@huangjeff5
huangjeff5 added this pull request to stack #6774 October 12, 2026 03:59
@huangjeff5 huangjeff5 changed the title feat(py)!: model types use Go's names; drop Candidate and model_ref; model_action_metadata takes ModelInfo feat(py)!: model types use Go's names; drop Candidate and model_ref Oct 12, 2026
…n_metadata takes ModelInfo

- Supports, Constrained, Stage -> ModelSupports, ConstrainedSupport, ModelStage
  (codegen output names; JSON unchanged).
- Export GenerationUsage; drop the ModelUsage alias.
- Remove model_ref(); build ModelRef(name=f'{ns}/{local}', ...) directly.
- model_action_metadata(*, name, info: ModelInfo | None, config_schema) shares
  one builder with model(), so listed and resolved models get the same label.
@huangjeff5
huangjeff5 force-pushed the feat/py-model-surface branch from aedb1dd to 77134e7 Compare October 12, 2026 05:01
…d-model-name

# Conflicts:
#	py/scripts/schema_to_typing.py
…e' into feat/py-model-surface

# Conflicts:
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py
#	py/packages/genkit-openai/tests/openai_model_test.py
#	py/packages/genkit/src/genkit/_ai/_model.py
#	py/packages/genkit/tests/genkit/ai/generate_config_keys_test.py
#	py/packages/genkit/tests/genkit/ai/generate_operation_test.py
#	py/packages/genkit/tests/genkit/ai/model_resolution_test.py
#	py/packages/genkit/tests/genkit/ai/model_test.py
#	py/packages/genkit/tests/genkit/core/endpoints/reflection_test.py
#	py/packages/genkit/tests/genkit/core/reflection_v2_test.py
#	py/packages/genkit/tests/genkit/veneer/veneer_test.py
#	py/scripts/schema_to_typing.py
… a stored handle dict

A stored handle is wire JSON. ai.check_operation / ai.cancel_operation take
the dict back directly and validate it with Operation.model_validate, which
stays extra='forbid'. A typo'd key or a missing id is INVALID_ARGUMENT with
the field named. A ModelResponse dump gets its own message pointing at
response.operation. The action still receives an Operation, so the published
check/cancel input schema is unchanged.

check_operation / cancel_operation are overloaded like JS checkOperation<T>:
Operation[T] -> Operation[T], a stored dict -> Operation[ModelResponse].
…es-only payloads; derive ABNORMAL_FINISH_REASONS from is_abnormal
# Conflicts:
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_gemini.py
#	py/packages/genkit/src/genkit/_core/_action.py
#	py/packages/genkit/tests/genkit/ai/genkit_api_test.py
#	py/packages/genkit/tests/genkit/ai/typed_config_required_test.py
…urface

# Conflicts:
#	py/docs/index.md
#	py/docs/types.md
#	py/packages/genkit-a2ui/src/genkit_a2ui/_middleware.py
#	py/packages/genkit-anthropic/src/genkit_anthropic/_models.py
#	py/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py
#	py/packages/genkit-anthropic/src/genkit_anthropic/_utils.py
#	py/packages/genkit-google-cloud/tests/cloud_spans_test.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_deep_research.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_veo.py
#	py/packages/genkit-middleware/tests/fallback_test.py
#	py/packages/genkit-ollama/src/genkit_ollama/_models.py
#	py/packages/genkit-openai/src/genkit_openai/_models/_model.py
#	py/packages/genkit/src/genkit/_core/_model.py
#	py/packages/genkit/src/genkit/_core/_typing.py
#	py/packages/genkit/tests/genkit/ai/typed_config_required_test.py
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.
…subclasses it

Go and JS split a generic core BackgroundAction[In, Out] (start/check/cancel
over Operation[Out]) from the AI-layer BackgroundModel. Python had only the
model-specific class, so core imported ModelRequest/ModelResponse and a
non-model job had nowhere to live.

- genkit/_core/_background.py: BackgroundAction[InT, OutT], a composite of
  start/check/cancel Actions (not an Action). InT/OutT are read off
  `class X(BackgroundAction[In, Out])`; instance state is written only in
  _bind, so a handle rebuilt from the registry matches the defined one.
  No model imports. Exported from genkit.plugin_api.
- genkit/_ai/_background_model.py: BackgroundModel(BackgroundAction[
  ModelRequest, ModelResponse]) with ModelInfo/config metadata, the start
  config check, and the "pass response.operation" guards. label and
  config_schema are derived from the start action.
- ai.check_operation / cancel_operation are generic like JS
  checkOperation<T>: Operation[T] -> Operation[T], dict -> Operation[Any].
  The handle's action key picks the class; model handles keep today's
  validation order, statuses, reasons and messages.
- Plugin.init/resolve/list_actions accept a BackgroundAction. The registry
  registers all three member actions, and resolves /check-operation and
  /cancel-operation keys through a plugin that only resolves the start key.
- Check/cancel actions carry the start metadata, like JS/Go.
Base automatically changed from refactor/py-background-model-name to main October 30, 2026 02:23
@huangjeff5
huangjeff5 merged commit d3018c3 into main Oct 30, 2026
26 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-model-surface branch October 30, 2026 02:34
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
Picks up #6757, #6766, #6777, #6775, #6764, #6709.

- _handler.py / fastapi_test.py: keep main's genkit.web imports
  (ContextProvider, RequestData, error_body, read_body, wants_stream) and
  this PR's to_sse / _stream_to_sse routing.
- _action.py: #6709 removed log_served_failure and
  served_stream_error_event; the core framer now logs with error_status
  (5xx traceback, 4xx warning) and frames {"error": error_body(e)}, same
  bytes as before.
- _action.py: keep the framer's stdlib logger (noqa TID251), same
  rationale as the adapter handlers' pyproject exemption.
huangjeff5 added a commit that referenced this pull request Oct 30, 2026
…types-dump

Conflict resolutions:
- py/packages/genkit/src/genkit/_core/_base.py: GenkitModel.model_config keeps
  main's validate_by_name/validate_by_alias (replacing populate_by_name) plus
  this PR's serialize_by_alias=True and ser_json_bytes='base64'. Main's new
  GenkitConfig class kept as is. Dropped the _keep_none_fields hook: its only
  user, GenerationCommonConfig, is a GenkitConfig on main (#6714), which the
  GenkitModel wrap serializer never touches, so it already keeps explicit None.
- py/scripts/schema_to_typing.py: took main's GenerationUsage.from_messages
  emission; dropped this PR's GenerationCommonConfig _keep_none_fields emission
  for the same reason.
- py/packages/genkit/src/genkit/_core/_typing.py: regenerated with
  ./py/bin/generate_schema_typing; now identical to origin/main.
  ./py/bin/generate_schema_typing --ci passes.

Post-merge fixes:
- nested_dump_test.py: model_ref(...) -> ModelRef(name=...) (#6766 removed
  the model_ref builder).
- flask_nested_types_test.py: type: ignore on @app.post, the same Flask
  T_route async-view error main's flask_test.py already carries.
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).
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 python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants