Skip to content

fix(py): enforce generate invariants for system=, docs= media, restart input, and max_turns - #83

Merged
huangjeff5 merged 2 commits into
mainfrom
fix/py-1.0-pr3b-generate-loop-invariants
Nov 13, 2026
Merged

huangjeff5 merged 2 commits into
mainfrom
fix/py-1.0-pr3b-generate-loop-invariants

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Prompt sanitization keeps vector embeddings and database ACLs out of model prompts, system= messages with history are prepended instead of clobbered, human-in-the-loop restarts record the approved input, and max_turns is validated up front.

# --- BEFORE ---
# 1. docs= leaked internal vector embeddings, ACLs, and metadata into provider prompt
doc = Document.from_text('menu specials', metadata={'acl': ['admin'], 'embedding': [0.12, -0.45]})
await ai.generate(prompt='Summarize', docs=[doc])
# => Prompt text contained:
#    - [0]: menu specials
#      metadata: {'acl': ['admin'], 'embedding': [0.12, -0.45]}

# 2. Approving modified tool input in human-in-the-loop kept unapproved input in history
paused = await ai.generate(prompt='book 7 days', tools=['booking_tool'])
done = await ai.generate(
    messages=paused.messages,
    tools=['booking_tool'],
    resume_restart=paused.interrupts[0].restart(replace_input={'days': 5}),
)
done.messages[1].content[0].tool_request.input
# => {'days': 7}  (unapproved input remained in history)

# 3. system= with messages= clobbered or mishandled existing system turns
await ai.generate(messages=[Message.system('old instruction')], system='new instruction')
# => Did not prepend new instruction cleanly ahead of history

# 4. Combining prompt= with resume failed deep in generation with an obscure message-role error
await ai.generate(messages=paused.messages, prompt='add breakfast', resume_restart=paused.interrupts[0].restart())
# => Internal message-role sequence error during turn loop

# 5. max_turns allowed True (evaluated as 1) and crashed on non-integers
await ai.generate(prompt='hi', max_turns=True)
# => Stopped after 1 tool turn instead of rejecting invalid type


# --- AFTER ---
# 1. docs= formats text citation lines; ACLs, embeddings, and tenant IDs stay out of prompt
doc = Document.from_text('menu specials', metadata={'acl': ['admin'], 'embedding': [0.12, -0.45]})
res = await ai.generate(prompt='Summarize', docs=[doc])
# => Prompt text contains strictly:
#    - [0]: menu specials

# 2. History and next turn carry the approved input the tool actually ran with
paused = await ai.generate(prompt='book 7 days', tools=['booking_tool'])
done = await ai.generate(
    messages=paused.messages,
    tools=['booking_tool'],
    resume_restart=paused.interrupts[0].restart(replace_input={'days': 5}),
)
print(done.messages[1].content[0].tool_request.input)
# => {'days': 5}

# 3. system= prepends cleanly ahead of conversation history
res = await ai.generate(
    messages=[Message.user('hi')],
    system='You are a restaurant host.',
)
print([m.text for m in res.request.messages])
# => ['You are a restaurant host.', 'hi']

# 4. Invalid resume combinations fail up front before the model runs
res = await ai.generate(
    messages=paused.messages,
    prompt='add breakfast',
    tools=['booking_tool'],
    resume_restart=paused.interrupts[0].restart(),
)
print(res.finish_reason, res.error.status, res.error.reason)
# => failed FAILED_PRECONDITION INVALID_RESUME
print(res.error.message)
# => Cannot 'resume' generation unless the previous message is a model message with at least one tool request.
#    The last message is a user turn after the paused tool request;
#    resume_respond/resume_restart cannot be combined with prompt=.

# 5. max_turns rejects bool, nan, inf, and fractional numbers up front
await ai.generate(prompt='hi', max_turns=True)
# => GenkitError: INVALID_ARGUMENT: max turns must be a whole number, got True

Main Changes

  • Internal document metadata stays out of prompts: Previously, injecting docs=[Document(...)] into ai.generate() allowed internal document metadata (vector embeddings, database ACLs, tenant IDs) to bleed into provider prompt text. We now format documents strictly as - [ref]: <text> using only ref/id and text content, preventing sensitive backend metadata from leaking to model providers.
  • Human-in-the-loop restarts record the approved input: Previously, when an approver overrode tool arguments via restart(replace_input=...), conversation history and the next model turn retained the original, unapproved request. We now rewrite the stored tool request to the approved input and strip replacedInput so subsequent turns do not misinterpret it as an unhandled interrupt.
  • system= prepends cleanly to existing history: Previously, passing both system='...' and messages=[...] clobbered or mishandled existing system messages in conversation history. We now prepend the new system message to the front of history, matching Go and JS behavior. Passing system='' is a no-op.
  • Fail fast on invalid resume preconditions: Previously, passing prompt= alongside resume_respond or resume_restart failed deep in generation with an obscure message-role error because prompt= appends a user turn after the paused tool request. We now fail immediately before calling the model with FAILED_PRECONDITION and INVALID_RESUME, explicitly naming prompt= in the error message. Unanswered interrupts passed to reject_unanswered_interrupts also carry reason=ErrorReason.INVALID_RESUME.
  • Whole-number validation for max_turns: Previously, the check only validated max_turns < 0, so Python's isinstance(True, int) caused max_turns=True to run as 1 tool turn, while nan and 2.5 caused internal runtime errors. We now validate that max_turns is a non-negative whole number, while continuing to accept whole floats (3.0) loaded from .prompt files.

@huangjeff5
huangjeff5 added this pull request to stack #88 November 11, 2026 02:37
@huangjeff5
huangjeff5 removed this pull request from stack #88 November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3b-generate-loop-invariants branch from 92d4a2d to 1b4c470 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3b-generate-loop-invariants branch from 1b4c470 to 0e716c1 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 added this pull request to stack #104 November 11, 2026 19:43
@huangjeff5
huangjeff5 requested a review from apascal07 November 12, 2026 06:04
…t 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.
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3b-generate-loop-invariants branch from 0e716c1 to c387d9d Compare November 12, 2026 06:37
@huangjeff5
huangjeff5 removed this pull request from stack #104 November 12, 2026 06:39
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr3-generation-loop to main November 12, 2026 06:40
@huangjeff5
huangjeff5 added this pull request to stack #118 November 12, 2026 07:32
Comment thread packages/genkit/src/genkit/_ai/_aio.py Resolved
@huangjeff5
huangjeff5 merged commit 5b0e25a into main Nov 13, 2026
21 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr3b-generate-loop-invariants branch November 13, 2026 03:18
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.

2 participants