Skip to content

feat(py)!: Model, BackgroundModel, Embedder, and Tool classes replace lowercase builders - #6777

Merged
huangjeff5 merged 78 commits into
mainfrom
feat/py-tool-embedder-classes
Oct 30, 2026
Merged

huangjeff5 merged 78 commits into
mainfrom
feat/py-tool-embedder-classes

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Model, BackgroundModel, Embedder, and Tool are now PascalCase classes that replace lowercase factory functions (model(), background_model(), embedder(), tool()) and standalone metadata helpers (model_action_metadata(), embedder_action_metadata()). Plugins return these objects directly: init, resolve and list_actions take Action | BackgroundAction, so a background model is handed back whole instead of as three routed actions.

Stacked on #6766.

# --- BEFORE ---
from genkit import tool
from genkit.embedder import embedder, embedder_action_metadata
from genkit.model import model, model_action_metadata
from genkit.plugin_api import ActionMetadata

# Lowercase builders shadowed local variable names and module namespaces
chef_model = model('bistro/chef-v1', generate_chef, info=CHEF_INFO)
menu_embed = embedder('bistro/menu-embed', embed_menu, info=EMBED_INFO)

# Plugins duplicated schemas across metadata descriptors and runtime action factories
class BistroPlugin(Plugin):
    async def list_actions(self) -> list[ActionMetadata]:
        return [
            model_action_metadata('bistro/chef-v1', info=CHEF_INFO, config_schema=ChefConfig),
            embedder_action_metadata('bistro/menu-embed', info=EMBED_INFO, config_schema=EmbedConfig),
        ]

# --- AFTER ---
from genkit import Tool
from genkit.embedder import Embedder
from genkit.model import BackgroundModel, Model
from genkit.plugin_api import Action, ActionKind, BackgroundAction, Plugin

# 1. First-class PascalCase constructors avoid variable shadowing
chef_model = Model('bistro/chef-v1', generate_chef, info=CHEF_INFO, config_schema=ChefConfig)
menu_embed = Embedder('bistro/menu-embed', embed_menu, info=EMBED_INFO, config_schema=EmbedConfig)

# 2. Return actions and background actions directly from list_actions()
class BistroPlugin(Plugin):
    name = 'bistro'

    def _chef_model(self) -> Model:
        return Model('bistro/chef-v1', generate_chef, info=CHEF_INFO, config_schema=ChefConfig)

    def _menu_embedder(self) -> Embedder:
        return Embedder('bistro/menu-embed', embed_menu, info=EMBED_INFO, config_schema=EmbedConfig)

    async def list_actions(self) -> list[Action | BackgroundAction]:
        return [self._chef_model(), self._menu_embedder()]

# 3. Construct standalone tools directly via Tool(...)
check_inventory = Tool(lookup_stock, name='checkInventory', description='Check ingredient stock.')

