Skip to content

feat(py)!: response.error is Failure; GenkitError keeps only what callers use - #6767

Merged
huangjeff5 merged 1 commit into
mainfrom
feat/py-error-shapes
Nov 2, 2026
Merged

huangjeff5 merged 1 commit into
mainfrom
feat/py-error-shapes

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Genkit has two error shapes in Python: GenkitError is the exception you raise and except; Failure is the frozen record returned as data on .error (ModelResponse.error, Operation.error, AgentOutput.error, SessionSnapshot.error). GenkitError keeps only status, message, details, reason, retry_after_ms, and __cause__. Old names are removed with no deprecation aliases.

# --- BEFORE ---
from genkit import GenkitError, GenkitRuntimeError, RuntimeErrorReason
from genkit.model import OperationError, StreamingCallbackError

res = await ai.generate(prompt='Refund order A-17.', tools=['refund_order'])
res.error.status        # => 'INTERNAL'  (str)
res.error.details       # => {'stack': '', 'reason': 'TOOL_FAILED'}
res.error.reason is RuntimeErrorReason.TOOL_FAILED  # => True

try:
    await ai.generate(prompt='Summarize invoice.')
except GenkitError as e:
    e.cause                                   # => httpx.HTTPStatusError(...)
    e.response_metadata['retry_after_ms']     # => 3000.0
    e.http_code, e.source, e.trace_id         # => 429, None, None

# --- AFTER ---
from genkit import ErrorReason, Failure, GenkitError

res = await ai.generate(prompt='Refund order A-17.', tools=['refund_order'])
res.error.status        # => 'INTERNAL'  (StatusName | None)
res.error.details       # => {'reason': 'TOOL_FAILED'}
res.error.reason is ErrorReason.TOOL_FAILED  # => True

try:
    await ai.generate(prompt='Summarize invoice.')
except GenkitError as e:
    e.__cause__         # => httpx.HTTPStatusError(...)
    e.retry_after_ms    # => 3000.0

