Repository navigation
fix(py): isolate .prompt loader errors, honor output.constrained, and serialize NaN/Infinity as null #85
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
fix(py): isolate .prompt loader errors, honor output.constrained, and serialize NaN/Infinity as null #85
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
de777cc
fix(py): isolate .prompt loader errors and unbox FAILED ModelResponse…
huangjeff5 b5ca24e
fix(py): unbox failures in to_sse only for generate streams, not flow…
huangjeff5 0a40a8c
fix(py): drop StreamResponse tuple-unpacking guard
huangjeff5 a31b37e
fix(py): keep tracebacks for bad .prompt files and pin constrained on…
huangjeff5 305b186
fix(py): let an explicit output content type win over the format's
huangjeff5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| #!/usr/bin/env python3 | ||
| # | ||
| # Copyright 2026 Google LLC | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| """Dotprompt file loading: frontmatter output settings and per-file isolation.""" | ||
|
|
||
| import tempfile | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
|
|
||
| from genkit import Genkit, Message, ModelResponse, Part | ||
| from genkit._ai._prompt import strip_frontmatter | ||
| from genkit._core._typing import ConstrainedSupport, Role | ||
| from genkit.model import ModelContext, ModelInfo, ModelRequest, ModelSupports | ||
| from genkit.testing import define_scripted_model | ||
|
|
||
| _SCHEMA_PROMPT = """--- | ||
| model: menuModel | ||
| output: | ||
| schema: | ||
| title: string | ||
| constrained: {constrained} | ||
| --- | ||
| Suggest a dish. | ||
| """ | ||
|
|
||
|
|
||
| def _define_menu_model(ai: Genkit) -> list[ModelRequest]: | ||
| """A model that supports native JSON mode and records what it receives.""" | ||
| seen: list[ModelRequest] = [] | ||
|
|
||
| async def menu_model(request: ModelRequest, ctx: ModelContext) -> ModelResponse: | ||
| seen.append(request) | ||
| return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{"title": "Tartine"}')])) | ||
|
|
||
| ai.define_model( | ||
| name='menuModel', fn=menu_model, info=ModelInfo(supports=ModelSupports(constrained=ConstrainedSupport.ALL)) | ||
| ) | ||
| return seen | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize('constrained', [False, True]) | ||
| async def test_prompt_file_output_constrained_reaches_the_model(constrained: bool) -> None: | ||
| """`constrained: false` in frontmatter turns native JSON mode off on the model request.""" | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| text = _SCHEMA_PROMPT.format(constrained=str(constrained).lower()) | ||
| (Path(tmp_dir) / 'dish.prompt').write_text(text) | ||
| ai = Genkit(prompt_dir=tmp_dir) | ||
| seen = _define_menu_model(ai) | ||
|
|
||
| await ai.prompt('dish')() | ||
|
|
||
| assert seen[0].output is not None | ||
| assert seen[0].output.constrained is constrained | ||
| assert seen[0].output.schema is not None | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_prompt_file_schema_without_constrained_defaults_to_native_json() -> None: | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| (Path(tmp_dir) / 'dish.prompt').write_text( | ||
| '---\nmodel: menuModel\noutput:\n schema:\n title: string\n---\nSuggest a dish.\n' | ||
| ) | ||
| ai = Genkit(prompt_dir=tmp_dir) | ||
| seen = _define_menu_model(ai) | ||
|
|
||
| await ai.prompt('dish')() | ||
|
|
||
| assert seen[0].output is not None | ||
| assert seen[0].output.constrained is True | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| @pytest.mark.parametrize( | ||
| ('output', 'expected'), | ||
| [ | ||
| ('contentType: text/markdown', 'text/markdown'), | ||
| ( | ||
| 'schema:\n title: string\n contentType: application/vnd.restaurant+json', | ||
| 'application/vnd.restaurant+json', | ||
| ), | ||
| ], | ||
| ids=['no_format', 'with_schema'], | ||
| ) | ||
| async def test_prompt_file_content_type_reaches_the_model(output: str, expected: str) -> None: | ||
| """Frontmatter contentType is what the model sees, even when the json format has its own.""" | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| (Path(tmp_dir) / 'menu.prompt').write_text( | ||
| f'---\nmodel: menuModel\noutput:\n {output}\n---\nWrite the menu.\n' | ||
| ) | ||
| ai = Genkit(prompt_dir=tmp_dir) | ||
| seen = _define_menu_model(ai) | ||
|
|
||
| await ai.prompt('menu')() | ||
|
|
||
| assert seen[0].output is not None | ||
| assert seen[0].output.content_type == expected | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_one_bad_prompt_file_does_not_drop_its_siblings(capfd: pytest.CaptureFixture[str]) -> None: | ||
| """A YAML typo in one file is logged with its path and traceback; the rest of the folder loads.""" | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| root = Path(tmp_dir) | ||
| (root / 'a_broken.prompt').write_text('---\ndescription: Note: always greet\n bad: [\n---\nHi\n') | ||
| (root / 'b_greet.prompt').write_text('---\nmodel: scriptedModel\n---\nHello\n') | ||
| (root / 'sub').mkdir() | ||
| (root / 'sub' / 'menu.prompt').write_text('---\nmodel: scriptedModel\n---\nMenu\n') | ||
|
|
||
| ai = Genkit(prompt_dir=tmp_dir, model='scriptedModel') | ||
| define_scripted_model(ai) | ||
|
|
||
| assert (await ai.prompt('b_greet').render()).messages | ||
| assert (await ai.prompt('sub/menu').render()).messages | ||
| out, err = capfd.readouterr() | ||
| assert 'a_broken.prompt' in out + err | ||
| assert 'Traceback' in out + err | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_prompt_variant_keeps_every_dot_after_the_name() -> None: | ||
| with tempfile.TemporaryDirectory() as tmp_dir: | ||
| (Path(tmp_dir) / 'scorer.v2.1.prompt').write_text('---\nmodel: scriptedModel\n---\nScore it.\n') | ||
| ai = Genkit(prompt_dir=tmp_dir, model='scriptedModel') | ||
| define_scripted_model(ai) | ||
|
|
||
| rendered = await ai.prompt('scorer', variant='v2.1').render() | ||
|
|
||
| assert rendered.messages | ||
|
|
||
|
|
||
| def test_strip_frontmatter_keeps_markdown_dividers_in_the_body() -> None: | ||
| assert strip_frontmatter('---\nname: x\n---\nIntro\n\n---\n\nMore') == 'Intro\n\n---\n\nMore' | ||
| assert strip_frontmatter('Intro\n\n---\n\nMore') == 'Intro\n\n---\n\nMore' | ||
| assert strip_frontmatter('---- not a delimiter ---\nbody') == '---- not a delimiter ---\nbody' |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.