From c387d9da465f219460dedaa6193856eb3b2da77a Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 00:05:17 -0600 Subject: [PATCH 1/2] fix(py): enforce generate invariants for system=, docs= media, restart input, and max_turns - max_turns: validated up front. True, nan, inf, and 2.5 raise INVALID_ARGUMENT instead of running as 1 or leaking a ValidationError. A whole float like 3.0 from a .prompt file still works. Default stays 50 tool rounds. - restart(replace_input=...): history and the model's next turn carry the input the tool ran with. replacedInput is stripped from the history part so it doesn't read as a pending restart. A restart that pauses again pauses on the approved input. - system= with messages=: prepended; system messages already in history are sent as stored. system='' adds nothing. - prompt= with resume_respond/resume_restart: fails FAILED_PRECONDITION / INVALID_RESUME before the model runs, and the message names prompt=. - docs=: text only, `- [ref]: text`; metadata and media stay out of the prompt. Skipping docs= because a context part already exists now logs. - AgentInterrupt.metadata exposes the Interrupt(...) payload. - A bare restart() reads as resumed in ctx.is_resumed() and on the span. - Resume validation errors in reject_unanswered_interrupts set reason=INVALID_RESUME. --- .../genkit/src/genkit/_ai/_agents/_client.py | 9 + packages/genkit/src/genkit/_ai/_aio.py | 46 ++- packages/genkit/src/genkit/_ai/_generate.py | 109 ++++-- packages/genkit/src/genkit/_core/_model.py | 2 + packages/genkit/src/genkit/_core/_tool.py | 3 +- .../ai/generate_interrupt_resume_test.py | 5 +- .../tests/genkit/ai/generate_loop_test.py | 356 ++++++++++++++++++ 7 files changed, 490 insertions(+), 40 deletions(-) create mode 100644 packages/genkit/tests/genkit/ai/generate_loop_test.py diff --git a/packages/genkit/src/genkit/_ai/_agents/_client.py b/packages/genkit/src/genkit/_ai/_agents/_client.py index eafe6e82c..39f89a9e0 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_client.py +++ b/packages/genkit/src/genkit/_ai/_agents/_client.py @@ -196,10 +196,13 @@ def __init__( name: str, ref: str | None, input_data: InputT, + metadata: dict[str, Any] | None = None, ) -> None: self.name = name self.ref = ref self.input = input_data + # What the tool passed to ``Interrupt(...)``: approval reason, amount, etc. + self.metadata = metadata def respond(self, output: OutputT) -> Part: """Tool response for ``chat.resume(respond=[...])``. @@ -404,6 +407,11 @@ def error_from_exception(e: Exception) -> GenkitError: return GenkitError(status=status, message=message, cause=e) +def interrupt_payload(part: Part) -> dict[str, Any] | None: + payload = (part.metadata or {}).get('interrupt') + return cast(dict[str, Any], payload) if isinstance(payload, dict) else None + + def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrupt[Any, Any]]: if message is None: return [] @@ -418,6 +426,7 @@ def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrup name=req.name, ref=req.ref, input_data=req.input, + metadata=interrupt_payload(part), ) ) return interrupts diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 0a64b5aff..6ea273dd0 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -48,6 +48,7 @@ from genkit._ai._formats._types import Formatter from genkit._ai._generate import ( CallScope, + check_max_turns, define_generate_action, generate_action, register_middleware, @@ -1641,6 +1642,11 @@ class Weather(BaseModel): print(res.output) # => city='Paris' forecast='Sunny' + ``max_turns`` caps tool rounds (default 50, matching Go): the model may + call tools that many times and then reply, so a run uses at most + ``max_turns + 1`` model calls. Past the cap the response is ``ABORTED`` + with reason ``MAX_TURNS_EXCEEDED``. + ``prompt`` and ``system`` strings are sent exactly as written. Braces are content (JSON, code, or another template), not Handlebars. Partials (``{{> persona}}``), ``define_helper`` helpers and @@ -1840,12 +1846,7 @@ def generate_stream( """ initial_msgs: list[Message] = [] if not isinstance(messages, str): - if system: - initial_msgs.append(Message(role=Role.SYSTEM, content=parts_from_prompt(system))) - if messages: - initial_msgs.extend(messages) - if prompt: - initial_msgs.append(Message(role=Role.USER, content=parts_from_prompt(prompt))) + initial_msgs = call_messages(system=system, messages=messages, prompt=prompt) async def _run_generate( send_chunk: Callable[[ModelResponseChunk], None], @@ -1912,6 +1913,11 @@ async def _generate( """ if isinstance(messages, str): raise TypeError('messages must be a list of Message; pass text with prompt=') + # Before GenerateCall, whose lax int field turns True into 1. + check_max_turns(max_turns) + # prompt= with resume_respond/resume_restart puts a user turn after the + # paused tool request; resolve_resume_options fails that turn + # FAILED_PRECONDITION before the model runs, same as any bad resume. scope = CallScope(self) registry = scope.registry @@ -1922,13 +1928,7 @@ async def _generate( # strings passed at call time are content, not templates: braces may be # JSON, code, or another template. templates are what you define up # front (define_prompt, .prompt files, define_agent's system). - resolved_msgs: list[Message] = [] - if system: - resolved_msgs.append(Message(role=Role.SYSTEM, content=parts_from_prompt(system))) - if messages: - resolved_msgs.extend(messages) - if prompt: - resolved_msgs.append(Message(role=Role.USER, content=parts_from_prompt(prompt))) + resolved_msgs = call_messages(system=system, messages=messages, prompt=prompt) options = await to_generate_options( registry=registry, call=GenerateCall( @@ -2291,3 +2291,23 @@ async def generate_operation( if not response.operation: raise missing_operation_error(name=model_action.name) return as_model_operation(response.operation, name=model_action.name, status='INTERNAL') + + +def call_messages( + *, + system: str | list[Part] | None, + messages: list[Message] | None, + prompt: str | list[Part] | None, +) -> list[Message]: + """History for one generate call: system, then messages, then prompt. + + ``messages=`` is sent as given. A ``system=`` passed with it goes in + front; system messages already in that history stay where they are. + """ + out: list[Message] = [] + if system: + out.append(Message(role=Role.SYSTEM, content=parts_from_prompt(system))) + out.extend(messages or []) + if prompt: + out.append(Message(role=Role.USER, content=parts_from_prompt(prompt))) + return out diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 857c9d2f5..7070d6322 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -125,6 +125,8 @@ ToolResponse, ) +# Tool rounds allowed when the caller sets no max_turns; matches Go default. +# Each round is a paid model call; a run stops after this many turns. DEFAULT_MAX_TURNS = 50 # Interrupt is a BaseException so a tool's `except Exception` can't swallow it. @@ -675,7 +677,12 @@ def last_user_message(*, messages: list[Message]) -> Message | None: def context_item_template(d: Document, index: int) -> str: - """Render a document as a citation line for context injection.""" + """Render a document as a citation line for context injection. + + Only ``ref``/``id`` goes on the line, same as JS. Other metadata (ACLs, + embeddings, tenant ids) stays out of the prompt. Only the document's text + is rendered; media parts in a document are not sent. + """ out = '- ' ref = (d.metadata and (d.metadata.get('ref') or d.metadata.get('id'))) or index out += f'[{ref}]: ' @@ -714,6 +721,10 @@ def augment_with_context( if context_idx >= 0: meta = user_message.content[context_idx].metadata or {} if not meta.get('pending'): + logger.warning( + 'docs= not injected: the last user message already has a context part', + docs=len(request.docs), + ) return request # Render all documents as a single formatted text string @@ -741,6 +752,30 @@ def augment_with_context( return new_req +def check_max_turns(max_turns: object) -> None: + """max_turns is a whole, non-negative count of tool rounds. + + ``True`` would pass as 1 and ``nan`` would fail deep in validation, so + both get the same INVALID_ARGUMENT as a negative count. ``3.0`` (what + dotprompt's float field carries) is fine. + """ + if max_turns is None: + return + whole = isinstance(max_turns, int) or (isinstance(max_turns, float) and max_turns.is_integer()) + if isinstance(max_turns, bool) or not whole: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'max turns must be a whole number, got {max_turns!r}', + reason=ErrorReason.INVALID_INPUT, + ) + if cast(float, max_turns) < 0: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'max turns cannot be negative, got {max_turns}', + reason=ErrorReason.INVALID_INPUT, + ) + + def raise_if_stopped(caller_stopped: asyncio.Event | None) -> None: if caller_stopped is not None and caller_stopped.is_set(): raise GenkitError(status='CANCELLED', message='Generation aborted.') @@ -890,12 +925,7 @@ async def run_generate( ) if caller_stopped is not None and caller_stopped.is_set(): return box_aborted_turn(messages=list(options.messages or [])) - if options.max_turns is not None and options.max_turns < 0: - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'max turns cannot be negative, got {options.max_turns}', - reason=ErrorReason.INVALID_INPUT, - ) + check_max_turns(options.max_turns) # The veneer already checked ahead of its span. /util/generate (Dev UI, # reflection) starts here, so it fails before middleware or the model runs. reject_config_api_key(options.config) @@ -2748,6 +2778,29 @@ async def resolve_tool(registry: Registry, tool_ref: str | Tool) -> Action: return tool +def resume_precondition_message(messages: list[Message]) -> str: + """Why a resume can't answer this history, naming prompt= when that's the cause. + + ``prompt=`` with ``resume_respond``/``resume_restart`` appends a user turn + after the paused tool request, so the last message is no longer the one + the resume answers. + """ + message = ( + "Cannot 'resume' generation unless the previous message is a model message with at least one tool request." + ) + if ( + len(messages) >= 2 + and messages[-1].role == Role.USER + and messages[-2].role == Role.MODEL + and any(p.tool_request is not None for p in messages[-2].content) + ): + message += ( + ' The last message is a user turn after the paused tool request;' + ' resume_respond/resume_restart cannot be combined with prompt=.' + ) + return message + + async def resolve_resume_options( *, options: GenerateActionOptions, @@ -2766,10 +2819,7 @@ async def resolve_resume_options( if last_message is None or last_message.role != Role.MODEL or len(tool_requests) == 0: raise PublicError( 'FAILED_PRECONDITION', - ( - "Cannot 'resume' generation unless the previous message is a model " - 'message with at least one tool request.' - ), + resume_precondition_message(messages), reason=ErrorReason.INVALID_RESUME, ) @@ -2937,6 +2987,7 @@ async def resolve_resumed_tool( message=f'Tool {tool_req.name} not found', reason=ErrorReason.TOOL_NOT_FOUND, ) + ran_request, metadata, interrupt = restarted_tool_request(original=tool_req_root, restart=restart_trp) try: executed = await run_restart( tool=tool, @@ -2947,22 +2998,13 @@ async def resolve_resumed_tool( except TOOL_RAISES as e: intr = interrupt_from_exc(e) if intr is not None: - return (interrupt_request_part(tool_req_root, intr), None) + # Paused again on the input it actually ran with, so the next + # answer (and the history) sees the approved input. + return (interrupt_request_part(Part(tool_request=ran_request, metadata=metadata), intr), None) log_dropped_failure(e, tool=tool_req.name) raise - metadata = dict(tool_req_root.metadata) if tool_req_root.metadata else {} - interrupt = metadata.get('interrupt') - if interrupt: - del metadata['interrupt'] return ( - Part( - tool_request=ToolRequest( - name=tool_req.name, - ref=tool_req.ref, - input=tool_req.input, - ), - metadata={**metadata, 'resolvedInterrupt': interrupt}, - ), + Part(tool_request=ran_request, metadata={**metadata, 'resolvedInterrupt': interrupt}), executed, ) @@ -3058,6 +3100,25 @@ async def next_fn(p: ToolHookParams, ctx: MiddlewareContext) -> MultipartToolRes ) +def restarted_tool_request(*, original: Part, restart: Part) -> tuple[ToolRequest, dict[str, Any], object]: + """The tool request history keeps for a restart: the input the tool ran with. + + ``restart(replace_input=...)`` swaps the input. History and the model's + next turn read the approved input. The original input is not recorded: + on a tool request in history, ``replacedInput`` would read as a pending + restart. Returns the request, its metadata without ``interrupt`` or + ``replacedInput``, and the interrupt payload. + """ + original_req = original.tool_request + restart_req = restart.tool_request + assert original_req is not None and restart_req is not None + metadata = dict(original.metadata) if original.metadata else {} + interrupt = metadata.pop('interrupt', None) + metadata.pop('replacedInput', None) + ran = ToolRequest(name=original_req.name, ref=original_req.ref, input=restart_req.input) + return ran, metadata, interrupt + + def matching_restart( *, restarts: list[Part] | None, diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 2001cdf67..01e98b290 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -923,6 +923,7 @@ def reject_unanswered_interrupts( f'resume part for {name!r} is still an interrupt; ' 'use Part.restart(...) or Part.respond(...) before generate.' ), + reason=ErrorReason.INVALID_RESUME, ) for part in respond or []: if part.tool_request is not None and part.tool_response is None: @@ -930,6 +931,7 @@ def reject_unanswered_interrupts( raise GenkitError( status='INVALID_ARGUMENT', message=(f'resume_respond got the paused request for {name!r}; answer it with Part.respond(output)'), + reason=ErrorReason.INVALID_RESUME, ) diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index c65749d1f..4ddb0cf61 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -322,7 +322,8 @@ async def call_tool_fn( function through here, so resume metadata reaches it either way. """ resumed_meta = _tool_resumed_metadata.get() - if resumed_meta: + # A bare restart() resumes with {}; it is still a resume. + if resumed_meta is not None: # Record resumed metadata on the current span for observability. set_custom_metadata_attributes({'resumed': resumed_meta}) # The ctx parameter always receives this ToolContext, whatever context diff --git a/packages/genkit/tests/genkit/ai/generate_interrupt_resume_test.py b/packages/genkit/tests/genkit/ai/generate_interrupt_resume_test.py index 4339f9cd3..a05054ebe 100644 --- a/packages/genkit/tests/genkit/ai/generate_interrupt_resume_test.py +++ b/packages/genkit/tests/genkit/ai/generate_interrupt_resume_test.py @@ -853,7 +853,8 @@ async def pay(inp: dict) -> str: 'content': [ {'text': 'x'}, { - 'toolRequest': {'ref': 'p1', 'name': 'pay', 'input': {}}, + # History keeps the input the restart ran with. + 'toolRequest': {'ref': 'p1', 'name': 'pay', 'input': {'ok': True}}, 'metadata': {'resolvedInterrupt': {'hold': True}}, }, ], @@ -1021,7 +1022,7 @@ async def b_tool(inp: dict) -> str: 'metadata': {'resolvedInterrupt': {'tool': 'a'}}, }, { - 'toolRequest': {'ref': 'rb', 'name': 'b', 'input': {}}, + 'toolRequest': {'ref': 'rb', 'name': 'b', 'input': {'ok': True}}, 'metadata': {'resolvedInterrupt': {'tool': 'b'}}, }, ], diff --git a/packages/genkit/tests/genkit/ai/generate_loop_test.py b/packages/genkit/tests/genkit/ai/generate_loop_test.py new file mode 100644 index 000000000..c900cfc37 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/generate_loop_test.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""Turn-loop invariants: max_turns, restart input, system= with history, docs=, and resume with prompt=.""" + +import pytest + +from genkit import ( + Document, + Genkit, + Interrupt, + Message, + ModelResponse, + Part, + ToolContext, +) +from genkit._ai._agents._client import agent_interrupts_from_message +from genkit._ai._generate import CallScope, augment_with_context, generate_action, restarted_tool_request +from genkit._core._error import ErrorReason, GenkitError +from genkit._core._model import GenerateActionOptions, ModelRequest +from genkit._core._typing import FinishReason, Role, ToolRequest +from genkit.testing import ScriptedModel, define_scripted_model + + +def _answers(text: str) -> ModelResponse: + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text(text)]), + ) + + +def _transfer_request(amount: int) -> ModelResponse: + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message( + role=Role.MODEL, + content=[Part(tool_request=ToolRequest(name='transfer', input={'days': amount}, ref='t1'))], + ), + ) + + +def _hitl_app() -> tuple[Genkit, ScriptedModel, list[object]]: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + ran_with: list[object] = [] + + @ai.tool(name='transfer') + async def transfer(inp: dict, ctx: ToolContext) -> str: + if not ctx.is_resumed(): + raise Interrupt({'reason': 'needs approval', 'days': inp['days']}) + ran_with.append(inp) + return f'booked {inp["days"]} days' + + return ai, pm, ran_with + + +@pytest.mark.asyncio +async def test_restart_replace_input_is_the_input_history_keeps() -> None: + """The model's next turn and the audit trail see the approved input, not the original.""" + ai, pm, ran_with = _hitl_app() + pm.responses = [_transfer_request(7), _answers('booked')] + + paused = await ai.generate(prompt='book 7 days', tools=['transfer']) + assert paused.finish_reason == FinishReason.INTERRUPTED + intr = paused.interrupts[0] + assert intr.metadata is not None + assert intr.metadata['interrupt'] == {'reason': 'needs approval', 'days': 7} + + done = await ai.generate( + messages=paused.messages, + tools=['transfer'], + resume_restart=intr.restart(replace_input={'days': 5}), + ) + + assert ran_with == [{'days': 5}] + assert done.text == 'booked' + model_turn = next(m for m in done.messages if m.role == Role.MODEL and m.content[0].tool_request is not None) + part = model_turn.content[0] + assert part.tool_request is not None + assert part.tool_request.input == {'days': 5} + assert part.metadata is not None + # On a tool request in history, replacedInput would read as a restart. + assert 'replacedInput' not in part.metadata + assert part.metadata['resolvedInterrupt'] == {'reason': 'needs approval', 'days': 7} + assert 'interrupt' not in part.metadata + assert 'resumed' not in part.metadata + # The model reads the approved input on the turn after the restart. + assert pm.last_request is not None + sent = next(m for m in pm.last_request.messages if m.role == Role.MODEL) + assert sent.content[0].tool_request is not None + assert sent.content[0].tool_request.input == {'days': 5} + + +@pytest.mark.asyncio +async def test_restart_without_replace_input_keeps_the_model_input() -> None: + ai, pm, ran_with = _hitl_app() + pm.responses = [_transfer_request(7), _answers('booked')] + + paused = await ai.generate(prompt='book 7 days', tools=['transfer']) + done = await ai.generate( + messages=paused.messages, + tools=['transfer'], + resume_restart=paused.interrupts[0].restart(), + ) + + assert ran_with == [{'days': 7}] + model_turn = next(m for m in done.messages if m.role == Role.MODEL and m.content[0].tool_request is not None) + assert model_turn.content[0].tool_request is not None + assert model_turn.content[0].tool_request.input == {'days': 7} + assert 'replacedInput' not in (model_turn.content[0].metadata or {}) + + +@pytest.mark.asyncio +async def test_restart_that_pauses_again_keeps_the_replaced_input() -> None: + """A second approval step sees the input the restart ran with.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + + @ai.tool(name='transfer') + async def transfer(inp: dict, ctx: ToolContext) -> str: + raise Interrupt({'reason': 'second approver', 'days': inp['days']}) + + pm.responses = [_transfer_request(7)] + paused = await ai.generate(prompt='book 7 days', tools=['transfer']) + again = await ai.generate( + messages=paused.messages, + tools=['transfer'], + resume_restart=paused.interrupts[0].restart(replace_input={'days': 5}), + ) + + assert again.finish_reason == FinishReason.INTERRUPTED + part = again.interrupts[0] + assert part.tool_request is not None + assert part.tool_request.input == {'days': 5} + assert part.metadata is not None + assert part.metadata['interrupt'] == {'reason': 'second approver', 'days': 5} + assert 'replacedInput' not in part.metadata + + +def test_restarted_tool_request_never_carries_replaced_input() -> None: + """Neither the restart part nor a stale history part can put replacedInput back on history.""" + original = Part( + tool_request=ToolRequest(name='transfer', input={'days': 7}, ref='t1'), + metadata={'interrupt': {'reason': 'approve'}, 'replacedInput': {'days': 9}, 'note': 'kept'}, + ) + restart = Part( + tool_request=ToolRequest(name='transfer', input={'days': 5}, ref='t1'), + metadata={'resumed': True, 'replacedInput': {'days': 7}}, + ) + + ran, metadata, interrupt = restarted_tool_request(original=original, restart=restart) + + assert ran.input == {'days': 5} + assert metadata == {'note': 'kept'} + assert interrupt == {'reason': 'approve'} + + +def test_agent_interrupt_exposes_the_interrupt_payload() -> None: + message = Message( + role=Role.MODEL, + content=[ + Part( + tool_request=ToolRequest(name='transfer', input={'days': 7}, ref='t1'), + metadata={'interrupt': {'reason': 'needs approval'}}, + ) + ], + ) + + [intr] = agent_interrupts_from_message(message) + + assert intr.metadata == {'reason': 'needs approval'} + + +@pytest.mark.asyncio +async def test_system_with_saved_history_goes_first_and_keeps_history() -> None: + """system= is prepended; the saved chat's own system message is sent as stored.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('Bonjour'), _answers('Bill: $42')] + + first = await ai.generate(system='You are the host.', prompt='Hi') + await ai.generate(system='You are the cashier.', messages=first.messages, prompt='Check please') + + assert pm.last_request is not None + sent = pm.last_request.messages + assert [m.role for m in sent] == [Role.SYSTEM, Role.SYSTEM, Role.USER, Role.MODEL, Role.USER] + assert sent[0].text == 'You are the cashier.' + assert sent[1].text == 'You are the host.' + + +@pytest.mark.asyncio +async def test_empty_system_adds_nothing_and_keeps_history() -> None: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('Bonjour'), _answers('ok')] + + first = await ai.generate(system='You are the host.', prompt='Hi') + await ai.generate(system='', messages=first.messages, prompt='Thanks') + + assert pm.last_request is not None + sent = pm.last_request.messages + assert [m.role for m in sent] == [Role.SYSTEM, Role.USER, Role.MODEL, Role.USER] + assert sent[0].text == 'You are the host.' + + +@pytest.mark.asyncio +async def test_omitted_system_keeps_the_saved_persona() -> None: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('Bonjour'), _answers('ok')] + + first = await ai.generate(system='You are the host.', prompt='Hi') + await ai.generate(messages=first.messages, prompt='Thanks') + + assert pm.last_request is not None + assert pm.last_request.messages[0].role == Role.SYSTEM + assert pm.last_request.messages[0].text == 'You are the host.' + + +def test_docs_context_is_text_only_and_leaves_metadata_out() -> None: + """Citation line is `- [ref]: text`; metadata and media parts stay out of the prompt.""" + request = ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('Which dishes are vegan?')])], + docs=[ + Document( + content=[ + Part.from_text('Lentil soup'), + Part.from_media('gs://menu/soup.png', content_type='image/png'), + ], + metadata={'id': 'menu-7', 'acl': ['user-7'], 'embedding': [0.1, 0.2]}, + ) + ], + ) + + augmented = augment_with_context(request) + + user = augmented.messages[-1] + context = [p for p in user.content if (p.metadata or {}).get('purpose') == 'context'] + assert len(context) == 1 + assert context[0].text is not None + assert '\n- [menu-7]: Lentil soup\n' in context[0].text + assert 'acl' not in context[0].text + assert 'embedding' not in context[0].text + assert 'user-7' not in context[0].text + assert all(p.media is None for p in user.content) + + +def test_docs_context_without_extra_metadata_is_unchanged() -> None: + request = ModelRequest( + messages=[Message(role=Role.USER, content=[Part.from_text('hi')])], + docs=[Document.from_text('Lentil soup', metadata={'ref': 'r1'})], + ) + + augmented = augment_with_context(request) + + text = augmented.messages[-1].content[-1].text + assert text is not None + assert '- [r1]: Lentil soup\n' in text + + +@pytest.mark.asyncio +@pytest.mark.parametrize('bad', [True, False, float('nan'), float('inf'), 2.5]) +async def test_max_turns_rejects_non_whole_numbers(bad: object) -> None: + """max_turns=True used to run as 1; nan leaked a raw ValidationError.""" + ai = Genkit(model='scriptedModel') + define_scripted_model(ai) + + with pytest.raises(GenkitError) as raised: + await ai.generate(prompt='hi', max_turns=bad) # type: ignore[arg-type] + + assert raised.value.status == 'INVALID_ARGUMENT' + + +@pytest.mark.asyncio +async def test_max_turns_accepts_a_whole_float_from_dotprompt() -> None: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('ok')] + + response = await generate_action( + CallScope(ai), + GenerateActionOptions( + model='scriptedModel', + messages=[Message(role=Role.USER, content=[Part.from_text('hi')])], + max_turns=3.0, + ), + ) + + assert response.text == 'ok' + + +@pytest.mark.asyncio +async def test_prompt_with_resume_fails_before_the_model_runs() -> None: + """Same boxed FAILED_PRECONDITION as any resume whose last message isn't a tool request.""" + ai, pm, ran_with = _hitl_app() + pm.responses = [_transfer_request(7)] + paused = await ai.generate(prompt='book 7 days', tools=['transfer']) + calls = pm.request_count + + response = await ai.generate( + prompt='also add breakfast', + messages=paused.messages, + tools=['transfer'], + resume_restart=paused.interrupts[0].restart(), + ) + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert response.error.reason is ErrorReason.INVALID_RESUME + assert response.error.message.startswith( + "Cannot 'resume' generation unless the previous message is a model message" + ) + assert 'prompt=' in response.error.message + assert pm.request_count == calls + assert ran_with == [] + + +@pytest.mark.asyncio +async def test_resume_without_a_paused_tool_request_does_not_mention_prompt() -> None: + ai, pm, _ = _hitl_app() + + response = await ai.generate( + messages=[Message(role=Role.USER, content=[Part.from_text('book 7 days')])], + tools=['transfer'], + resume_restart=Part(tool_request=ToolRequest(name='transfer', input={}, ref='t1'), metadata={'resumed': True}), + ) + + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert response.error.reason is ErrorReason.INVALID_RESUME + assert 'prompt=' not in response.error.message + assert pm.request_count == 0 + + +@pytest.mark.asyncio +async def test_bare_restart_still_reads_as_resumed() -> None: + """restart() with no metadata resumes with {}; the tool must still see a resume.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + seen: list[object] = [] + + @ai.tool(name='transfer') + async def transfer(inp: dict, ctx: ToolContext) -> str: + if not ctx.is_resumed(): + raise Interrupt({'reason': 'approve'}) + seen.append(ctx.resumed_metadata) + return 'ok' + + pm.responses = [_transfer_request(7), _answers('done')] + paused = await ai.generate(prompt='book', tools=['transfer']) + await ai.generate(messages=paused.messages, tools=['transfer'], resume_restart=paused.interrupts[0].restart()) + + assert len(seen) == 1 From 5589fb33f9fc5a4831f68f166c8d8e3e17e46b0f Mon Sep 17 00:00:00 2001 From: Jeff Huang Date: Thu, 12 Nov 2026 17:05:59 -0600 Subject: [PATCH 2/2] fix(py): address PR #83 review feedback on max_turns, resume preconditions, and interrupt metadata --- .../genkit/src/genkit/_ai/_agents/_client.py | 9 -- packages/genkit/src/genkit/_ai/_aio.py | 20 ++- packages/genkit/src/genkit/_ai/_generate.py | 111 ++++----------- packages/genkit/src/genkit/_ai/_prompt.py | 21 ++- packages/genkit/src/genkit/_core/_model.py | 39 ++++++ .../tests/genkit/ai/generate_loop_test.py | 130 +++++++++++++----- 6 files changed, 204 insertions(+), 126 deletions(-) diff --git a/packages/genkit/src/genkit/_ai/_agents/_client.py b/packages/genkit/src/genkit/_ai/_agents/_client.py index 39f89a9e0..eafe6e82c 100644 --- a/packages/genkit/src/genkit/_ai/_agents/_client.py +++ b/packages/genkit/src/genkit/_ai/_agents/_client.py @@ -196,13 +196,10 @@ def __init__( name: str, ref: str | None, input_data: InputT, - metadata: dict[str, Any] | None = None, ) -> None: self.name = name self.ref = ref self.input = input_data - # What the tool passed to ``Interrupt(...)``: approval reason, amount, etc. - self.metadata = metadata def respond(self, output: OutputT) -> Part: """Tool response for ``chat.resume(respond=[...])``. @@ -407,11 +404,6 @@ def error_from_exception(e: Exception) -> GenkitError: return GenkitError(status=status, message=message, cause=e) -def interrupt_payload(part: Part) -> dict[str, Any] | None: - payload = (part.metadata or {}).get('interrupt') - return cast(dict[str, Any], payload) if isinstance(payload, dict) else None - - def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrupt[Any, Any]]: if message is None: return [] @@ -426,7 +418,6 @@ def agent_interrupts_from_message(message: Message | None) -> list[AgentInterrup name=req.name, ref=req.ref, input_data=req.input, - metadata=interrupt_payload(part), ) ) return interrupts diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 6ea273dd0..4cc00f955 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -48,6 +48,7 @@ from genkit._ai._formats._types import Formatter from genkit._ai._generate import ( CallScope, + box_from_exc, check_max_turns, define_generate_action, generate_action, @@ -88,7 +89,7 @@ from genkit._core._config_check import layer_call_config from genkit._core._dap import DapFn, DynamicActionProvider from genkit._core._environment import is_dev_environment -from genkit._core._error import ErrorReason, GenkitError +from genkit._core._error import ErrorReason, GenkitError, PublicError from genkit._core._flow import Flow from genkit._core._logger import ( REFLECTION_THREAD_NAME, @@ -1844,6 +1845,7 @@ def generate_stream( # => stop ``` """ + check_max_turns(max_turns) initial_msgs: list[Message] = [] if not isinstance(messages, str): initial_msgs = call_messages(system=system, messages=messages, prompt=prompt) @@ -1915,9 +1917,19 @@ async def _generate( raise TypeError('messages must be a list of Message; pass text with prompt=') # Before GenerateCall, whose lax int field turns True into 1. check_max_turns(max_turns) - # prompt= with resume_respond/resume_restart puts a user turn after the - # paused tool request; resolve_resume_options fails that turn - # FAILED_PRECONDITION before the model runs, same as any bad resume. + if prompt is not None and (resume_respond is not None or resume_restart is not None): + return box_from_exc( + response=ModelResponse(), + messages=call_messages(system=system, messages=messages, prompt=prompt), + exc=PublicError( + 'FAILED_PRECONDITION', + "Cannot 'resume' generation unless the previous message is a model message with at least one" + ' tool request. resume_respond/resume_restart cannot be combined with prompt=.', + reason=ErrorReason.INVALID_RESUME, + ), + caller_stopped=False, + reason=ErrorReason.INVALID_RESUME, + ) scope = CallScope(self) registry = scope.registry diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 7070d6322..7194dd3f8 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -105,6 +105,7 @@ OutputConfig, Part, as_message, + check_max_turns, chunk_for_stream, reject_config_api_key, reject_unanswered_interrupts, @@ -721,10 +722,6 @@ def augment_with_context( if context_idx >= 0: meta = user_message.content[context_idx].metadata or {} if not meta.get('pending'): - logger.warning( - 'docs= not injected: the last user message already has a context part', - docs=len(request.docs), - ) return request # Render all documents as a single formatted text string @@ -752,30 +749,6 @@ def augment_with_context( return new_req -def check_max_turns(max_turns: object) -> None: - """max_turns is a whole, non-negative count of tool rounds. - - ``True`` would pass as 1 and ``nan`` would fail deep in validation, so - both get the same INVALID_ARGUMENT as a negative count. ``3.0`` (what - dotprompt's float field carries) is fine. - """ - if max_turns is None: - return - whole = isinstance(max_turns, int) or (isinstance(max_turns, float) and max_turns.is_integer()) - if isinstance(max_turns, bool) or not whole: - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'max turns must be a whole number, got {max_turns!r}', - reason=ErrorReason.INVALID_INPUT, - ) - if cast(float, max_turns) < 0: - raise GenkitError( - status='INVALID_ARGUMENT', - message=f'max turns cannot be negative, got {max_turns}', - reason=ErrorReason.INVALID_INPUT, - ) - - def raise_if_stopped(caller_stopped: asyncio.Event | None) -> None: if caller_stopped is not None and caller_stopped.is_set(): raise GenkitError(status='CANCELLED', message='Generation aborted.') @@ -2778,29 +2751,6 @@ async def resolve_tool(registry: Registry, tool_ref: str | Tool) -> Action: return tool -def resume_precondition_message(messages: list[Message]) -> str: - """Why a resume can't answer this history, naming prompt= when that's the cause. - - ``prompt=`` with ``resume_respond``/``resume_restart`` appends a user turn - after the paused tool request, so the last message is no longer the one - the resume answers. - """ - message = ( - "Cannot 'resume' generation unless the previous message is a model message with at least one tool request." - ) - if ( - len(messages) >= 2 - and messages[-1].role == Role.USER - and messages[-2].role == Role.MODEL - and any(p.tool_request is not None for p in messages[-2].content) - ): - message += ( - ' The last message is a user turn after the paused tool request;' - ' resume_respond/resume_restart cannot be combined with prompt=.' - ) - return message - - async def resolve_resume_options( *, options: GenerateActionOptions, @@ -2819,7 +2769,10 @@ async def resolve_resume_options( if last_message is None or last_message.role != Role.MODEL or len(tool_requests) == 0: raise PublicError( 'FAILED_PRECONDITION', - resume_precondition_message(messages), + ( + "Cannot 'resume' generation unless the previous message is a model " + 'message with at least one tool request.' + ), reason=ErrorReason.INVALID_RESUME, ) @@ -2958,20 +2911,8 @@ async def resolve_resumed_tool( tool_request=tool_req_root, ) if provided_response: - # remove the 'interrupt' but leave a 'resolvedInterrupt' - metadata = dict(tool_req_root.metadata) if tool_req_root.metadata else {} - interrupt = metadata.get('interrupt') - if interrupt: - del metadata['interrupt'] return ( - Part( - tool_request=ToolRequest( - name=tool_req.name, - ref=tool_req.ref, - input=tool_req.input, - ), - metadata={**metadata, 'resolvedInterrupt': interrupt}, - ), + resolved_interrupt_part(original=tool_req_root, tool_input=tool_req.input), provided_response, ) @@ -2987,7 +2928,8 @@ async def resolve_resumed_tool( message=f'Tool {tool_req.name} not found', reason=ErrorReason.TOOL_NOT_FOUND, ) - ran_request, metadata, interrupt = restarted_tool_request(original=tool_req_root, restart=restart_trp) + restart_req = restart_trp.tool_request + assert restart_req is not None try: executed = await run_restart( tool=tool, @@ -3000,11 +2942,13 @@ async def resolve_resumed_tool( if intr is not None: # Paused again on the input it actually ran with, so the next # answer (and the history) sees the approved input. - return (interrupt_request_part(Part(tool_request=ran_request, metadata=metadata), intr), None) + metadata, _ = strip_interrupt_metadata(tool_req_root) + paused_req = ToolRequest(name=tool_req.name, ref=tool_req.ref, input=restart_req.input) + return (interrupt_request_part(Part(tool_request=paused_req, metadata=metadata), intr), None) log_dropped_failure(e, tool=tool_req.name) raise return ( - Part(tool_request=ran_request, metadata={**metadata, 'resolvedInterrupt': interrupt}), + resolved_interrupt_part(original=tool_req_root, tool_input=restart_req.input), executed, ) @@ -3100,23 +3044,28 @@ async def next_fn(p: ToolHookParams, ctx: MiddlewareContext) -> MultipartToolRes ) -def restarted_tool_request(*, original: Part, restart: Part) -> tuple[ToolRequest, dict[str, Any], object]: - """The tool request history keeps for a restart: the input the tool ran with. +def strip_interrupt_metadata(part: Part) -> tuple[dict[str, Any], object]: + """Return metadata without ``interrupt`` or ``replacedInput``, plus the interrupt payload. - ``restart(replace_input=...)`` swaps the input. History and the model's - next turn read the approved input. The original input is not recorded: - on a tool request in history, ``replacedInput`` would read as a pending - restart. Returns the request, its metadata without ``interrupt`` or - ``replacedInput``, and the interrupt payload. + On a tool request in history, ``replacedInput`` would read as a pending + restart, so both ``interrupt`` and ``replacedInput`` are cleared when an + interrupt is resolved or re-paused. """ - original_req = original.tool_request - restart_req = restart.tool_request - assert original_req is not None and restart_req is not None - metadata = dict(original.metadata) if original.metadata else {} + metadata = dict(part.metadata) if part.metadata else {} interrupt = metadata.pop('interrupt', None) metadata.pop('replacedInput', None) - ran = ToolRequest(name=original_req.name, ref=original_req.ref, input=restart_req.input) - return ran, metadata, interrupt + return metadata, interrupt + + +def resolved_interrupt_part(*, original: Part, tool_input: object) -> Part: + """Return the resolved history ToolRequest part with ``resolvedInterrupt``.""" + orig_req = original.tool_request + assert orig_req is not None + metadata, interrupt = strip_interrupt_metadata(original) + return Part( + tool_request=ToolRequest(name=orig_req.name, ref=orig_req.ref, input=tool_input), + metadata={**metadata, 'resolvedInterrupt': interrupt}, + ) def matching_restart( diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index 0cd9da8a1..c5d03c399 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -24,6 +24,7 @@ import weakref from collections.abc import Awaitable, Callable, Mapping, Sequence from dataclasses import dataclass +from numbers import Integral from pathlib import Path from typing import Any, ClassVar, Generic, NamedTuple, TypedDict, TypeVar, cast @@ -33,7 +34,7 @@ PromptInputConfig, PromptMetadata, ) -from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError +from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, field_validator from typing_extensions import Never, Self from genkit._ai import _aio @@ -82,6 +83,7 @@ OutputConfig, Part, ToolChoice, + check_max_turns, resume_options_to_resume, ) from genkit._core._registry import Registry @@ -247,6 +249,16 @@ class GenerateCall(BaseModel): model: ModelArg | Action | None = None config: Mapping[str, Any] | BaseModel | None = None + @field_validator('max_turns', mode='before') + @classmethod + def _check_max_turns(cls, v: object) -> object: + check_max_turns(v) + if isinstance(v, float) and v.is_integer(): + return int(v) + if isinstance(v, Integral) and not isinstance(v, bool): + return int(v) + return v + def with_overrides(self, opts: PromptSettings) -> Self: """Return a copy where every ``PromptSettings`` key the call passed replaces this one's. @@ -254,6 +266,13 @@ def with_overrides(self, opts: PromptSettings) -> Self: ``PromptGenerateOptions``; keys outside ``PromptSettings`` are ignored here. """ set_by_call = {k: v for k, v in opts.items() if k in PromptSettings.__optional_keys__ and v is not None} + if 'max_turns' in set_by_call: + check_max_turns(set_by_call['max_turns']) + mt = set_by_call['max_turns'] + if isinstance(mt, float) and mt.is_integer(): + set_by_call['max_turns'] = int(mt) + elif isinstance(mt, Integral) and not isinstance(mt, bool): + set_by_call['max_turns'] = int(mt) return self.model_copy(update=set_by_call) diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 01e98b290..a210c44fb 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -27,6 +27,7 @@ from dataclasses import dataclass from functools import cached_property from importlib import import_module +from numbers import Integral from typing import Any, ClassVar, Final, Generic, Literal, TypeGuard, cast, get_args from pydantic import ( @@ -973,6 +974,38 @@ def interrupts(self) -> list[Part]: return [p for p in self.tool_requests if p.metadata and p.metadata.get('interrupt')] +def check_max_turns(max_turns: object) -> None: + """Validate that ``max_turns`` is a whole, non-negative count of tool rounds. + + ``True`` would pass as 1 and ``nan`` would fail deep in validation, so + both get the same INVALID_ARGUMENT as a negative count. ``3.0`` (what + dotprompt's float field carries) and ``numbers.Integral`` values (such as + ``np.int64``) are accepted. + """ + if max_turns is None: + return + if isinstance(max_turns, bool): + whole = False + elif isinstance(max_turns, Integral): + whole = True + elif isinstance(max_turns, float): + whole = max_turns.is_integer() + else: + whole = False + if not whole: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'max turns must be a whole number, got {max_turns!r}', + reason=ErrorReason.INVALID_INPUT, + ) + if cast(float, max_turns) < 0: + raise GenkitError( + status='INVALID_ARGUMENT', + message=f'max turns cannot be negative, got {max_turns}', + reason=ErrorReason.INVALID_INPUT, + ) + + class GenerateActionOptions(GenkitModel): """Generate options with messages as list[Message] for type-safe use with ai.generate().""" @@ -990,6 +1023,12 @@ class GenerateActionOptions(GenkitModel): step_name: str | None = None use: list[MiddlewareRef] | None = None + @field_validator('max_turns', mode='before') + @classmethod + def _check_max_turns(cls, v: object) -> object: + check_max_turns(v) + return v + @field_validator('messages', mode='before') @classmethod def _wrap_messages(cls, v: object) -> object: diff --git a/packages/genkit/tests/genkit/ai/generate_loop_test.py b/packages/genkit/tests/genkit/ai/generate_loop_test.py index c900cfc37..a9cd5ae0f 100644 --- a/packages/genkit/tests/genkit/ai/generate_loop_test.py +++ b/packages/genkit/tests/genkit/ai/generate_loop_test.py @@ -5,6 +5,7 @@ """Turn-loop invariants: max_turns, restart input, system= with history, docs=, and resume with prompt=.""" +import numpy as np import pytest from genkit import ( @@ -16,10 +17,10 @@ Part, ToolContext, ) -from genkit._ai._agents._client import agent_interrupts_from_message -from genkit._ai._generate import CallScope, augment_with_context, generate_action, restarted_tool_request +from genkit._ai._generate import CallScope, augment_with_context, generate_action, resolved_interrupt_part +from genkit._core import _tool as tool_mod from genkit._core._error import ErrorReason, GenkitError -from genkit._core._model import GenerateActionOptions, ModelRequest +from genkit._core._model import GenerateActionOptions, ModelRequest, reject_unanswered_interrupts from genkit._core._typing import FinishReason, Role, ToolRequest from genkit.testing import ScriptedModel, define_scripted_model @@ -139,38 +140,18 @@ async def transfer(inp: dict, ctx: ToolContext) -> str: assert 'replacedInput' not in part.metadata -def test_restarted_tool_request_never_carries_replaced_input() -> None: - """Neither the restart part nor a stale history part can put replacedInput back on history.""" +def test_resolved_interrupt_part_strips_interrupt_and_replaced_input() -> None: + """History keeps the approved input and resolvedInterrupt, never interrupt or replacedInput.""" original = Part( tool_request=ToolRequest(name='transfer', input={'days': 7}, ref='t1'), metadata={'interrupt': {'reason': 'approve'}, 'replacedInput': {'days': 9}, 'note': 'kept'}, ) - restart = Part( - tool_request=ToolRequest(name='transfer', input={'days': 5}, ref='t1'), - metadata={'resumed': True, 'replacedInput': {'days': 7}}, - ) - - ran, metadata, interrupt = restarted_tool_request(original=original, restart=restart) - - assert ran.input == {'days': 5} - assert metadata == {'note': 'kept'} - assert interrupt == {'reason': 'approve'} - -def test_agent_interrupt_exposes_the_interrupt_payload() -> None: - message = Message( - role=Role.MODEL, - content=[ - Part( - tool_request=ToolRequest(name='transfer', input={'days': 7}, ref='t1'), - metadata={'interrupt': {'reason': 'needs approval'}}, - ) - ], - ) + resolved = resolved_interrupt_part(original=original, tool_input={'days': 5}) - [intr] = agent_interrupts_from_message(message) - - assert intr.metadata == {'reason': 'needs approval'} + assert resolved.tool_request is not None + assert resolved.tool_request.input == {'days': 5} + assert resolved.metadata == {'note': 'kept', 'resolvedInterrupt': {'reason': 'approve'}} @pytest.mark.asyncio @@ -336,11 +317,19 @@ async def test_resume_without_a_paused_tool_request_does_not_mention_prompt() -> @pytest.mark.asyncio -async def test_bare_restart_still_reads_as_resumed() -> None: - """restart() with no metadata resumes with {}; the tool must still see a resume.""" +async def test_bare_restart_still_reads_as_resumed(monkeypatch: pytest.MonkeyPatch) -> None: + """restart() with no metadata resumes with {}; the tool span still records resumed.""" ai = Genkit(model='scriptedModel') pm, _ = define_scripted_model(ai) seen: list[object] = [] + span_attrs: list[dict[str, object]] = [] + orig_set_attrs = tool_mod.set_custom_metadata_attributes + + def _record_attrs(attrs: dict[str, object]) -> None: + span_attrs.append(dict(attrs)) + orig_set_attrs(attrs) + + monkeypatch.setattr(tool_mod, 'set_custom_metadata_attributes', _record_attrs) @ai.tool(name='transfer') async def transfer(inp: dict, ctx: ToolContext) -> str: @@ -354,3 +343,82 @@ async def transfer(inp: dict, ctx: ToolContext) -> str: await ai.generate(messages=paused.messages, tools=['transfer'], resume_restart=paused.interrupts[0].restart()) assert len(seen) == 1 + assert {'resumed': {}} in span_attrs + + +@pytest.mark.asyncio +async def test_resume_with_user_turn_after_paused_tool_does_not_mention_prompt() -> None: + """History ending in a user turn after a paused tool request must not blame prompt=.""" + ai, pm, _ = _hitl_app() + pm.responses = [_transfer_request(7)] + paused = await ai.generate(prompt='book 7 days', tools=['transfer']) + calls = pm.request_count + + response = await ai.generate( + messages=[*paused.messages, Message(role=Role.USER, content=[Part.from_text('also add breakfast')])], + tools=['transfer'], + resume_restart=paused.interrupts[0].restart(), + ) + + assert response.finish_reason == FinishReason.FAILED + assert response.error is not None + assert response.error.status == 'FAILED_PRECONDITION' + assert response.error.reason is ErrorReason.INVALID_RESUME + assert 'prompt=' not in response.error.message + assert pm.request_count == calls + + +def test_reject_unanswered_interrupts_sets_invalid_resume_reason() -> None: + paused = Part( + tool_request=ToolRequest(name='transfer', input={'days': 7}, ref='t1'), + metadata={'interrupt': {'reason': 'approve'}}, + ) + + with pytest.raises(GenkitError) as restart_err: + reject_unanswered_interrupts(restart=[paused]) + assert restart_err.value.status == 'INVALID_ARGUMENT' + assert restart_err.value.reason is ErrorReason.INVALID_RESUME + + with pytest.raises(GenkitError) as respond_err: + reject_unanswered_interrupts(respond=[paused]) + assert respond_err.value.status == 'INVALID_ARGUMENT' + assert respond_err.value.reason is ErrorReason.INVALID_RESUME + + +@pytest.mark.asyncio +@pytest.mark.parametrize('bad', [True, False, 2.5]) +async def test_max_turns_rejects_bool_and_fraction_across_entry_points(bad: object) -> None: + from genkit._ai._agents._base import define_agent + + ai = Genkit(model='scriptedModel') + define_scripted_model(ai) + + with pytest.raises(GenkitError) as gen_err: + ai.generate_stream(prompt='hi', max_turns=bad) # type: ignore[arg-type] + assert gen_err.value.status == 'INVALID_ARGUMENT' + + with pytest.raises(GenkitError) as prompt_err: + ai.define_prompt(name=f'p_{bad}', prompt='hi', max_turns=bad) # type: ignore[arg-type] + assert prompt_err.value.status == 'INVALID_ARGUMENT' + + with pytest.raises(GenkitError) as agent_err: + define_agent(ai, name=f'a_{bad}', max_turns=bad) # type: ignore[arg-type] + assert agent_err.value.status == 'INVALID_ARGUMENT' + + with pytest.raises(GenkitError) as opts_err: + GenerateActionOptions(messages=[], max_turns=bad) # type: ignore[arg-type] + assert opts_err.value.status == 'INVALID_ARGUMENT' + + +@pytest.mark.asyncio +async def test_max_turns_accepts_numpy_integral() -> None: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [_answers('ok'), _answers('ok')] + + res = await ai.generate(prompt='hi', max_turns=np.int64(3)) # type: ignore[arg-type] + assert res.text == 'ok' + + prompt = ai.define_prompt(name='np_turns', prompt='hi', max_turns=np.int64(3)) # type: ignore[arg-type] + prompt_res = await prompt() + assert prompt_res.text == 'ok'