Main Changes

  • One Failure value type across all .error fields: Previously, response.error was GenkitRuntimeError while Operation.error was a separate message-only OperationError. Both—plus AgentOutput.error and SessionSnapshot.error—are now Failure (status, message, details, .reason), serializing to the same {status?, message, details?} wire JSON that JS (OperationSchema .passthrough()) and Go (errorWire) read.

  • Why Failure and ErrorReason (instead of RuntimeError or GenkitRuntimeError):

    • Not RuntimeError (genkit-schema.json / JS's compile-time type alias): exporting RuntimeError in Python shadows builtins.RuntimeError—importing it breaks raise RuntimeError(...) and crashes except RuntimeError: with TypeError: catching classes that do not inherit from BaseException is not allowed.
    • Not GenkitRuntimeError / OperationError (main's names): keeping -Error on a Pydantic BaseModel violates PEP 8 and creates the exact same trap (except GenkitRuntimeError: crashes at runtime with TypeError because it isn't an exception), and "RuntimeError" is a misnomer on background Operation.error (e.g., Veo or Batch jobs).
    • Failure + ErrorReason: makes the split unambiguous at the call site—GenkitError is raised/caught, Failure is plain data read off .error (similar to Go mapping the wire shape to private errorWire), and ErrorReason sits on both GenkitError.reason and Failure.reason without referencing a deleted RuntimeError class.
  • Lenient wire parsing for cross-SDK snapshots: Payloads written by JS, Go, or newer SDK versions can carry unknown keys, unrecognized statuses, or non-dict details. Failure drops unknown keys, maps unknown statuses to 'UNKNOWN', and wraps non-object details as {'value': <original>} instead of failing validation.

  • Trimmed GenkitError to what callers actually read: Removed .cause (use standard __cause__), response_metadata (replaced by retry_after_ms), trace_id, http_code, source, to_serializable(), to_callable_serializable(), Status, and HttpErrorWireFormat. Stack traces and trace IDs are added only when serializing for the Dev UI.

  • Stream callback errors fail the turn without retrying: Every on_chunk callback on MiddlewareContext is wrapped in a guard that raises _StreamingCallbackError(BaseException), bypassing except Exception in plugins and Retry/Fallback middleware to record ErrorReason.STREAM_CALLBACK_FAILED. Partial tool progress chunks (feat(py): stream typed tool chunks via ToolContext[ChunkT] #6314) are the one exception: they catch and drop callback errors so a flaky sink never aborts a side-effecting tool mid-run (matching Go's toolStreamer.send).

  • Strict status classification on agent turns: Previously, to_error_details read .status off arbitrary exceptions (turning aiohttp's status=429 into a status string). Now only GenkitError.status, CancelledError ('CANCELLED'), and TimeoutError ('DEADLINE_EXCEEDED') map to specific statuses; everything else maps to 'INTERNAL', matching Go's status.Classified.

Breaking changes

  • Removed with no aliases: GenkitRuntimeError, RuntimeErrorReason, OperationError, StreamingCallbackError, ErrorResponseMetadata, Status, HttpErrorWireFormat, and genkit-middleware's caused_by_caller_callback.
  • GenkitError: removed trace_id, .cause, .response_metadata, .http_code, .source, .to_serializable(), and to_callable_serializable().
  • Operation.error now carries full Failure (status, message, details), not just message.
  • MiddlewareContext.on_chunk assignment wraps callbacks in the guard (STREAM_CALLBACK_FAILED).

Migration

  • GenkitRuntimeError -> Failure; RuntimeErrorReason -> ErrorReason; OperationError(message=...) -> Failure(message=...).
  • StreamingCallbackError / caused_by_caller_callback -> check response.error.reason is ErrorReason.STREAM_CALLBACK_FAILED.
  • err.cause -> err.__cause__; err.response_metadata['retry_after_ms'] -> err.retry_after_ms.

JS / Go parity

  • Wire JSON ({status?, message, details?}): identical across JS, Go, and Python.
  • Two shapes (thrown exception vs data record) — matches JS: JS splits class GenkitError extends Error (thrown) from type RuntimeError (plain data on AgentOutput.error and SessionSnapshot.error). Go uses one struct (*status.Error) for both because Go's error is an interface (Error() string); Python can't do that because Pydantic BaseModel cannot subclass BaseException, so Python follows JS's two-shape split under a non-colliding name (JS has no built-in RuntimeError, whereas Python has builtins.RuntimeError).
  • Trimmed GenkitError — matches Go: dropping http_code, source, and .cause (in favor of __cause__) aligns with Go's status.Error, where HTTPCode and Source are deprecated and wrapping uses stdlib Unwrap().
  • Intentional deltas from JS/Go:
    • Operation.error unified onto Failure: JS ({ message: string } with .passthrough()) and Go (*OperationError { Message string }) still keep an older message-only OperationError type; Python reuses Failure so background ops preserve status and details, while remaining wire-compatible with JS's .passthrough() and Go's JSON decoder.
    • e.retry_after_ms flattened: JS nests e.responseMetadata?.retryAfterMs; Python exposes e.retry_after_ms directly instead of wrapping a single float in a dict.
    • ErrorReason in details['reason'] (pre-existing on main): all three SDKs now have ModelResponse.error (RuntimeError in JS with throwOnError: false, *status.Error on Go's partial ModelResponse, Failure in Python). Where Go classifies finer causes via status.Sentinel subtypes (errors.Is(err, ai.ErrToolFailed)), Python records ErrorReason in details['reason'] (.reason on both GenkitError and Failure), which also survives JSON round-tripping.

Rebase notes (lands last)

Lands after #7001 -> #6947 -> #6978 -> #6712 -> #6681 -> #6314:

Where to look

  • py/packages/genkit/src/genkit/_core/_error.py — Failure, ErrorReason, GenkitError, _StreamingCallbackError
  • py/packages/genkit/src/genkit/_core/_middleware.py — _GuardedOnChunk, MiddlewareContext.on_chunk
  • py/packages/genkit/src/genkit/_ai/_generate.py — run_generate callback wiring, box_from_exc, box_dead_turn
  • py/packages/genkit/src/genkit/_ai/_agents/_runtime.py — to_error_details

@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 error handling across the Genkit Python SDK, replacing RuntimeErrorReason with ErrorReason, GenkitRuntimeError with Failure, and replacing the custom .cause and response_metadata attributes with standard .__cause__ and direct retry_after_ms properties. Feedback on the changes highlights a compatibility issue in _runtime.py where both TimeoutError and asyncio.TimeoutError should be checked for Python 3.9 support. Additionally, the refactoring introduced several duplicated assertions and redundant self-comparisons (e.g., assert error.__cause__ is error.__cause__) across multiple test suites that should be cleaned up.

@huangjeff5
huangjeff5 added this pull request to stack #6771 October 12, 2026 01:09
Base automatically changed from feat/py-interrupt-base-exception to main October 31, 2026 04:10
@huangjeff5
huangjeff5 force-pushed the feat/py-error-shapes branch 3 times, most recently from 676b2d0 to c94aa3e Compare November 2, 2026 12:13

@pavelgj pavelgj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

…lers use

Every failure returned as data (ModelResponse.error, Operation.error,
AgentOutput.error, SessionSnapshot.error) is one frozen type, genkit.Failure.
It loads unknown keys, unknown statuses, and non-object details written by
other SDKs or newer versions instead of failing the read.

GenkitError keeps status, message, details, reason, retry_after_ms, and
__cause__. trace_id, cause, response_metadata, to_callable_serializable,
Status, and HttpErrorWireFormat are removed; http_code, source, and
to_serializable are private.

A raising on_chunk callback (caller's or middleware's) surfaces as a private
BaseException, fails the turn with STREAM_CALLBACK_FAILED, and is never
retried. Agent turns classify only Genkit statuses on the top-level exception.

GenkitRuntimeError -> Failure, RuntimeErrorReason -> ErrorReason,
genkit.model.OperationError and StreamingCallbackError removed with no aliases.
@huangjeff5
huangjeff5 force-pushed the feat/py-error-shapes branch from c94aa3e to 17d6aa4 Compare November 2, 2026 22:23
@huangjeff5
huangjeff5 merged commit 9ce58ef into main Nov 2, 2026
25 checks passed
@huangjeff5
huangjeff5 deleted the feat/py-error-shapes branch November 2, 2026 23:39
huangjeff5 added a commit that referenced this pull request Nov 3, 2026
huangjeff5 added a commit that referenced this pull request Nov 3, 2026
huangjeff5 added a commit that referenced this pull request Nov 3, 2026
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