Skip to content

fix(py): isolate .prompt loader errors, honor output.constrained, and serialize NaN/Infinity as null - #85

Merged
huangjeff5 merged 5 commits into
mainfrom
fix/py-1.0-pr3d-prompt-loader-sse
Nov 16, 2026
Merged

huangjeff5 merged 5 commits into
mainfrom
fix/py-1.0-pr3d-prompt-loader-sse

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

A syntax error in one .prompt file no longer drops the rest of its folder, frontmatter output.constrained reaches the model, and non-finite floats in flow results serialize as null instead of failing the request.

# --- BEFORE ---
# 1. One broken .prompt or partial ended the folder walk: the folder-level
#    handler logged it, then skipped every later file in that folder and all
#    of its subfolders. Startup continued with those prompts missing.
ai = Genkit(prompt_dir='./prompts')
# => ERROR Error loading prompts from ./prompts (yaml.parser.ParserError ...)
# => prompts after a_broken.prompt and everything under ./prompts/sub/ unregistered

# 2. Frontmatter `constrained: false` was ignored; a schema always forced native JSON mode
# ---
# output:
#   schema: Recipe
#   constrained: false
# ---
opts = await ai.prompt('recipe').render({'dish': 'tartine'})
print(opts.output.constrained)
# => True

# 3. Non-finite floats in a flow result failed the request
@ai.flow()
async def score_dish(dish: str) -> dict[str, float]:
    return {'z_score': float('nan')}

result_json(await score_dish('tartine'))
# => ValueError: Out of range float values are not JSON compliant: nan
#    (to_sse sent {"error":{"message":"Internal Error","status":"INTERNAL"}})


# --- AFTER ---
# 1. The broken file is logged at ERROR with its path and traceback; siblings and subfolders load
ai = Genkit(prompt_dir='./prompts')
# => ERROR Failed to load prompt file ./prompts/a_broken.prompt
#    Traceback (most recent call last): ...

# 2. Frontmatter `constrained` reaches the request
opts = await ai.prompt('recipe').render({'dish': 'tartine'})
print(opts.output.constrained)
# => False

# 3. NaN and Infinity go out as null over JSON and SSE
print(result_json(await score_dish('tartine')))
# => {"result":{"z_score":null}}

Main Changes

  • Isolate .prompt load failures to the file: Previously, one try wrapped the whole folder walk, so the first bad prompt or partial ended it. Later files in that folder and all its subfolders were skipped, and the log named the folder, not the file. Each file now has its own try, logged at ERROR with the file path and traceback. Only read and frontmatter errors surface here; templates compile on first use, so template errors surface at render.
  • Honor frontmatter output.constrained; an explicit content type beats the format's: Previously, load_prompt set output_constrained=True whenever output.schema was present, so constrained: false was dropped. Frontmatter constrained now wins; a schema with no setting still asks for native JSON mode. Frontmatter contentType is forwarded the same as define_prompt(output_content_type=...). apply_format used to replace any explicit content type with the format's own (json → application/json), so it only reached the model with no format set. It now fills in the format's value only when the caller didn't set one, the same rule constrained already followed. format stays format-owned, so a custom format like cited-json still maps onto wire format json.
  • Serialize NaN and Infinity as null in genkit.web: Previously, result_json and to_sse encoded with allow_nan=False and no fallback, so a non-finite float in a flow result raised (HTTP 500 / INTERNAL error frame). to_jsonable_python(..., inf_nan_mode='null') now emits null, the same as tool outputs and model messages already do (mode='json').
  • Keep every dot after the name in the variant: Previously, scorer.v2.1.prompt split on every . and registered variant v2, dropping .1. The name splits on the first . only, so the variant is v2.1.
  • Strip partial frontmatter only on delimiter lines: Previously, a partial starting with --- had everything up to the next --- anywhere in the file removed, including a Markdown divider in the body. Both delimiters must now be lines of their own.