Main Changes

  • PascalCase classes replace lowercase factory functions: Previously, from genkit.model import model and from genkit.embedder import embedder shadowed module names and common variable names in user code. We replaced them with Model, BackgroundModel, Embedder, and Tool classes because explicit types clarify construction boundaries and match Evaluator and BatchEvaluator.
  • list_actions() returns concrete actions instead of detached metadata: Previously, plugins maintained redundant ActionMetadata records for listing and separate factory functions for runtime execution. We changed Plugin.list_actions() to return Sequence[Action | BackgroundAction] directly because instantiating single-source actions eliminates schema drift between discovery and invocation.
  • Plugins return the background model, not its three actions: Previously, a plugin flattened a background model into .actions in init and routed /check-operation/{n}/check and /cancel-operation/{n}/cancel back to the same object by hand in resolve; forgetting the cancel branch broke cancellation silently. GoogleAI and VertexAI now return the BackgroundModel itself for Veo and Deep Research, and the registry (refactor(py)!: BackgroundAction is the generic core; BackgroundModel subclasses it #6757) registers all three keys from it. Calling plugin.resolve(CHECK_OPERATION, ...) directly now returns None; resolving through the registry, ai.check_operation and the Dev UI work as before.
  • Removed standalone *_action_metadata() helpers: Previously, callers used model_action_metadata() and embedder_action_metadata() to construct detached JSON-RPC descriptors. We removed them and made metadata extraction internal to Registry.list_actions() via _action_metadata() because external consumers should only interact with runnable actions.
  • Enforced wire schemas at construction time: Previously, actions registered without type annotations produced incomplete JSON-RPC reflection schemas. Model, Embedder, Evaluator, and BatchEvaluator now unconditionally stamp wire input_schema and output_schema in __init__ even when handler functions lack type annotations, ensuring reflection endpoints remain reliable.

…stering it

Plugins can now return evaluators from init()/resolve() the same way they
return models and embedders. evaluator_action_metadata takes the display
name, definition and billed flag so a listed evaluator shows the same card
in the Dev UI as the built one. The Vertex plugin uses both, so starting it
no longer constructs a throwaway Genkit app (and an extra Dev UI reflection
server), and its evaluator listing carries real names and billed=true.
…lder

# Conflicts:
#	py/packages/genkit-google-genai/src/genkit_google_genai/_evaluators/_evaluation.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_google.py
#	py/packages/genkit/src/genkit/_ai/_evaluator.py
… METRIC_CONFIGS directly

define_batch_evaluator uses _evaluator_metadata again instead of the
pre-#6669 block that wrote into the caller's nested evaluator dict, and
the builder keeps main's private name and config_schema type. Vertex
builds one evaluator per metric with no None path, and the duplicate
listing test folds its enum check into the existing one.
…ithout registering it

define_batch_evaluator is now batch_evaluator(...) plus register, the same
split as evaluator / define_evaluator, so a plugin can return a batch
evaluator from init() or resolve() without a registry.
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.
…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.
…lasses

# Conflicts:
#	py/packages/genkit-google-genai/src/genkit_google_genai/_google.py
# Conflicts:
#	py/packages/genkit-anthropic/tests/anthropic_models_test.py
#	py/packages/genkit-otel/tests/genai_instrumentation_test.py
#	py/packages/genkit/src/genkit/_ai/_model.py
#	py/packages/genkit/src/genkit/_core/_typing.py
#	py/scripts/schema_to_typing.py
…a-key' into feat/py-evaluator-builder

# Conflicts:
#	py/packages/genkit-ollama/src/genkit_ollama/plugin_api.py
#	py/packages/genkit/src/genkit/_ai/_evaluator.py
#	py/scripts/schema_to_typing.py
…lasses

# Conflicts:
#	py/packages/genkit-google-genai/src/genkit_google_genai/_google.py
#	py/packages/genkit-ollama/src/genkit_ollama/_plugin.py
#	py/packages/genkit/src/genkit/_ai/_embedding.py
#	py/packages/genkit/src/genkit/_ai/_model.py
#	py/packages/genkit/tests/genkit/ai/model_test.py
#	py/packages/genkit/tests/genkit/core/reflection_v2_test.py
…d-model-name

# Conflicts:
#	py/packages/genkit/src/genkit/_ai/_model.py
@huangjeff5 huangjeff5 changed the title feat(py)!: Model, BackgroundModel, Embedder, and Tool classes replace lowercase builders and *_action_metadata() feat(py)!: Model, BackgroundModel, Embedder, and Tool classes replace lowercase builders Oct 29, 2026
@huangjeff5

Copy link
Copy Markdown
Contributor Author

@apascal07 Dropped the Evaluator / BatchEvaluator class conversions and evaluator changes from this PR since evaluators are excluded from the 1.0 cut and removed in #6947. This PR now strictly introduces Model, BackgroundModel, Embedder, and Tool classes.

# 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
# Conflicts:
#	py/docs/index.md
#	py/docs/types.md
#	py/packages/genkit-amazon-bedrock/src/genkit_amazon_bedrock/_plugin.py
#	py/packages/genkit-anthropic/src/genkit_anthropic/_plugin.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_google.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_antigravity.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_deep_research.py
#	py/packages/genkit-google-genai/src/genkit_google_genai/_models/_interactions_lyria.py
#	py/packages/genkit-google-genai/tests/google_plugin_test.py
#	py/packages/genkit-middleware/src/genkit_middleware/_skills.py
#	py/packages/genkit-middleware/tests/tool_approval_test.py
#	py/packages/genkit/src/genkit/_ai/_aio.py
#	py/packages/genkit/src/genkit/_ai/_embedding.py
#	py/packages/genkit/src/genkit/_ai/_model.py
#	py/packages/genkit/src/genkit/_core/_background.py
#	py/packages/genkit/src/genkit/_core/_plugin.py
#	py/packages/genkit/tests/genkit/ai/ai_plugin_test.py
#	py/packages/genkit/tests/genkit/veneer/lookup_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.
Action generated input/output JSON schemas from the ModelRequest[Cfg] annotation, then Model replaced them with freshly generated ModelRequest/ModelResponse schemas. Action now takes the schemas a subclass publishes and builds only the validator from the annotation; fixed_json_schema generates each fixed class's schema once and hands out copies.
…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.
Brings in #6757's split: BackgroundAction is the generic core, BackgroundModel
subclasses it in genkit/_ai/_background_model.py. Conflict resolution ports
this branch's class rewrite onto the new layout:

- BackgroundAction(name, start, check, *, kind, cancel, metadata,
  description) and BackgroundModel(name, start, check, *, cancel, label,
  info, config_schema, metadata, description) build their actions and bind
  them; background_model() is gone, like the other lowercase builders.
- fixed_json_schema for the Operation output type, input type and
  Operation schemas, now in the shared builder.
- Plugin.list_actions is Sequence[Action | BackgroundAction[Any, Any]]
  (no ActionMetadata, per this branch); registry lists both.
…drop check/cancel routing

The registry now files a BackgroundAction's start, check and cancel actions
together and resolves check/cancel keys through the start key, so GoogleAI
and VertexAI return the BackgroundModel itself and stop hand-routing
/check and /cancel names. list_actions, init and the caches are typed
Action | BackgroundAction[Any, Any]. Tests resolve check/cancel through the
registry end to end.
# Conflicts:
#	py/packages/genkit-anthropic/tests/anthropic_config_test.py
Base automatically changed from feat/py-model-surface to main October 30, 2026 02:34
@huangjeff5
huangjeff5 merged commit ed850f4 into main Oct 30, 2026
26 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-tool-embedder-classes branch October 30, 2026 02:42
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
…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