diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 857c9d2f5..71c097275 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -2255,8 +2255,12 @@ def apply_format( out_request.output.constrained = constrained - if format_def.config.content_type is not None: + # The format fills in a content type only when the caller didn't set one, + # the same as `constrained` above and JS applyFormat. + if out_request.output.content_type is None: out_request.output.content_type = format_def.config.content_type + # `format` stays format-owned: a custom format (say `cited-json`) maps onto + # the wire format (`json`) that models and the instruction rule key on. if format_def.config.format is not None: out_request.output.format = format_def.config.format diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index 0cd9da8a1..f1a319062 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -21,6 +21,7 @@ import asyncio import os +import re import weakref from collections.abc import Awaitable, Callable, Mapping, Sequence from dataclasses import dataclass @@ -1548,6 +1549,10 @@ def _transform_prompt_metadata( if isinstance(output, dict) and 'instructions' in output else (raw_output.get('instructions') if isinstance(raw_output, dict) else None) ), + # Same raw fallback: frontmatter `constrained: false` and + # `contentType` must reach the request. + 'constrained': _output_key(output, raw_output, 'constrained'), + 'contentType': _output_key(output, raw_output, 'contentType'), }, 'input': { 'default': input_cfg.get('default') if isinstance(input_cfg, dict) else None, @@ -1562,6 +1567,23 @@ def _transform_prompt_metadata( } +def file_constrained(output: dict[str, Any]) -> bool | None: + """Frontmatter `constrained:` wins; a schema with no setting asks for native JSON mode.""" + constrained = output.get('constrained') + if isinstance(constrained, bool): + return constrained + return True if output.get('jsonSchema') else None + + +def _output_key(output: object, raw_output: object, key: str) -> Any: # noqa: ANN401 + for source in (output, raw_output): + if isinstance(source, dict): + value = cast(dict[str, Any], source).get(key) + if value is not None: + return value + return None + + def load_prompt(ai: _aio.Genkit, path: Path, filename: str, prefix: str = '', ns: str = '') -> None: """Load a .prompt file and register it as a lazy-loaded prompt.""" registry = ai._registry @@ -1573,9 +1595,8 @@ def load_prompt(ai: _aio.Genkit, path: Path, filename: str, prefix: str = '', ns base_name = filename.removesuffix('.prompt') variant: str | None = None if '.' in base_name: - parts = base_name.split('.') - base_name = parts[0] - variant = parts[1] + # `scorer.v2.1.prompt` is prompt `scorer`, variant `v2.1`. + base_name, variant = base_name.split('.', 1) name = f'{prefix}{base_name}' file_path = path / (prefix.rstrip('/') + '/' + filename if prefix else filename) @@ -1619,7 +1640,8 @@ async def create_prompt_from_file() -> Prompt[Any, Any]: input_schema=metadata.get('input', {}).get('jsonSchema'), input_default=file_default if isinstance(file_default, dict) else None, output_schema=output_schema, - output_constrained=True if metadata.get('output', {}).get('jsonSchema') else None, + output_constrained=file_constrained(metadata.get('output', {})), + output_content_type=metadata.get('output', {}).get('contentType'), output_format=metadata.get('output', {}).get('format'), output_instructions=metadata.get('output', {}).get('instructions'), messages=metadata.get('messages'), @@ -1715,7 +1737,13 @@ def load_prompt_folder_recursively( if not entry.is_file() or not entry.name.endswith('.prompt'): continue if not entry.name.startswith('_'): - load_prompt(ai, dir_path, entry.name, prefix, ns) + # One bad file (unreadable, bad frontmatter) must not take its + # siblings and subdirectories down with it. Templates compile + # on first use, so template errors surface there, not here. + try: + load_prompt(ai, dir_path, entry.name, prefix, ns) + except Exception: # noqa: BLE001 - logged with the file, siblings keep loading + logger.exception(f'Failed to load prompt file {entry.path}') continue short_name = entry.name[1:-7] # Remove "_" prefix and ".prompt" suffix @@ -1729,14 +1757,12 @@ def load_prompt_folder_recursively( else: names.append(short_name) - with Path(entry.path).open(encoding='utf-8') as f: - source = f.read() - - # Strip frontmatter if present - if source.startswith('---'): - end_frontmatter = source.find('---', 3) - if end_frontmatter != -1: - source = source[end_frontmatter + 3 :].strip() + try: + with Path(entry.path).open(encoding='utf-8') as f: + source = strip_frontmatter(f.read()) + except Exception: # noqa: BLE001 - logged with the file, siblings keep loading + logger.exception(f'Failed to load partial file {entry.path}') + continue for name in names: define_partial(ai._registry, name, source) @@ -1751,6 +1777,21 @@ def load_prompt_folder_recursively( logger.exception(f'Error loading prompts from {full_path}', exc_info=e) +_FRONTMATTER = re.compile(r'\A---[ \t]*\r?\n(?:.*?\r?\n)?---[ \t]*(?:\r?\n|\Z)', re.DOTALL) + + +def strip_frontmatter(source: str) -> str: + """Drop a leading `---` frontmatter block; `---` lines in the body stay. + + Both delimiters must be lines of their own, so a Markdown divider in a + partial without frontmatter is template text, not a delimiter. + """ + match = _FRONTMATTER.match(source) + if match is None: + return source + return source[match.end() :].strip() + + def load_prompt_folder(ai: _aio.Genkit, dir_path: str | Path = './prompts', ns: str = '') -> None: """Load all prompt files from a directory. @@ -1773,7 +1814,7 @@ def load_prompt_folder(ai: _aio.Genkit, dir_path: str | Path = './prompts', ns: return load_prompt_folder_recursively(ai, path, ns, '') - logger.info(f'Loaded prompts from directory: {path}') + logger.debug(f'Loaded prompts from directory: {path}') async def lookup_prompt(registry: Registry, name: str, variant: str | None = None) -> Prompt[Any, Any]: diff --git a/packages/genkit/src/genkit/web/_sse.py b/packages/genkit/src/genkit/web/_sse.py index ae55665e8..b8dc01003 100644 --- a/packages/genkit/src/genkit/web/_sse.py +++ b/packages/genkit/src/genkit/web/_sse.py @@ -72,7 +72,9 @@ def _frame_value(obj: object) -> object: # sees it. Apply the same rule here: only a PublicError's text leaves. if isinstance(obj, (AgentOutput, SessionSnapshot)) and obj.error is not None: obj = obj.model_copy(update={'error': client_safe_failure(obj.error)}) - return to_jsonable_python(obj, by_alias=True, exclude_none=True) + # NaN/Infinity go out as null, the same as tool outputs and model + # messages (mode='json'), instead of crashing allow_nan=False with a 500. + return to_jsonable_python(obj, by_alias=True, exclude_none=True, inf_nan_mode='null') def _dumps(value: object) -> str: diff --git a/packages/genkit/tests/genkit/ai/formats/format_instructions_test.py b/packages/genkit/tests/genkit/ai/formats/format_instructions_test.py index 483b3b84c..64a24ab15 100644 --- a/packages/genkit/tests/genkit/ai/formats/format_instructions_test.py +++ b/packages/genkit/tests/genkit/ai/formats/format_instructions_test.py @@ -198,3 +198,23 @@ async def test_caller_constrained_false_wins_over_model_support() -> None: assert seen[-1].output is not None assert seen[-1].output.constrained is False assert _schema_in_prompt(seen[-1]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('content_type', 'expected'), + [ + ('application/vnd.restaurant+json', 'application/vnd.restaurant+json'), + (None, 'application/json'), + ], +) +async def test_caller_content_type_wins_over_the_format_default(content_type: str | None, expected: str) -> None: + """An explicit output_content_type reaches the model; without one, the format's value does.""" + ai = Genkit() + seen = _define_menu_model(ai, 'menuModel', ConstrainedSupport.ALL) + + await ai.generate(model='menuModel', prompt='Suggest a dish.', output_schema=Dish, output_content_type=content_type) + + assert seen[-1].output is not None + assert seen[-1].output.format == 'json' + assert seen[-1].output.content_type == expected diff --git a/packages/genkit/tests/genkit/ai/prompt_loader_test.py b/packages/genkit/tests/genkit/ai/prompt_loader_test.py new file mode 100644 index 000000000..32b127579 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/prompt_loader_test.py @@ -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' diff --git a/packages/genkit/tests/genkit/ai/to_sse_test.py b/packages/genkit/tests/genkit/ai/to_sse_test.py index 62826168c..307db707c 100644 --- a/packages/genkit/tests/genkit/ai/to_sse_test.py +++ b/packages/genkit/tests/genkit/ai/to_sse_test.py @@ -518,6 +518,23 @@ async def test_prompt_stream_to_sse_frames_chunks_and_result() -> None: assert frames[2]['result']['message']['content'] == [{'text': 'Smoked Salmon'}] +@pytest.mark.asyncio +async def test_flow_returning_a_failed_model_response_sends_it_as_the_result() -> None: + """A flow's return value is data: a FAILED ModelResponse goes out as `result`, same as over JSON.""" + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [] # The scripted model raises when it runs out of responses. + + @ai.flow() + async def suggest_dish(order: str) -> ModelResponse: + return await ai.generate(prompt=order) + + lines = await _lines(to_sse(suggest_dish.stream('tartine'))) + + assert len(lines) == 1 + assert json.loads(lines[0].removeprefix('data: '))['result']['finishReason'] == 'failed' + + @pytest.mark.asyncio async def test_generate_stream_to_sse_public_error_details_keep_failure_immutable( caplog: pytest.LogCaptureFixture, diff --git a/packages/genkit/tests/genkit/core/web_test.py b/packages/genkit/tests/genkit/core/web_test.py index b4a0638bd..6485d842d 100644 --- a/packages/genkit/tests/genkit/core/web_test.py +++ b/packages/genkit/tests/genkit/core/web_test.py @@ -17,7 +17,6 @@ """Tests for serving flows over HTTP with genkit.web.""" import datetime -import logging import uuid import pytest @@ -231,13 +230,9 @@ async def daily_special(ctx: FlowContext[str]) -> str: @pytest.mark.asyncio @pytest.mark.parametrize('bad_float', [float('nan'), float('inf'), float('-inf')]) -async def test_web_encoders_reject_non_finite_floats( - bad_float: float, - caplog: pytest.LogCaptureFixture, -) -> None: - """Out-of-range floats raise ValueError in result_json and frame as a redacted 500 error in to_sse.""" - with pytest.raises(ValueError, match='Out of range float values are not JSON compliant'): - result_json(bad_float) +async def test_web_encoders_send_non_finite_floats_as_null(bad_float: float) -> None: + """Out-of-range floats go out as null, like tool outputs and JS JSON.stringify, not a 500.""" + assert result_json(bad_float) == '{"result":null}' ai = Genkit() @@ -245,10 +240,6 @@ async def test_web_encoders_reject_non_finite_floats( async def compute_score() -> float: return bad_float - with caplog.at_level(logging.ERROR): - lines = [line async for line in to_sse(compute_score.stream())] + lines = [line async for line in to_sse(compute_score.stream())] - assert lines == ['data: {"error":{"message":"Internal Error","status":"INTERNAL"}}\n\n'] - assert [(r.levelname, r.getMessage(), r.exc_info is not None) for r in caplog.records] == [ - ('ERROR', "served action 'compute_score' stream failed", True), - ] + assert lines == ['data: {"result":null}\n\n']