Breaking changes

  • Variant names: x.v2.1.prompt registers variant v2.1, not v2. Lookups with variant='v2' for such a file now miss.
  • Frontmatter: output.constrained: false with a schema now sends an unconstrained request, with the schema instructions injected into the prompt. Previously it was silently constrained.
  • Content type: an explicit output_content_type (or frontmatter contentType) now reaches the model even when a format is set. Before, the format's content type replaced it. Gemini keys JSON mode on format == 'json' or content_type == 'application/json', so a mismatched pair like output_format='text', output_content_type='application/json' now turns JSON mode on.
  • Partial frontmatter: --- must be on its own line to open or close frontmatter in a partial. A partial that relied on the old substring match keeps more of its text.
  • Wire format: result_json and to_sse emit null for NaN, Infinity and -Infinity instead of raising or sending an INTERNAL error frame.

Cross-SDK

  • Per-file isolation: matches Go (slog.Error("failed to load prompt file, skipping it", ...)). JS has no per-file catch in loadPromptFolderRecursively.
  • Variant split: matches Go (strings.Cut(base, ".")). JS still takes name.split('.')[1], so x.v2.1.prompt is v2 there.
  • Explicit content type wins: matches JS applyFormat ({...resolvedFormat.config, ...outRequest.output}). Go has no caller-facing output content type option.
  • Frontmatter constrained / contentType: neither JS nor Go reads these from frontmatter today. A .prompt with constrained: false behaves differently in Python than in JS/Go until they follow.
  • NaN / Infinity: matches JS JSON.stringify (null). Go's encoding/json returns an error for non-finite floats.

@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-pr3c-action-context-ai-run branch from a44f8d2 to 4376044 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3d-prompt-loader-sse branch from 7239c1a to f581401 Compare November 11, 2026 06:22
@huangjeff5
huangjeff5 added this pull request to stack #89 November 11, 2026 06:23
@huangjeff5 huangjeff5 changed the title fix(py): isolate .prompt loader errors, honor output.constrained, and unbox FAILED responses in to_sse fix(py): isolate .prompt loader errors, honor output.constrained, and serialize NaN/Infinity as null Nov 11, 2026
@huangjeff5
huangjeff5 removed this pull request from stack #89 November 11, 2026 18:06
@huangjeff5
huangjeff5 changed the base branch from fix/py-1.0-pr3c-action-context-ai-run to main November 11, 2026 18:37
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3d-prompt-loader-sse branch from 1ac7d23 to b2313a4 Compare November 11, 2026 18:38
@huangjeff5
huangjeff5 force-pushed the fix/py-1.0-pr3d-prompt-loader-sse branch from b2313a4 to b5ca24e Compare November 12, 2026 07:27

@hilariie hilariie left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The description doesn't match the diff in a few places. The SSE unboxing bullet is already on main, the old loader didn't abort startup (it silently skipped the rest of the folder and its subfolders), the log is an error rather than a warning, example 2 needs await and opts.output.constrained, and Go sends an error for NaN rather than null. It's also missing the Breaking changes and Cross-SDK sections: the variant split changes x.v2.1.prompt from variant v2 to v2.1, and the SSE format and frontmatter both change.

… the model request

Log per-file loader failures with logger.exception so the exception type and
traceback survive. Loader tests now assert on the request the model receives:
constrained survives apply_format, contentType reaches the model when no format
claims it. Move the flow-returns-FAILED SSE case into to_sse_test.py and drop
sse_failed_response_test.py; the rest was already covered.
apply_format replaced any caller content type with the format's own, so
output_content_type (and frontmatter contentType) only reached the model when no
format was set. The format now fills it in only when the caller left it unset,
the same rule constrained already follows and JS applyFormat uses.
@huangjeff5
huangjeff5 merged commit 765c560 into main Nov 16, 2026
20 of 21 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-1.0-pr3d-prompt-loader-sse branch November 16, 2026 21:21
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