Repository navigation
feat(py)!: response.error is Failure; GenkitError keeps only what callers use - #6767
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
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
added a commit
that referenced
this pull request
Oct 12, 2026
huangjeff5
force-pushed
the
feat/py-error-shapes
branch
3 times, most recently
from
November 2, 2026 12:13
676b2d0 to
c94aa3e
Compare
…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
force-pushed
the
feat/py-error-shapes
branch
from
November 2, 2026 22:23
c94aa3e to
17d6aa4
Compare
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Genkit has two error shapes in Python:
GenkitErroris the exception youraiseandexcept;Failureis the frozen record returned as data on.error(ModelResponse.error,Operation.error,AgentOutput.error,SessionSnapshot.error).GenkitErrorkeeps onlystatus,message,details,reason,retry_after_ms, and__cause__. Old names are removed with no deprecation aliases.Main Changes
One
Failurevalue type across all.errorfields: Previously,response.errorwasGenkitRuntimeErrorwhileOperation.errorwas a separate message-onlyOperationError. Both—plusAgentOutput.errorandSessionSnapshot.error—are nowFailure(status,message,details,.reason), serializing to the same{status?, message, details?}wire JSON that JS (OperationSchema.passthrough()) and Go (errorWire) read.Why
FailureandErrorReason(instead ofRuntimeErrororGenkitRuntimeError):RuntimeError(genkit-schema.json/ JS's compile-time type alias): exportingRuntimeErrorin Python shadowsbuiltins.RuntimeError—importing it breaksraise RuntimeError(...)and crashesexcept RuntimeError:withTypeError: catching classes that do not inherit from BaseException is not allowed.GenkitRuntimeError/OperationError(main's names): keeping-Erroron a PydanticBaseModelviolates PEP 8 and creates the exact same trap (except GenkitRuntimeError:crashes at runtime withTypeErrorbecause it isn't an exception), and "RuntimeError" is a misnomer on backgroundOperation.error(e.g., Veo or Batch jobs).Failure+ErrorReason: makes the split unambiguous at the call site—GenkitErroris raised/caught,Failureis plain data read off.error(similar to Go mapping the wire shape to privateerrorWire), andErrorReasonsits on bothGenkitError.reasonandFailure.reasonwithout referencing a deletedRuntimeErrorclass.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.Failuredrops unknown keys, maps unknown statuses to'UNKNOWN', and wraps non-objectdetailsas{'value': <original>}instead of failing validation.Trimmed
GenkitErrorto what callers actually read: Removed.cause(use standard__cause__),response_metadata(replaced byretry_after_ms),trace_id,http_code,source,to_serializable(),to_callable_serializable(),Status, andHttpErrorWireFormat. Stack traces and trace IDs are added only when serializing for the Dev UI.Stream callback errors fail the turn without retrying: Every
on_chunkcallback onMiddlewareContextis wrapped in a guard that raises_StreamingCallbackError(BaseException), bypassingexcept Exceptionin plugins and Retry/Fallback middleware to recordErrorReason.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'stoolStreamer.send).Strict status classification on agent turns: Previously,
to_error_detailsread.statusoff arbitrary exceptions (turningaiohttp'sstatus=429into a status string). Now onlyGenkitError.status,CancelledError('CANCELLED'), andTimeoutError('DEADLINE_EXCEEDED') map to specific statuses; everything else maps to'INTERNAL', matching Go'sstatus.Classified.Breaking changes
GenkitRuntimeError,RuntimeErrorReason,OperationError,StreamingCallbackError,ErrorResponseMetadata,Status,HttpErrorWireFormat, andgenkit-middleware'scaused_by_caller_callback.GenkitError: removedtrace_id,.cause,.response_metadata,.http_code,.source,.to_serializable(), andto_callable_serializable().Operation.errornow carries fullFailure(status,message,details), not justmessage.MiddlewareContext.on_chunkassignment wraps callbacks in the guard (STREAM_CALLBACK_FAILED).Migration
GenkitRuntimeError->Failure;RuntimeErrorReason->ErrorReason;OperationError(message=...)->Failure(message=...).StreamingCallbackError/caused_by_caller_callback-> checkresponse.error.reason is ErrorReason.STREAM_CALLBACK_FAILED.err.cause->err.__cause__;err.response_metadata['retry_after_ms']->err.retry_after_ms.JS / Go parity
{status?, message, details?}): identical across JS, Go, and Python.class GenkitError extends Error(thrown) fromtype RuntimeError(plain data onAgentOutput.errorandSessionSnapshot.error). Go uses one struct (*status.Error) for both because Go'serroris an interface (Error() string); Python can't do that because PydanticBaseModelcannot subclassBaseException, so Python follows JS's two-shape split under a non-colliding name (JShas no built-inRuntimeError, whereas Python hasbuiltins.RuntimeError).GenkitError— matches Go: droppinghttp_code,source, and.cause(in favor of__cause__) aligns with Go'sstatus.Error, whereHTTPCodeandSourceare deprecated and wrapping uses stdlibUnwrap().Operation.errorunified ontoFailure: JS ({ message: string }with.passthrough()) and Go (*OperationError { Message string }) still keep an older message-onlyOperationErrortype; Python reusesFailureso background ops preservestatusanddetails, while remaining wire-compatible with JS's.passthrough()and Go's JSON decoder.e.retry_after_msflattened: JS nestse.responseMetadata?.retryAfterMs; Python exposese.retry_after_msdirectly instead of wrapping a single float in a dict.ErrorReasonindetails['reason'](pre-existing onmain): all three SDKs now haveModelResponse.error(RuntimeErrorin JS withthrowOnError: false,*status.Erroron Go's partialModelResponse,Failurein Python). Where Go classifies finer causes viastatus.Sentinelsubtypes (errors.Is(err, ai.ErrToolFailed)), Python recordsErrorReasonindetails['reason'](.reasonon bothGenkitErrorandFailure), which also survives JSON round-tripping.Rebase notes (lands last)
Lands after
#7001->#6947->#6978->#6712->#6681->#6314:RuntimeErrorReasonuses toErrorReasonin_embedder.py,_aio.py,_ai/_model.py,_action.py,_core/_model.py.except Exception:toexcept (Exception, _StreamingCallbackError):inmake_tool_chunk_streamerso partial tool chunks stay best-effort while model and final tool chunks still fail withSTREAM_CALLBACK_FAILED.Where to look
py/packages/genkit/src/genkit/_core/_error.py—Failure,ErrorReason,GenkitError,_StreamingCallbackErrorpy/packages/genkit/src/genkit/_core/_middleware.py—_GuardedOnChunk,MiddlewareContext.on_chunkpy/packages/genkit/src/genkit/_ai/_generate.py—run_generatecallback wiring,box_from_exc,box_dead_turnpy/packages/genkit/src/genkit/_ai/_agents/_runtime.py—to_error_details