Skip to content
5 changes: 3 additions & 2 deletions packages/genkit-a2ui/src/genkit_a2ui/_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,9 @@ class Surfaces(Middleware[SurfacesConfig]):

Under `validation='strict'` a bad fence fails the turn: generate returns a
response with `finish_reason` failed, no `message`, and the reason on
`error`. `messages` ends at the user turn, so a retry does not feed the
hallucinated surface back to the model.
`error` (with `raise_on_error=True` it raises instead). `messages` ends at
the user turn, so a retry does not feed the hallucinated surface back to
the model.
"""

name = 'surfaces'
Expand Down
2 changes: 2 additions & 0 deletions packages/genkit-a2ui/tests/catalog_loader_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ async def test_generate_unknown_catalog_fails_the_turn_before_the_model() -> Non
model='scriptedModel',
prompt='banner',
use=[Surfaces(catalog=BANNER_CATALOG.id)],
raise_on_error=False,
)
assert_dead_turn(
response,
Expand Down Expand Up @@ -156,6 +157,7 @@ async def test_generate_strict_rejects_a_component_the_loaded_catalog_lacks() ->
model='scriptedModel',
prompt='weather',
use=[Surfaces(catalog=BANNER_CATALOG.id, validation='strict')],
raise_on_error=False,
)
assert_dead_turn(response, reason=ErrorReason.INVALID_OUTPUT, match='not in catalog')

Expand Down
5 changes: 5 additions & 0 deletions packages/genkit-a2ui/tests/generate_a2ui_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,7 @@ async def test_generate_a2ui_strict_fails_the_turn_on_bad_block() -> None:
model='scriptedModel',
prompt=WEATHER_PROMPT,
use=[Surfaces(validation='strict')],
raise_on_error=False,
)
assert_dead_turn(response, reason=ErrorReason.INVALID_OUTPUT, match='NotAThing')

Expand All @@ -234,6 +235,7 @@ async def test_generate_stream_strict_fails_the_turn_on_bad_block() -> None:
model='scriptedModel',
prompt=WEATHER_PROMPT,
use=[Surfaces(validation='strict')],
raise_on_error=False,
)
streamed_envs: list[dict[str, Any]] = []
async for chunk in stream.stream:
Expand Down Expand Up @@ -267,6 +269,7 @@ async def test_strict_refusal_keeps_the_tokens_the_turn_cost() -> None:
model='scriptedModel',
prompt=WEATHER_PROMPT,
use=[Surfaces(validation='strict')],
raise_on_error=False,
)

assert_dead_turn(response, reason=ErrorReason.INVALID_OUTPUT, match='NotAThing')
Expand Down Expand Up @@ -537,6 +540,7 @@ async def test_generate_a2ui_strict_fails_on_malformed_json_fence() -> None:
model='scriptedModel',
prompt=WEATHER_PROMPT,
use=[Surfaces(validation='strict')],
raise_on_error=False,
)
assert_dead_turn(response, reason=ErrorReason.INVALID_OUTPUT, match='failed to parse envelope block as JSON')

Expand Down Expand Up @@ -566,6 +570,7 @@ async def test_generate_a2ui_strict_fails_on_missing_root() -> None:
model='scriptedModel',
prompt=WEATHER_PROMPT,
use=[Surfaces(validation='strict')],
raise_on_error=False,
)
assert_dead_turn(response, reason=ErrorReason.INVALID_OUTPUT, match='id "root"')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ async def test_generate_bedrock_image_extra_prompt_field_fails_invalid_argument(
"""An `extra` key that would overwrite the prompt fails with INVALID_ARGUMENT and sends nothing."""
ai, transport = bedrock_app()

response = await ai.generate(model=model, prompt='a reef', config={'extra': extra})
response = await ai.generate(model=model, prompt='a reef', config={'extra': extra}, raise_on_error=False)

assert response.error is not None
assert response.error.status == 'INVALID_ARGUMENT'
Expand Down
15 changes: 9 additions & 6 deletions packages/genkit-anthropic/tests/anthropic_generate_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ async def test_plugin_without_key_and_no_tenant_key_raises_naming_both() -> None
api = FakeClaudeApi()
ai = _genkit(api, api_key=None)

response = await ai.generate(model=MODEL, prompt='hi')
response = await ai.generate(model=MODEL, prompt='hi', raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down Expand Up @@ -301,7 +301,7 @@ async def test_generate_claude_blank_secrets_key_fails_instead_of_using_plugin_k
api = FakeClaudeApi()
ai = _genkit(api, api_key=plugin_key)

response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': secrets})
response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': secrets}, raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down Expand Up @@ -356,7 +356,9 @@ async def test_generate_claude_secrets_key_on_client_that_cannot_swap_key_fails(
api = FakeClaudeApi()
ai = _genkit(api, **client_params)

response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': {'api_key': TENANT_KEY}})
response = await ai.generate(
model=MODEL, prompt='hi', context={'secrets': {'api_key': TENANT_KEY}}, raise_on_error=False
)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down Expand Up @@ -455,6 +457,7 @@ async def lookup_menu(dish: str) -> str:
tools=['lookup_menu'],
tool_choice='required',
config=config,
raise_on_error=False,
)

assert response.finish_reason == FinishReason.FAILED
Expand Down Expand Up @@ -595,7 +598,7 @@ async def test_generate_layered_thinking_without_any_budget_fails_before_send(
ai = _genkit(api)
claude = Anthropic.claude('claude-sonnet-4-6', config=AnthropicConfig(**default) if default else None)

response = await ai.generate(model=claude, prompt='hi', config=call_config)
response = await ai.generate(model=claude, prompt='hi', config=call_config, raise_on_error=False)

assert response.error is not None
assert response.error.status == 'INVALID_ARGUMENT'
Expand Down Expand Up @@ -658,7 +661,7 @@ async def wrap_model(self, params: Any, ctx: Any, next_fn: Any) -> Any: # noqa:
edit(params.request.config)
return await next_fn(params, ctx)

response = await ai.generate(model=MODEL, prompt='hi', config=config, use=[Tune()])
response = await ai.generate(model=MODEL, prompt='hi', config=config, use=[Tune()], raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.finish_message is not None
Expand Down Expand Up @@ -687,7 +690,7 @@ async def wrap_model(self, params: Any, ctx: Any, next_fn: Any) -> Any: # noqa:
edit(params.request.config)
return await next_fn(params, ctx)

response = await ai.generate(model=MODEL, prompt='hi', config=config, use=[Tune()])
response = await ai.generate(model=MODEL, prompt='hi', config=config, use=[Tune()], raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit-google-cloud/tests/cloud_spans_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -862,7 +862,7 @@ async def boom(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse:

ai.define_model(_MODEL, boom)
with _cloud_trace() as cloud:
response = await ai.generate(prompt=_PROMPT, model=_MODEL)
response = await ai.generate(prompt=_PROMPT, model=_MODEL, raise_on_error=False)
_force_flush()

assert response.finish_reason == FinishReason.FAILED
Expand Down
12 changes: 8 additions & 4 deletions packages/genkit-google-genai/tests/flat_config_rules_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ async def test_search_start_time_without_end_time_raises(sent: _Sent) -> None:
"""A time range needs both ends; the Gemini API rejects one."""
config = GeminiConfig(google_search_start_time=datetime(2026, 1, 1, tzinfo=timezone.utc))

response = await _googleai().generate(model=_GEMINI, prompt='hi', config=config)
response = await _googleai().generate(model=_GEMINI, prompt='hi', config=config, raise_on_error=False)

assert re.search('set google_search_start_time and google_search_end_time together', _failure(response))
assert sent.bodies == []
Expand Down Expand Up @@ -200,7 +200,9 @@ async def test_search_time_range_whole_second_end_is_unchanged(sent: _Sent) -> N
@pytest.mark.asyncio
async def test_file_search_top_k_without_store_names_raises(sent: _Sent) -> None:
"""File Search options with no store to search name the missing field."""
response = await _googleai().generate(model=_GEMINI, prompt='hi', config=GeminiConfig(file_search_top_k=5))
response = await _googleai().generate(
model=_GEMINI, prompt='hi', config=GeminiConfig(file_search_top_k=5), raise_on_error=False
)

assert re.search('file_search_top_k needs file_search_store_names', _failure(response))
assert sent.bodies == []
Expand Down Expand Up @@ -273,7 +275,7 @@ async def test_vertex_only_setting_raises_on_gemini_api(
sent: _Sent, model: str, config: GeminiConfig, field: str
) -> None:
"""The plugin names the flat field instead of letting google-genai raise on the nested one."""
response = await _googleai().generate(model=model, prompt='hi', config=config)
response = await _googleai().generate(model=model, prompt='hi', config=config, raise_on_error=False)

assert re.search(f'{re.escape(field)}.*Vertex AI only', _failure(response))
assert sent.bodies == []
Expand All @@ -293,7 +295,9 @@ async def test_vertex_only_setting_raises_on_gemini_api(
@pytest.mark.asyncio
async def test_gemini_api_only_file_search_raises_on_vertex_ai(sent: _Sent, config: GeminiConfig, field: str) -> None:
"""File Search is Gemini-API-only; Vertex AI rejects it naming the flat field."""
response = await _vertexai().generate(model='vertexai/gemini-2.5-flash', prompt='hi', config=config)
response = await _vertexai().generate(
model='vertexai/gemini-2.5-flash', prompt='hi', config=config, raise_on_error=False
)

assert re.search(f'{re.escape(field)}: Gemini API only, not supported on Vertex AI', _failure(response))
assert sent.bodies == []
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ async def _describe(ai: Genkit, url: str, content_type: str = 'image/png') -> An
content=[Part.from_text('describe'), Part.from_media(url=url, content_type=content_type)],
)
],
raise_on_error=False,
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1713,7 +1713,7 @@ async def test_generate_extra_cannot_set_fields_built_from_the_request(
"""The model id, input, and Lyria's system_instruction / tools are reserved; extra can't replace them."""
patcher, create_calls, _, _ = patch_interactions(f'genkit_google_genai._models.{mod}', create_result=_TEXT_REPLY)
with patcher:
response = await googleai.generate(model=model, prompt='hi', config={'extra': {key: 'x'}})
response = await googleai.generate(model=model, prompt='hi', config={'extra': {key: 'x'}}, raise_on_error=False)

assert response.error is not None
assert response.error.status == 'INVALID_ARGUMENT'
Expand Down Expand Up @@ -1748,7 +1748,7 @@ async def todays_specials() -> str:
'genkit_google_genai._models._interactions_lyria', create_result=_TEXT_REPLY
)
with patcher:
response = await googleai.generate(model=_LYRIA, prompt='hi', tools=['todays_specials'])
response = await googleai.generate(model=_LYRIA, prompt='hi', tools=['todays_specials'], raise_on_error=False)

assert response.error is not None
assert response.error.status == 'INVALID_ARGUMENT'
Expand Down Expand Up @@ -2048,6 +2048,7 @@ async def test_generate_antigravity_extra_empty_tools_list_raises_and_sends_noth
model=_ANTIGRAVITY,
prompt='hi',
config=AntigravityConfig(extra={key: []}),
raise_on_error=False,
)

assert response.error is not None
Expand All @@ -2072,6 +2073,7 @@ async def test_generate_antigravity_extra_non_list_tools_raises_and_sends_nothin
model=_ANTIGRAVITY,
prompt='hi',
config={'extra': {'tools': bad_tools}},
raise_on_error=False,
)

assert response.error is not None
Expand Down
2 changes: 1 addition & 1 deletion packages/genkit-google-genai/tests/plugin_network_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ async def test_no_max_retries_makes_one_attempt() -> None:
api = FlakyGoogleApi(failures=1)
ai = Genkit(plugins=[GoogleAI(api_key='k', http_client_factory=api.client)])

response = await ai.generate(model='googleai/gemini-2.5-flash', prompt='Suggest a dish.')
response = await ai.generate(model='googleai/gemini-2.5-flash', prompt='Suggest a dish.', raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down
9 changes: 5 additions & 4 deletions packages/genkit-middleware/tests/fallback_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ async def down(request: ModelRequest, ctx: ModelContext) -> ModelResponse:

ai.define_model(name='primary', fn=down)

response = await ai.generate(model='primary', prompt='hi', use=[Fallback(models=['nope'])])
response = await ai.generate(model='primary', prompt='hi', use=[Fallback(models=['nope'])], raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.finish_message == 'No model named "nope" is registered on this app.'
Expand All @@ -300,7 +300,7 @@ async def down(request: ModelRequest, ctx: ModelContext) -> ModelResponse:
responses=[ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('from backup')]))],
)

response = await ai.generate(model='primary', prompt='hi', use=[Fallback(models=['backup'])])
response = await ai.generate(model='primary', prompt='hi', use=[Fallback(models=['backup'])], raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.finish_message == 'internal error'
Expand Down Expand Up @@ -337,7 +337,7 @@ async def test_prompt_with_failing_on_chunk_and_fallback_does_not_call_backup()
def on_chunk(_: object) -> None:
raise RuntimeError('model sink closed')

response = await prompt(on_chunk=on_chunk, use=[Fallback(models=['backup'])])
response = await prompt(on_chunk=on_chunk, use=[Fallback(models=['backup'])], raise_on_error=False)

assert response.finish_reason == FinishReason.FAILED
assert response.finish_message == 'model sink closed'
Expand Down Expand Up @@ -393,6 +393,7 @@ def rewrite(_: ModelResponseChunk) -> None:
Fallback(models=['backup'], statuses=['INTERNAL', 'UNKNOWN', 'UNAVAILABLE']),
RaisingChunkRewriter(),
],
raise_on_error=False,
)
chunks = [chunk.text async for chunk in stream]
response = await stream.response
Expand Down Expand Up @@ -567,7 +568,7 @@ def on_chunk(_: object) -> None:
raise RuntimeError('model sink closed')

prompt = ai.define_prompt(model='wraps', prompt='hi')
response = await prompt(on_chunk=on_chunk, use=[Fallback(models=['backup'])])
response = await prompt(on_chunk=on_chunk, use=[Fallback(models=['backup'])], raise_on_error=False)

assert backup_pm.request_count == 0
assert response.finish_reason == FinishReason.FAILED
Expand Down
7 changes: 6 additions & 1 deletion packages/genkit-middleware/tests/retry_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ async def down(request: ModelRequest, ctx: ModelContext) -> ModelResponse:
model='down',
prompt='hi',
use=[Retry(max_retries=2, statuses=['UNAVAILABLE'], initial_delay_ms=0, no_jitter=True)],
raise_on_error=False,
)

assert response.finish_reason == FinishReason.FAILED
Expand Down Expand Up @@ -424,6 +425,7 @@ def on_chunk(_: object) -> None:
response = await prompt(
on_chunk=on_chunk,
use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)],
raise_on_error=False,
)

assert pm.request_count == 1
Expand Down Expand Up @@ -484,6 +486,7 @@ async def test_retry_does_not_retry_when_inner_middleware_chunk_callback_raises(
stream = ai.generate_stream(
prompt='Suggest a dish.',
use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True), _RaisingChunkRewriter()],
raise_on_error=False,
)
chunks = [chunk.text async for chunk in stream]
response = await stream.response
Expand Down Expand Up @@ -607,7 +610,9 @@ def on_chunk(_: object) -> None:
raise ValueError('model sink closed')

prompt = ai.define_prompt(model='wraps', prompt='hi')
response = await prompt(on_chunk=on_chunk, use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)])
response = await prompt(
on_chunk=on_chunk, use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)], raise_on_error=False
)

assert calls == 1
assert response.finish_reason == FinishReason.FAILED
Expand Down
12 changes: 9 additions & 3 deletions packages/genkit-ollama/tests/config_and_secrets_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,9 @@ async def test_generate_ollama_secrets_key_with_pinned_authorization_fails_preco
"""A static `Authorization` in `request_headers` is proxy auth; a secrets key fails instead of replacing it."""
ai = make_ai(request_headers={header_name: 'Bearer plugin'})

response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': {'api_key': 'tenant'}})
response = await ai.generate(
model=MODEL, prompt='hi', context={'secrets': {'api_key': 'tenant'}}, raise_on_error=False
)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand All @@ -300,7 +302,9 @@ def headers() -> dict[str, str]:

ai = make_ai(request_headers=headers)

response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': {'api_key': 'tenant'}})
response = await ai.generate(
model=MODEL, prompt='hi', context={'secrets': {'api_key': 'tenant'}}, raise_on_error=False
)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down Expand Up @@ -395,7 +399,9 @@ async def test_generate_ollama_unusable_secrets_key_raises_invalid_argument(serv
"""A `context.secrets.api_key` that is set but blank, not a string, or has whitespace fails; nothing is sent."""
ai = make_ai()

response = await ai.generate(model=MODEL, prompt='hi', context={'secrets': {'api_key': value}})
response = await ai.generate(
model=MODEL, prompt='hi', context={'secrets': {'api_key': value}}, raise_on_error=False
)

assert response.finish_reason == FinishReason.FAILED
assert response.error is not None
Expand Down
1 change: 1 addition & 0 deletions packages/genkit-ollama/tests/models/ollama_media_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ async def _describe(ai: Genkit, url: str) -> Any: # noqa: ANN401
content=[Part.from_text('describe'), Part.from_media(url=url, content_type='image/png')],
)
],
raise_on_error=False,
)


Expand Down
Loading
Loading