Skip to content

refactor(py)!: BackgroundAction is the generic core; BackgroundModel subclasses it - #6757

Merged
huangjeff5 merged 14 commits into
mainfrom
refactor/py-background-model-name
Oct 30, 2026
Merged

huangjeff5 merged 14 commits into
mainfrom
refactor/py-background-model-name

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

BackgroundAction[In, Out] is the generic core for long-running jobs: a start, check and optional cancel action over Operation[Out]. BackgroundModel subclasses it as BackgroundAction[ModelRequest, ModelResponse]. This is the same split as Go and JS, and it mirrors Action vs Model.

# --- BEFORE ---
from genkit import Operation
from genkit.model import BackgroundAction  # model-specific despite the name

veo: BackgroundAction = ai.define_background_model(name='veo', start=start_job, check=check_job)
op = Operation.model_validate_json(saved_json)
op.output.media[0].url
# => AttributeError: 'dict' object has no attribute 'media'

# --- AFTER ---
from genkit import Operation
from genkit.model import BackgroundModel, ModelResponse
from genkit.plugin_api import BackgroundAction

# 1. A background model is a typed background action
veo: BackgroundModel = ai.define_background_model(name='veo', start=start_job, check=check_job)
assert isinstance(veo, BackgroundAction)

# 2. check_operation keeps the handle's output type
op: Operation[ModelResponse] = await ai.generate_operation(model=veo, prompt='A cat surfing at sunset.')
op = await ai.check_operation(op)
print(op.output.media[0].url)
# => https://cdn.example/promo.mp4

# 3. A stored JSON handle validates against the action it names
op = await ai.check_operation(json.loads(saved_json))
# => Operation[Any] statically; output is a ModelResponse at runtime

Main Changes

  • BackgroundAction is generic core, BackgroundModel subclasses it: Previously Python had one class, named BackgroundAction but model-only, with ModelRequest/ModelResponse baked into _core. _core/_background.py now has no model imports. BackgroundModel lives in _ai/_background_model.py and is exported from genkit.model. BackgroundAction is exported from genkit.plugin_api next to Action. It's a composite of three registered actions, not an Action subclass, the same as JS and Go.
  • Type facts come from the type arguments, instance state from the actions: Lookup rebuilds a handle from registered actions without calling __init__, so state set only in __init__ would be lost. __init_subclass__ reads In/Out off BackgroundAction[ModelRequest, ModelResponse], and _bind(start, check, cancel) is the only writer of instance state. BackgroundModel reads label and config_schema back from the start action. A looked-up model therefore validates ModelResponse and carries the same label as the one that was defined.
  • check_operation / cancel_operation are generic, like JS checkOperation<T>: Operation[T] in gives Operation[T] out, and a stored dict gives Operation[Any]. The handle's action is resolved first and the output is validated against that action's output type. Model handles keep their exact errors, statuses and reasons: UNSUPPORTED_BY_MODEL on cancel, the "pass response.operation" guard, and INVALID_ARGUMENT before any span.
  • Plugins can hand back the whole background action: Plugin.init / resolve / list_actions accept Action | BackgroundAction. When the registry gets a BackgroundAction for any of its keys (/background-model/{n}, /check-operation/{n}/check, /cancel-operation/{n}/cancel), it registers all three and returns the one asked for, as Go's Register does. Returning a bare Action still works. The plugin-side cleanup is in feat(py)!: Model, BackgroundModel, Embedder, and Tool classes replace lowercase builders #6777.
  • Operation is generic over its output: Operation(GenkitModel, Generic[Out]) with Out = Any, matching JS Operation<O = any> and Go core.Operation[Out]. Bare Operation has the same JSON schema as before; Operation[ModelResponse] validates output. Check and cancel actions now carry the start action's metadata, as in JS.

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().
@github-actions github-actions Bot added docs Improvements or additions to documentation python Python refactor labels Oct 11, 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 performs a comprehensive rename of BackgroundAction to BackgroundModel across the Python codebase, including documentation, core packages, plugins, and tests. It also updates related helper functions, variables, and error messages to reflect this change consistently. As there are no review comments, I have no feedback to provide.

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.
…d-model-name

# Conflicts:
#	py/packages/genkit/src/genkit/_ai/_model.py
@huangjeff5 huangjeff5 changed the title refactor(py)!: rename BackgroundAction to BackgroundModel refactor(py)!: BackgroundModel replaces BackgroundAction; Operation is generic over its output Oct 12, 2026
…d-model-name

# Conflicts:
#	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].
@apascal07

Copy link
Copy Markdown
Collaborator

FYI: In Go, a BackgroundModelAction is indeed a BackgroundAction which itself is a grouping of Actions:

return &BackgroundModelAction{*core.NewBackgroundActionOf(api.ActionTypeBackgroundModel, name, &core.BackgroundActionOptions[*ModelRequest, *ModelResponse]{
		Description: description,
		Metadata:    metadata,
		InputSchema: inputSchema,
		Check:       checkFn,
		Cancel:      o.Cancel,
	}, wrappedFn)}

BackgroundAction is a core concept, BackgroundModel is an ai concept, same as Model and Action.

# 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
…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.
@huangjeff5 huangjeff5 changed the title refactor(py)!: BackgroundModel replaces BackgroundAction; Operation is generic over its output refactor(py)!: BackgroundAction is the generic core; BackgroundModel subclasses it Oct 30, 2026
@huangjeff5

Copy link
Copy Markdown
Contributor Author

agreed, and done in 044a312. BackgroundAction[In, Out] is the generic core in _core (no model imports, exported from genkit.plugin_api), and BackgroundModel is BackgroundAction[ModelRequest, ModelResponse] in _ai, same split as Go/JS. check_operation is generic like JS checkOperation<T>, and plugins can return the whole BackgroundAction from init/resolve; the registry registers all three keys.

huangjeff5 added a commit that referenced this pull request Oct 30, 2026
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.
@huangjeff5
huangjeff5 merged commit 1e3db5a into main Oct 30, 2026
26 checks passed
@huangjeff5
huangjeff5 deleted the refactor/py-background-model-name branch October 30, 2026 02:23
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 refactor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants