Skip to content

feat(py): support raise_on_error in generate (default False) - #43

Closed
huangjeff5 wants to merge 8 commits into
mainfrom
feat/py-1.0-pr0-raise-on-error
Closed

huangjeff5 wants to merge 8 commits into
mainfrom
feat/py-1.0-pr0-raise-on-error

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

Callers can now pass raise_on_error=True to ai.generate() and prompt calls to raise exceptions on failures instead of inspecting response.error.

# before (always boxed response on failure)
response = await ai.generate(model='my-model', prompt='...')
if response.finish_reason == FinishReason.FAILED:
    print(response.error.message)
    # => model crashed

# after: opt-in to direct exception raising
try:
    response = await ai.generate(model='my-model', prompt='...', raise_on_error=True)
except GenkitError as e:
    print(e.status, e.message)
    # => INTERNAL model crashed

Changes

  • Opt-in exception raising via raise_on_error: bool = False: When True, generate_action raises GenkitError (or preserves PublicError) on provider errors, tool exceptions, schema validation failures, and turn limits. When False (default), errors remain boxed in ModelResponse with 100% backward compatibility with 0.12/0.13.
  • Stream iteration raises on failure: When streaming with raise_on_error=True, iteration raises after any initial chunks yield, and await stream.response raises. With raise_on_error=False, stream iteration completes and stream.response yields the boxed FAILED response.
  • generate_operation() raises the original error: it already raised when a start failed. It now passes raise_on_error=True, so the exception carries the underlying message (e.g. RuntimeError: nope) instead of the scrubbed internal error, and a PublicError stays a PublicError. except GenkitError still catches both.

Breaking changes

None.

@huangjeff5
huangjeff5 force-pushed the feat/py-1.0-pr0-raise-on-error branch from f4ae0d5 to 1f40c6f Compare November 9, 2026 19:08
@huangjeff5
huangjeff5 force-pushed the feat/py-1.0-pr0-raise-on-error branch 3 times, most recently from a75b702 to b055d2f Compare November 9, 2026 22:03
@huangjeff5 huangjeff5 changed the title feat(py)!: raise by default on failed generate turns (raise_on_error) feat(py): support raise_on_error in generate (default False) Nov 9, 2026
ai.generate, ai.generate_stream, Prompt.__call__ and Prompt.stream take a
raise_on_error keyword, the Python spelling of JS throwOnError. When on,
they raise the error behind a failed turn instead of returning a
ModelResponse with finish_reason=FAILED and text ''. A follow-up commit
sets the default to False, so existing callers keep the boxed response.

Why: Python now matches JS generate(), which throws by default. The boxed
return predates 0.13 and was never a deliberate Python-only contract. It
made every `return response.text` flow serve HTTP 200 {"result": ""} on
provider 401/403/404/429/503, masked PublicError from tools and RBAC
middleware, and hid max_turns exhaustion, schema failures and bad
resumes.

Mechanism:
- generate_action checks the result inside the `generate` span. If
  response.error is set and raise_on_error is on, it raises
  failure_exception(result): `_failure.to_exception()` when the turn was
  boxed from an exception (PublicError stays PublicError), otherwise a
  GenkitError built from response.error.
- Loop-classified failures have no `_failure`, so they raise from
  response.error too: max_turns (ABORTED / MAX_TURNS_EXCEEDED), missing
  tool (NOT_FOUND / TOOL_NOT_FOUND), and INVALID_OUTPUT (INTERNAL).
- A stream the caller closed (caller_stopped) still resolves .response to
  ABORTED and does not raise.
- Streams raise from `async for` after the chunks already sent and from
  `await stream.response` (Channel already re-raises the task error).
- Boxed on purpose: the agent runtime passes raise_on_error=False; the
  Dev UI /util/generate action calls run_generate directly.
- generate_operation now raises the original error from its inner
  generate call; its own error check stays as a fallback.

Unchanged: the Failure type (#6767), dropped-failure logging (#7032),
HTTP PublicError rules (non-public errors still serve 500 "Internal
Error"). Out of scope, separate PRs: output typing narrowing (PR2-15),
web handler cleanup (PR5-05..07), RST_STREAM / to_sse unboxing for
raise_on_error=False paths (PR3-02), error detail preservation (PR3-03).

Tests: tests that assert the boxed shape now pass raise_on_error=False;
new raise_on_error_test.py covers one case per symptom plus the boxed
callers. Docs: migration guide entry, generate/generate_stream and
middleware docstrings, Failure docstring, ollama sample.
Plugin suites (anthropic, openai, google-genai, ollama, bedrock,
vertexai, middleware, a2ui, google-cloud) asserted the boxed FAILED
response from ai.generate and prompt calls. They now opt into
raise_on_error=False so they keep covering the boxed shape. The a2ui
Surfaces docstring now says a strict-validation failure raises.
Keep ai.generate, ai.generate_stream, and prompt calls returning boxed
ModelResponse by default (finish_reason=FAILED, response.error set) to
preserve 100% backward compatibility with 0.12/0.13 and align with the
agent loop runtime contract for long-running workflows. Callers can opt
into direct exception raising by passing raise_on_error=True.
Docstrings, the replace_on_chunk example, and the ollama sample still
described the raise-by-default behavior from an earlier commit. Restore
the sample from main, rewrite the docs for the shipped default, and drop
the response.error check in generate_operation that raise_on_error=True
already covers.
@huangjeff5
huangjeff5 force-pushed the feat/py-1.0-pr0-raise-on-error branch from b070bee to 7dd8746 Compare November 10, 2026 06:12
The Truncated structured output section and the Failure docstring still
passed raise_on_error=False as if it were needed. It is the default; show
raise_on_error=True as the opt-in instead.
The guide covers 0.12 -> 0.13. The 1.0 notes go to the release notes.
@huangjeff5
huangjeff5 added this pull request to stack #77 November 10, 2026 18:38
@huangjeff5

Copy link
Copy Markdown
Collaborator Author

Decision: Don't need to make this change actually. That flag is only there in JS for backwards compatability. Not sure this flag makes sense/makes a difference for background operations.

@huangjeff5 huangjeff5 closed this Nov 10, 2026
@huangjeff5
huangjeff5 deleted the feat/py-1.0-pr0-raise-on-error branch November 10, 2026 21:50
@huangjeff5
huangjeff5 removed this pull request from stack #77 November 10, 2026 22:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant