diff --git a/packages/genkit/src/genkit/_ai/_formats/_array.py b/packages/genkit/src/genkit/_ai/_formats/_array.py index cc3d865fc..deceec582 100644 --- a/packages/genkit/src/genkit/_ai/_formats/_array.py +++ b/packages/genkit/src/genkit/_ai/_formats/_array.py @@ -133,8 +133,10 @@ def chunk_parser(chunk: ModelResponseChunk) -> list[object]: {json.dumps(resolved_schema, indent=2)} ``` """ - return FormatHandler( + handler = FormatHandler( chunk_parser=chunk_parser, message_parser=message_parser, instructions=instructions, ) + handler._streams_items = True + return handler diff --git a/packages/genkit/src/genkit/_ai/_formats/_jsonl.py b/packages/genkit/src/genkit/_ai/_formats/_jsonl.py index 481ec395e..d2e8852e8 100644 --- a/packages/genkit/src/genkit/_ai/_formats/_jsonl.py +++ b/packages/genkit/src/genkit/_ai/_formats/_jsonl.py @@ -147,8 +147,10 @@ def chunk_parser(chunk: ModelResponseChunk) -> list[object]: 'conforming to the following schema:\n\n' f'```\n{json.dumps(resolved_schema["items"], indent=2)}\n```\n' ) - return FormatHandler( + handler = FormatHandler( chunk_parser=chunk_parser, message_parser=message_parser, instructions=instructions, ) + handler._streams_items = True + return handler diff --git a/packages/genkit/src/genkit/_ai/_formats/_types.py b/packages/genkit/src/genkit/_ai/_formats/_types.py index 7f7bf8bb0..fac61c685 100644 --- a/packages/genkit/src/genkit/_ai/_formats/_types.py +++ b/packages/genkit/src/genkit/_ai/_formats/_types.py @@ -72,6 +72,7 @@ def __init__( instructions: Text appended to the prompt, or None for no instructions. """ self.instructions: str | None = instructions + self._streams_items: bool = False self.__message_parser = message_parser self.__chunk_parser = chunk_parser diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 0bc3ec25a..6b9f3acc0 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -29,7 +29,7 @@ from dataclasses import dataclass from typing import Any, TypeVar, cast -from pydantic import BaseModel, ValidationError +from pydantic import ValidationError from genkit._ai import _aio from genkit._ai._background_model import ensure_model_operation @@ -971,7 +971,7 @@ def __init__( self, message_index: int, formatter: FormatHandler[Any, Any] | None, - schema_type: type[BaseModel] | None = None, + schema_type: Any = None, # noqa: ANN401 ) -> None: self.message_index = message_index self.formatter = formatter @@ -2022,7 +2022,7 @@ def check_handoff(params: ModelHookParams, mw: MiddlewareDef) -> None: parse = formatter.parse_message response._message_parser = lambda msg: parse(msg) schema_type = options.output.schema_type if options.output else None - if schema_type: + if schema_type is not None: response._schema_type = schema_type return response @@ -2238,7 +2238,7 @@ def stamp_output( if formatter and response._message_parser is None: parse = formatter.parse_message response._message_parser = lambda msg: parse(msg) - if out and out.schema_type: + if out and out.schema_type is not None: response._schema_type = out.schema_type response._assert_valid_schema() return response diff --git a/packages/genkit/src/genkit/_ai/_prompt.py b/packages/genkit/src/genkit/_ai/_prompt.py index b99bcb594..b7a642ec4 100644 --- a/packages/genkit/src/genkit/_ai/_prompt.py +++ b/packages/genkit/src/genkit/_ai/_prompt.py @@ -225,7 +225,9 @@ class GenerateCall(BaseModel): metadata: dict[str, Any] | None = None # OutputSettings: the type that comes back. Fixed so Prompt[In, Out] holds. - output_schema: type | dict[str, Any] | str | None = None + # Any type form pydantic validates (list[T], Literal, Annotated, ...), a + # JSON schema dict, or a registered name; not `type`, which rejects aliases. + output_schema: Any = None output_format: str | None = None output_content_type: str | None = None output_instructions: bool | str | None = None @@ -364,11 +366,11 @@ async def _ensure_resolved(self) -> None: return resolved = await lookup_prompt(self._ai._registry, self._name, self._variant) - # Keep a Pydantic output type the caller passed: it wins over the file's - # dict schema or registered name, and the type is what gives typed output. + # Keep an output type the caller passed: it wins over the file's dict + # schema or registered name, and the type is what gives typed output. keep: dict[str, Any] = {} schema = self._def.output_schema - if isinstance(schema, type) and issubclass(schema, BaseModel): + if schema is not None and not isinstance(schema, (dict, str)): keep['output_schema'] = schema original_input = self._def.input_schema if original_input is not None: @@ -820,12 +822,13 @@ def resolve_output_schema( Handles three types of output_schema: - str: Schema name - look up JSON schema and type from registry - - Pydantic type: Store both JSON schema and type for runtime validation - dict: Raw JSON schema - convert directly + - Any other type (model, list[T], dataclass, Enum, ...): store both JSON + schema and type; the type hydrates ``.output`` through a TypeAdapter Args: registry: The registry to use for schema lookups. - output_schema: The schema to resolve (string name, Pydantic type, or dict). + output_schema: The schema to resolve (string name, Python type, or dict). output: The output config to populate with json_schema and schema_type. """ if output_schema is None: @@ -840,13 +843,11 @@ def resolve_output_schema( schema_type = registry.lookup_schema_type(output_schema) if schema_type: output.schema_type = schema_type - elif isinstance(output_schema, type) and issubclass(output_schema, BaseModel): - # Pydantic type - store both JSON schema and type + elif isinstance(output_schema, dict): output.json_schema = to_json_schema(output_schema) - output.schema_type = output_schema else: - # dict (raw JSON schema) output.json_schema = to_json_schema(output_schema) + output.schema_type = output_schema async def to_generate_options( diff --git a/packages/genkit/src/genkit/_core/_model.py b/packages/genkit/src/genkit/_core/_model.py index 477b7fd0b..ff374072f 100644 --- a/packages/genkit/src/genkit/_core/_model.py +++ b/packages/genkit/src/genkit/_core/_model.py @@ -37,7 +37,6 @@ Field, GetJsonSchemaHandler, PrivateAttr, - RootModel, TypeAdapter, ValidationError, ValidationInfo, @@ -57,8 +56,8 @@ from genkit._core._extract_json import extract_json, extract_partial_json, is_complete_json from genkit._core._logger import get_logger from genkit._core._operation import Operation -from genkit._core._partial import construct_partial -from genkit._core._schema import parse_schema +from genkit._core._partial import hydrate_chunk_items, hydrate_partial, is_model, unwrap_annotated +from genkit._core._schema import InvalidOutputSchemaError, output_adapter, parse_schema from genkit._core._typing import ( AgentFinishReason, Artifact as ArtifactData, @@ -1742,7 +1741,8 @@ class ModelResponse(GenkitModel, Generic[OutputT]): # _message_parser and _schema_type are set by the framework after construction # when output format parsing or schema validation is needed. _message_parser: Callable[[Message], object] | None = PrivateAttr(None) - _schema_type: type[BaseModel] | None = PrivateAttr(None) + # The output_schema type: a model, list[T], dataclass, Enum, Decimal, ... + _schema_type: Any = PrivateAttr(None) _failure: BoxedFailure | None = PrivateAttr(None) # Wire fields (must be declared for extra='forbid' to accept wire responses) message: Message | None = None @@ -1884,17 +1884,26 @@ def _assert_valid_schema(self) -> None: self._mark_invalid_output(error.message) return - # A custom format's parser can return a scalar (e.g. enum string). - # Skip Pydantic model validation for scalars. - is_custom_scalar = self._message_parser is not None and not isinstance(parsed, (dict, list)) - if is_custom_scalar or self._schema_type is None: + if self._keeps_raw(parsed): return try: - _ = self._schema_type.model_validate(parsed) + _ = output_adapter(self._schema_type).validate_python(parsed) except ValidationError: self._mark_invalid_output('Model output did not match the requested schema.') + def _keeps_raw(self, parsed: object) -> bool: + """Whether ``parsed`` is returned as-is instead of validated into the schema type.""" + if self._schema_type is None or parsed is None: + return True + # A custom format's parser can return a scalar (e.g. an enum string) + # that an object model class can't take. + return ( + self._message_parser is not None + and is_model(unwrap_annotated(annotation=self._schema_type)) + and not isinstance(parsed, (dict, list)) + ) + def _raw_parsed_output(self) -> object: if self._message_parser and self.message is not None: return self._message_parser(self.message) @@ -1966,15 +1975,12 @@ def output(self) -> OutputT | None: except GenkitError: return None - # A custom format's parser can return a scalar (e.g. enum string). - # Skip Pydantic model validation for scalars. - is_custom_scalar = self._message_parser is not None and not isinstance(parsed, (dict, list)) - if is_custom_scalar or self._schema_type is None or parsed is None: + if self._keeps_raw(parsed): return cast(OutputT, parsed) try: - return cast(OutputT, self._schema_type.model_validate(parsed)) - except ValidationError: + return cast(OutputT, output_adapter(self._schema_type).validate_python(parsed)) + except (ValidationError, InvalidOutputSchemaError): return None @property @@ -2037,7 +2043,7 @@ class ModelResponseChunk(GenkitModel, Generic[OutputT]): # construction so the constructor a plugin types is just the wire fields. _previous_chunks: list[Any] = PrivateAttr(default_factory=list) _chunk_parser: Callable[..., object] | None = PrivateAttr(default=None) - _schema_type: type[BaseModel] | None = PrivateAttr(default=None) + _schema_type: Any = PrivateAttr(default=None) # .output is parsed once per chunk. A plain @property over a private cache # rather than @cached_property: ty loses OutputT through cached_property on # a generic model and types every chunk.output as None. @@ -2110,6 +2116,12 @@ def output(self) -> OutputT | None: stay at ``None`` (or their default) until closed. Open numbers still pass through raw for ``datetime`` fields and for numeric ``Literal`` values that already match a member (even if more digits may follow). + - Once the JSON is complete the value is validated like the final + response; if that fails, this is ``None``. + + Other schema types hydrate the same way: ``list[Recipe]`` is a list of + ``Recipe``, an ``Enum`` is a member once the value is whole. A + dataclass or ``TypedDict`` stays a dict until the JSON closes. ``(await stream.response).output`` is the only fully validated ``Recipe``. The partial is built without validation, so a required ``title: str`` @@ -2131,23 +2143,26 @@ def _parse_output(self) -> object: try: text = self.accumulated_text parsed = self._chunk_parser(self) if self._chunk_parser else extract_partial_json(text) - if ( - self._schema_type is not None - and isinstance(parsed, dict) - and not issubclass(self._schema_type, RootModel) - ): - return construct_partial( - schema_type=self._schema_type, - data=parsed, - closed=is_complete_json(text), - ) - return parsed + if self._schema_type is None: + return parsed + if _streams_items(self._chunk_parser): + return hydrate_chunk_items(schema=self._schema_type, data=parsed) + return hydrate_partial(schema=self._schema_type, data=parsed, closed=is_complete_json(text)) except Exception: # one odd chunk shouldn't end a stream whose final reply may still parse. logger.debug('chunk.output could not be parsed; returning None', exc_info=True) return None +def _streams_items(chunk_parser: Callable[..., object] | None) -> bool: + if chunk_parser is None: + return False + return bool( + getattr(chunk_parser, '_streams_items', False) + or getattr(getattr(chunk_parser, '__self__', None), '_streams_items', False) + ) + + def as_model_response_chunk(value: object) -> ModelResponseChunk: if isinstance(value, ModelResponseChunk): copied = value.model_copy() @@ -2165,7 +2180,7 @@ def chunk_for_stream( index: float | None = None, previous_chunks: list[Any] | None = None, chunk_parser: Callable[..., object] | None = None, - schema_type: type[BaseModel] | None = None, + schema_type: Any = None, # noqa: ANN401 ) -> ModelResponseChunk[OutputT]: """Copy a plugin chunk and stamp stream index / parser on the copy. diff --git a/packages/genkit/src/genkit/_core/_partial.py b/packages/genkit/src/genkit/_core/_partial.py index 3d62b952e..8a688fa60 100644 --- a/packages/genkit/src/genkit/_core/_partial.py +++ b/packages/genkit/src/genkit/_core/_partial.py @@ -27,38 +27,84 @@ from __future__ import annotations import sys +import typing from collections.abc import Hashable, Mapping, MutableMapping, MutableSequence, Sequence from contextlib import suppress from enum import Enum from functools import lru_cache from types import UnionType -from typing import Annotated, Any, ForwardRef, Literal, TypeGuard, Union, cast, get_args, get_origin, get_type_hints - -from pydantic import AliasChoices, BaseModel, Discriminator, RootModel, TypeAdapter +from typing import ( + Annotated, + Any, + ForwardRef, + Literal, + TypeGuard, + TypeVar, + Union, + cast, + get_args, + get_origin, + get_type_hints, +) + +from pydantic import AliasChoices, BaseModel, Discriminator, RootModel, TypeAdapter, ValidationError from pydantic.fields import FieldInfo from pydantic_core import SchemaValidator, core_schema +from typing_extensions import TypeAliasType as _ExtTypeAliasType + +from genkit._core._schema import output_adapter -SEQUENCE_ORIGINS = (list, tuple, Sequence, MutableSequence) +SEQUENCE_ORIGINS = (list, tuple, set, frozenset, Sequence, MutableSequence) MAPPING_ORIGINS = (dict, Mapping, MutableMapping) UNION_ORIGINS = (Union, UnionType) +_STDLIB_VALUE_MODULES = frozenset({'builtins', 'uuid', 'datetime', 'decimal', '_decimal', 'pathlib', 'ipaddress'}) +_StdTypeAliasType: Any = getattr(typing, 'TypeAliasType', None) +_TYPE_ALIAS_TYPES: tuple[type[Any], ...] = ( + (_StdTypeAliasType, _ExtTypeAliasType) if isinstance(_StdTypeAliasType, type) else (_ExtTypeAliasType,) +) _UNRESOLVED = object() def is_model(annotation: Any) -> TypeGuard[type[BaseModel]]: # noqa: ANN401 - return ( - isinstance(annotation, type) - and issubclass(annotation, BaseModel) - and annotation is not BaseModel - and not issubclass(annotation, RootModel) - ) + try: + return ( + isinstance(annotation, type) + and issubclass(annotation, BaseModel) + and annotation is not BaseModel + and not issubclass(annotation, RootModel) + ) + except TypeError: # dict[str, Any] passes isinstance(_, type) on 3.10 + return False -def unwrap_annotated(*, annotation: Any) -> Any: # noqa: ANN401 - while get_origin(annotation) is Annotated: +def _step_type_alias(annotation: Any) -> tuple[Any, bool]: # noqa: ANN401 + if isinstance(annotation, _TYPE_ALIAS_TYPES): + return getattr(annotation, '__value__', annotation), True + origin = get_origin(annotation) + if isinstance(origin, _TYPE_ALIAS_TYPES): args = get_args(annotation) - if not args: - break - annotation = args[0] + value = getattr(origin, '__value__', None) + if args and value is not None: + with suppress(Exception): + return value[args[0] if len(args) == 1 else args], True + return annotation, False + + +def unwrap_annotated(*, annotation: Any) -> Any: # noqa: ANN401 + seen: set[int] = set() + while id(annotation) not in seen: + seen.add(id(annotation)) + stepped, changed = _step_type_alias(annotation) + if changed: + annotation = stepped + continue + if get_origin(annotation) is Annotated: + args = get_args(annotation) + if not args: + break + annotation = args[0] + continue + break return annotation @@ -79,17 +125,28 @@ def extract_discriminator(*, annotation: Any, info: FieldInfo | None = None) -> if disc is not None: return _unwrap_discriminator(disc) cur = annotation - while get_origin(cur) is Annotated: - args = get_args(cur) - if not args: - break - for meta in args[1:]: - disc = ( - _unwrap_discriminator(meta) if isinstance(meta, Discriminator) else getattr(meta, 'discriminator', None) - ) - if disc is not None: - return _unwrap_discriminator(disc) - cur = args[0] + seen: set[int] = set() + while id(cur) not in seen: + seen.add(id(cur)) + stepped, changed = _step_type_alias(cur) + if changed: + cur = stepped + continue + if get_origin(cur) is Annotated: + args = get_args(cur) + if not args: + break + for meta in args[1:]: + disc = ( + _unwrap_discriminator(meta) + if isinstance(meta, Discriminator) + else getattr(meta, 'discriminator', None) + ) + if disc is not None: + return _unwrap_discriminator(disc) + cur = args[0] + continue + break if get_origin(cur) in UNION_ORIGINS: for arg in get_args(cur): found = extract_discriminator(annotation=arg) @@ -98,7 +155,7 @@ def extract_discriminator(*, annotation: Any, info: FieldInfo | None = None) -> return None -def lookup_name(*, name: str, schema_type: type[BaseModel]) -> type[BaseModel] | None: +def lookup_name(*, name: str, schema_type: type) -> type[BaseModel] | None: # list['Post'] stores the name they wrote, not the class. The class # lives next to the schema on its module, or is the schema itself. if name == schema_type.__name__ and is_model(schema_type): @@ -108,7 +165,7 @@ def lookup_name(*, name: str, schema_type: type[BaseModel]) -> type[BaseModel] | return obj if is_model(obj) else None -def resolve(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: ANN401 +def resolve(*, annotation: Any, schema_type: type) -> Any: # noqa: ANN401 annotation = unwrap_annotated(annotation=annotation) if isinstance(annotation, ForwardRef): annotation = annotation.__forward_arg__ @@ -118,7 +175,7 @@ def resolve(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: A return annotation -def union_members(*, annotation: Any, schema_type: type[BaseModel]) -> tuple[Any, ...]: # noqa: ANN401 +def union_members(*, annotation: Any, schema_type: type) -> tuple[Any, ...]: # noqa: ANN401 annotation = resolve(annotation=annotation, schema_type=schema_type) origin = get_origin(annotation) if origin in UNION_ORIGINS: @@ -129,7 +186,7 @@ def union_members(*, annotation: Any, schema_type: type[BaseModel]) -> tuple[Any return (annotation,) -def unwrap_optional_container(*, annotation: Any, schema_type: type[BaseModel]) -> Any: # noqa: ANN401 +def unwrap_optional_container(*, annotation: Any, schema_type: type) -> Any: # noqa: ANN401 annotation = resolve(annotation=annotation, schema_type=schema_type) if get_origin(annotation) in UNION_ORIGINS: non_none = [ @@ -148,7 +205,10 @@ def field_annotation(*, schema_type: type[BaseModel], name: str, info: FieldInfo hints = get_type_hints(schema_type, include_extras=True) except Exception: return annotation - return hints.get(name, annotation) + hint = hints.get(name, annotation) + if isinstance(hint, TypeVar) or getattr(hint, '__parameters__', ()): + return info.rebuild_annotation() + return hint def field_keys(*, name: str, info: FieldInfo) -> tuple[str, ...]: @@ -253,7 +313,7 @@ def overlap(*, schema_type: type[BaseModel], data: dict[str, Any]) -> int: return len(keys & data.keys()) -def pick_model(*, annotation: Any, data: dict[str, Any], schema_type: type[BaseModel]) -> type[BaseModel] | None: # noqa: ANN401 +def pick_model(*, annotation: Any, data: dict[str, Any], schema_type: type) -> type[BaseModel] | None: # noqa: ANN401 candidates = [ member for member in union_members(annotation=annotation, schema_type=schema_type) if is_model(member) ] @@ -269,8 +329,10 @@ def _cached_adapter(annotation: Any, module_name: str) -> TypeAdapter[Any]: # n return TypeAdapter(annotation, module=module_name) -def validate_closed_value(*, annotation: Any, raw: Any, schema_type: type[BaseModel]) -> tuple[Any, bool]: # noqa: ANN401 +def validate_closed_value(*, annotation: Any, raw: Any, schema_type: type) -> tuple[Any, bool]: # noqa: ANN401 try: + if schema_type is object: + return output_adapter(annotation).validate_python(raw), True try: adapter = _cached_adapter(annotation, schema_type.__module__) except TypeError: @@ -363,18 +425,30 @@ def validate_closed_field( return None, False -def accepts_open_scalar(*, annotation: Any, raw: Any, schema_type: type[BaseModel]) -> bool: # noqa: ANN401 +def _enum_str_values(*, members: Sequence[Any]) -> set[str]: + values: set[str] = set() + for member in members: + if isinstance(member, type) and issubclass(member, Enum): + for item in member: + if isinstance(item.value, str): + values.add(item.value) + return values + + +def accepts_open_scalar(*, annotation: Any, raw: Any, schema_type: type) -> bool: # noqa: ANN401 members = [m for m in union_members(annotation=annotation, schema_type=schema_type) if m is not type(None)] if not members or any(m in (Any, object) for m in members): return True - tags = literal_values(annotation=annotation) + if isinstance(raw, str) and any(m is str for m in members): + return True + tags = literal_values(annotation=annotation) | _enum_str_values(members=members) if tags and raw in tags: return not ( isinstance(raw, str) and any(isinstance(other, str) and other != raw and other.startswith(raw) for other in tags) ) if isinstance(raw, str): - return any(m is str for m in members) + return False if isinstance(raw, (int, float)) and not isinstance(raw, bool): return not all((isinstance(m, type) and issubclass(m, Enum)) or get_origin(m) is Literal for m in members) return True @@ -384,7 +458,7 @@ def coerce( *, annotation: Any, # noqa: ANN401 raw: Any, # noqa: ANN401 - schema_type: type[BaseModel], + schema_type: type, closed: bool = False, discriminator: str | object | None = None, ) -> Any: # noqa: ANN401 @@ -411,7 +485,7 @@ def coerce( if handled: if matched is None: return _UNRESOLVED - return construct_partial(schema_type=matched, data=raw, closed=closed) + return build_partial(schema_type=matched, data=raw, closed=closed) if closed: validated, ok = validate_closed_value(annotation=annotation, raw=raw, schema_type=schema_type) @@ -422,7 +496,7 @@ def coerce( if isinstance(raw, dict): model = pick_model(annotation=annotation, data=raw, schema_type=schema_type) if model is not None: - return construct_partial(schema_type=model, data=raw, closed=closed) + return build_partial(schema_type=model, data=raw, closed=closed) origin = get_origin(container_annotation) if origin in MAPPING_ORIGINS: args = get_args(container_annotation) @@ -460,10 +534,21 @@ def coerce( ) if coerced_item is not _UNRESOLVED: items.append(coerced_item) - return tuple(items) if origin is tuple else items + if origin is tuple: + return tuple(items) + if origin in (set, frozenset): + with suppress(TypeError): + return origin(items) + return items return raw - if not closed and not accepts_open_scalar(annotation=annotation, raw=raw, schema_type=schema_type): - return _UNRESOLVED + if not closed: + if not accepts_open_scalar(annotation=annotation, raw=raw, schema_type=schema_type): + return _UNRESOLVED + members = [m for m in union_members(annotation=annotation, schema_type=schema_type) if m is not type(None)] + if any(isinstance(m, type) and issubclass(m, Enum) for m in members) and not any(m is str for m in members): + validated, ok = validate_closed_value(annotation=annotation, raw=raw, schema_type=schema_type) + if ok: + return validated return raw @@ -476,10 +561,20 @@ def construct_partial(*, schema_type: type[BaseModel], data: dict[str, Any], clo and missing required fields are ``None``. Keys and list items before the trailing open frontier run field validation (``@field_validator`` and field constraints, while ``@model_validator`` waits until the object itself - closes); closed values that fail validation fall back to - ``model_construct`` / raw values. ``(await stream.response).output`` - remains the only fully validated value. + closes); nested closed values that fail validation fall back to + ``model_construct`` / raw values. + + With ``closed=True`` the whole object is done, so it is validated like the + final response and a ``ValidationError`` propagates: the closing chunk + never carries an object that skipped validators. """ + if closed: + return schema_type.model_validate(data) + return build_partial(schema_type=schema_type, data=data, closed=False) + + +def build_partial(*, schema_type: type[BaseModel], data: dict[str, Any], closed: bool) -> BaseModel: + """``construct_partial`` for a nested object: a closed one that fails validation is still built.""" if closed: with suppress(Exception): return schema_type.model_validate(data) @@ -516,3 +611,108 @@ def construct_partial(*, schema_type: type[BaseModel], data: dict[str, Any], clo ) values[name] = default_value(info=info, validated_data=values) if coerced is _UNRESOLVED else coerced return schema_type.model_construct(**values) + + +def _is_root_model(annotation: Any) -> TypeGuard[type[RootModel[Any]]]: # noqa: ANN401 + try: + return isinstance(annotation, type) and issubclass(annotation, RootModel) + except TypeError: # list[int] passes isinstance(_, type) on 3.10 + return False + + +def anchor_type(annotation: Any) -> type: # noqa: ANN401 + """The first user class inside ``annotation``; its module resolves string forward refs.""" + pending: list[Any] = [annotation] + seen: set[int] = set() + while pending: + current = pending.pop(0) + if id(current) in seen: + continue + seen.add(id(current)) + stepped, changed = _step_type_alias(current) + if changed: + pending.append(stepped) + continue + if ( + isinstance(current, type) + and get_origin(current) is None + and current.__module__.split('.', 1)[0] not in _STDLIB_VALUE_MODULES + ): + return current + pending.extend(get_args(current)) + return object + + +def _validate_strict_item(*, annotation: Any, raw: Any, anchor: type) -> Any: # noqa: ANN401 + if anchor is object: + return output_adapter(annotation).validate_python(raw) + try: + adapter = _cached_adapter(annotation, anchor.__module__) + except TypeError: + adapter = TypeAdapter(annotation, module=anchor.__module__) + return adapter.validate_python(raw) + + +def hydrate_chunk_items(*, schema: Any, data: Any) -> Any: # noqa: ANN401 + """Hydrate a per-chunk delta list of complete items against ``schema``'s element type.""" + if not isinstance(data, list): + return hydrate_partial(schema=schema, data=data, closed=False) + unwrapped = unwrap_annotated(annotation=schema) + anchor: type = unwrapped if _is_root_model(unwrapped) else anchor_type(schema) + if _is_root_model(unwrapped): + info = unwrapped.model_fields['root'] + unwrapped = unwrap_annotated(annotation=field_annotation(schema_type=unwrapped, name='root', info=info)) + container = unwrap_optional_container(annotation=unwrapped, schema_type=anchor) + if get_origin(container) not in SEQUENCE_ORIGINS: + return data + inners = tuple(arg for arg in get_args(container) if arg is not Ellipsis) + if not inners or not data: + return [] if not data else data + unique = list(dict.fromkeys(inners)) + if len(unique) == 1: + return [_validate_strict_item(annotation=unique[0], raw=item, anchor=anchor) for item in data] + hydrated: list[Any] = [] + for item in data: + last_err: ValidationError | None = None + for candidate in unique: + try: + hydrated.append(_validate_strict_item(annotation=candidate, raw=item, anchor=anchor)) + last_err = None + break + except ValidationError as err: + last_err = err + if last_err is not None: + raise last_err + return hydrated + + +def hydrate_partial(*, schema: Any, data: Any, closed: bool) -> Any: # noqa: ANN401 + """Turn a streamed JSON value into ``schema`` as far as it goes. + + ``schema`` is any ``output_schema`` type. With ``closed=True`` the JSON is + complete, so the value is validated like the final response and a + ``ValidationError`` propagates. An open value is built leniently: models + through ``construct_partial``, lists and dicts item by item. A scalar + that can't be used yet (a prefix of an ``Enum`` value) is ``None``. A + dataclass or ``TypedDict`` has no partial form and stays raw JSON until + the value closes. + """ + if data is None: + return None + unwrapped = unwrap_annotated(annotation=schema) + # A model class only takes an object; anything else (a custom format's + # scalar) passes through as parsed. + if is_model(unwrapped) and not isinstance(data, dict): + return data + if closed: + return output_adapter(schema).validate_python(data) + if _is_root_model(unwrapped): + info = unwrapped.model_fields['root'] + root = coerce( + annotation=field_annotation(schema_type=unwrapped, name='root', info=info), + raw=data, + schema_type=unwrapped, + ) + return None if root is _UNRESOLVED else unwrapped.model_construct(root=root) + value = coerce(annotation=schema, raw=data, schema_type=anchor_type(schema)) + return None if value is _UNRESOLVED else value diff --git a/packages/genkit/src/genkit/_core/_schema.py b/packages/genkit/src/genkit/_core/_schema.py index f23df6c76..f14b1eb8d 100644 --- a/packages/genkit/src/genkit/_core/_schema.py +++ b/packages/genkit/src/genkit/_core/_schema.py @@ -24,7 +24,7 @@ from typing import Any, cast from jsonschema.validators import validator_for -from pydantic import TypeAdapter +from pydantic import PydanticUserError, TypeAdapter from genkit._core._error import ErrorReason, GenkitError @@ -47,8 +47,11 @@ def to_json_schema(schema: type | dict[str, Any] | str | None) -> dict[str, Any] return {'type': 'null'} if isinstance(schema, dict): return schema - type_adapter = TypeAdapter(schema) - return type_adapter.json_schema() + try: + type_adapter = TypeAdapter(schema) + return type_adapter.json_schema() + except (PydanticUserError, TypeError) as error: + raise InvalidOutputSchemaError(cause=error) from error def custom_options_schema(schema: type | dict[str, Any]) -> dict[str, Any]: @@ -92,6 +95,30 @@ def fixed_json_schema(cls: type) -> dict[str, Any]: return copy.deepcopy(_generated_schema(cls)) +@functools.lru_cache(maxsize=512) +def _cached_output_adapter(schema_type: Any) -> TypeAdapter[Any]: # noqa: ANN401 + return TypeAdapter(schema_type) + + +def output_adapter(schema_type: Any) -> TypeAdapter[Any]: # noqa: ANN401 + """The ``TypeAdapter`` that turns parsed JSON into an ``output_schema`` value. + + Works for any type pydantic validates: a model, ``list[T]``, ``dict``, + ``Literal``, ``Annotated``, a dataclass, ``TypedDict``, ``Enum``, + ``Decimal``, ``UUID``, ``datetime``. Built once per type; an annotation + whose metadata isn't hashable gets a fresh adapter each call. + """ + try: + return _cached_output_adapter(schema_type) + except PydanticUserError as error: + raise InvalidOutputSchemaError(cause=error) from error + except TypeError: + try: + return TypeAdapter(schema_type) + except (PydanticUserError, TypeError) as error: + raise InvalidOutputSchemaError(cause=error) from error + + def check_output_schema(json_schema: dict[str, Any]) -> None: """Raise if ``json_schema`` is not itself a JSON Schema. diff --git a/packages/genkit/tests/genkit/ai/output_hydration_test.py b/packages/genkit/tests/genkit/ai/output_hydration_test.py new file mode 100644 index 000000000..920419695 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/output_hydration_test.py @@ -0,0 +1,493 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""output_schema hydrates every type pydantic validates, not just BaseModel. + +``ai.generate(output_schema=T)`` types ``.output`` as ``T``; these tests pin +that runtime returns a ``T`` too, for responses, stream chunks, and prompts. +""" + +import dataclasses +import datetime +import enum +import ipaddress +import pathlib +import sys +import typing +import uuid +from decimal import Decimal +from typing import Annotated, Any, Literal + +import pytest +from pydantic import BaseModel, Field, RootModel, ValidationError, field_validator +from pydantic.dataclasses import dataclass as pydantic_dataclass +from typing_extensions import TypeAliasType, TypedDict + +from genkit import Genkit, GenkitError, Message, ModelResponse, ModelResponseChunk, Part +from genkit._core._error import ErrorReason +from genkit._core._partial import anchor_type, construct_partial, hydrate_partial, unwrap_annotated +from genkit._core._schema import InvalidOutputSchemaError, output_adapter, to_json_schema +from genkit._core._typing import Role +from genkit.testing import define_scripted_model + + +class InvoiceItem(BaseModel): + sku: str + quantity: int + + +class InvoiceList(RootModel[list[InvoiceItem]]): + pass + + +class ScoreRoot(RootModel[int]): + pass + + +class LabelRoot(RootModel[str]): + pass + + +class EvenScoreRoot(RootModel[int]): + @field_validator('root') + @classmethod + def _must_be_even(cls, v: int) -> int: + if v % 2 != 0: + raise ValueError('score must be even') + return v + + +@dataclasses.dataclass +class Vendor: + vendor_name: str + risk_score: int + + +@pydantic_dataclass +class PydanticVendor: + vendor_name: str + risk_score: int + + +class VendorDict(TypedDict): + vendor_name: str + risk_score: int + + +class Triage(enum.Enum): + APPROVE = 'APPROVE' + ESCALATE = 'ESCALATE' + + +class TriageStr(str, enum.Enum): # noqa: UP042 # enum.StrEnum is 3.11+ + APPROVE = 'APPROVE' + ESCALATE = 'ESCALATE' + + +class Plan(str, enum.Enum): # noqa: UP042 # enum.StrEnum is 3.11+ + PRO = 'PRO' + PRO_PLUS = 'PRO_PLUS' + + +class TriageRoot(RootModel[Triage]): + pass + + +class Pickup(BaseModel): + pickup_time: str + + +class Delivery(BaseModel): + address: str + + +@dataclasses.dataclass +class Contact: + vendor: Vendor + emails: list[str] + + +class PurchaseOrder(BaseModel): + lines: list[VendorDict] + contact: Contact | None = None + + +VendorListAlias = TypeAliasType('VendorListAlias', list[Vendor]) + + +def _ai_with_reply(text: str, chunks: list[str] | None = None) -> Genkit: + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(text)]))] + if chunks is not None: + pm.chunks = [[ModelResponseChunk(role=Role.MODEL, content=[Part.from_text(c)]) for c in chunks]] + return ai + + +VENDOR_JSON = '{"vendor_name": "Acme", "risk_score": 12}' +BETA_VENDOR_JSON = '{"vendor_name": "Beta", "risk_score": 5}' +UID = '550e8400-e29b-41d4-a716-446655440000' + +CASES: list[tuple[str, Any, str, Any]] = [ + ('list_of_models', list[InvoiceItem], '[{"sku": "CH-1", "quantity": 2}]', [InvoiceItem(sku='CH-1', quantity=2)]), + ('root_model', InvoiceList, '[{"sku": "CH-1", "quantity": 2}]', InvoiceList([InvoiceItem(sku='CH-1', quantity=2)])), + ('scalar_root_int', ScoreRoot, '42', ScoreRoot(42)), + ('scalar_root_str', LabelRoot, '"approved"', LabelRoot('approved')), + ('scalar_root_enum', TriageRoot, '"ESCALATE"', TriageRoot(Triage.ESCALATE)), + ('inline_root_int', RootModel[int], '7', RootModel[int](7)), + ('inline_root_str', RootModel[str], '"ok"', RootModel[str]('ok')), + ('set_of_str', set[str], '["a", "b"]', {'a', 'b'}), + ('frozenset_of_int', frozenset[int], '[1, 2]', frozenset({1, 2})), + ('pep695_alias', VendorListAlias, f'[{VENDOR_JSON}]', [Vendor(vendor_name='Acme', risk_score=12)]), + ('dict', dict[str, int], '{"a": 1}', {'a': 1}), + ('literal', Literal['APPROVE', 'ESCALATE'], '"ESCALATE"', 'ESCALATE'), + ('annotated', Annotated[int, Field(gt=0)], '7', 7), + ('dataclass', Vendor, VENDOR_JSON, Vendor(vendor_name='Acme', risk_score=12)), + ('pydantic_dataclass', PydanticVendor, VENDOR_JSON, PydanticVendor(vendor_name='Acme', risk_score=12)), + ('typed_dict', VendorDict, VENDOR_JSON, {'vendor_name': 'Acme', 'risk_score': 12}), + ('enum', Triage, '"ESCALATE"', Triage.ESCALATE), + ('str_enum', TriageStr, '"ESCALATE"', TriageStr.ESCALATE), + ('decimal', Decimal, '14250.75', Decimal('14250.75')), + ('uuid', uuid.UUID, f'"{UID}"', uuid.UUID(UID)), + ( + 'datetime', + datetime.datetime, + '"2026-10-15T14:30:00Z"', + datetime.datetime(2026, 10, 15, 14, 30, tzinfo=datetime.timezone.utc), + ), + ('optional_model', InvoiceItem | None, '{"sku": "CH-1", "quantity": 2}', InvoiceItem(sku='CH-1', quantity=2)), + ('union_of_models', Pickup | Delivery, '{"address": "1 Main St"}', Delivery(address='1 Main St')), + ( + 'nested_dataclass', + Contact, + f'{{"vendor": {VENDOR_JSON}, "emails": ["ap@acme.test"]}}', + Contact(vendor=Vendor(vendor_name='Acme', risk_score=12), emails=['ap@acme.test']), + ), +] + + +@pytest.mark.asyncio +@pytest.mark.parametrize(('schema', 'reply', 'expected'), [c[1:] for c in CASES], ids=[c[0] for c in CASES]) +async def test_generate_hydrates_output_schema(schema: Any, reply: str, expected: Any) -> None: # noqa: ANN401 + response = await _ai_with_reply(reply).generate(prompt='hi', output_schema=schema) + + assert response.error is None + assert response.output == expected + assert type(response.output) is type(expected) + + +@pytest.mark.asyncio +async def test_dict_of_decimal_hydrates_json_number() -> None: + response = await _ai_with_reply('{"amount": 0.1}').generate(prompt='hi', output_schema=dict[str, Decimal]) + + assert response.output == {'amount': Decimal('0.1')} + + +@pytest.mark.asyncio +async def test_wrong_shape_is_invalid_output_for_non_model_schema() -> None: + response = await _ai_with_reply('[{"sku": "CH-1"}]').generate(prompt='hi', output_schema=list[InvoiceItem]) + + assert response.output is None + assert response.error is not None + assert response.error.details == {'reason': 'INVALID_OUTPUT'} + + +@pytest.mark.asyncio +async def test_scalar_root_model_streams_and_rejects_invalid_scalars() -> None: + ai = _ai_with_reply('"hello"', chunks=['"hel', 'lo"']) + stream = ai.generate_stream(prompt='hi', output_schema=LabelRoot) + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [None, LabelRoot('hello')] + assert response.output == LabelRoot('hello') + assert hydrate_partial(schema=LabelRoot, data='hel', closed=False) == LabelRoot('hel') + assert hydrate_partial(schema=InvoiceList, data=[{'sku': 'CH-1'}], closed=False) == InvoiceList([ + InvoiceItem.model_construct(sku='CH-1', quantity=None) + ]) + + wrong_type = await _ai_with_reply('"not-an-int"').generate(prompt='hi', output_schema=ScoreRoot) + assert wrong_type.output is None + assert wrong_type.error is not None + assert wrong_type.error.details == {'reason': 'INVALID_OUTPUT'} + + # Odd integer passes JSON schema ('type': 'integer') and must still fail Pydantic validation. + odd_score = await _ai_with_reply('3').generate(prompt='hi', output_schema=EvenScoreRoot) + assert odd_score.output is None + assert odd_score.error is not None + assert odd_score.error.details == {'reason': 'INVALID_OUTPUT'} + + +@pytest.mark.asyncio +async def test_enum_format_returns_member() -> None: + response = await _ai_with_reply('ESCALATE').generate(prompt='hi', output_schema=TriageStr, output_format='enum') + + assert response.output is TriageStr.ESCALATE + + +@pytest.mark.asyncio +async def test_enum_format_stream_waits_when_chunk_is_prefix_of_longer_member() -> None: + stream_plus = _ai_with_reply('PRO_PLUS', chunks=['PRO', '_PLUS']).generate_stream( + prompt='hi', output_schema=Plan, output_format='enum' + ) + plus_chunks = [chunk.output async for chunk in stream_plus.stream] + plus_response = await stream_plus.response + + assert plus_chunks == [None, Plan.PRO_PLUS] + assert plus_response.output is Plan.PRO_PLUS + + stream_pro = _ai_with_reply('PRO', chunks=['PRO']).generate_stream( + prompt='hi', output_schema=Plan, output_format='enum' + ) + pro_chunks = [chunk.output async for chunk in stream_pro.stream] + pro_response = await stream_pro.response + + assert pro_chunks == [None] + assert pro_response.output is Plan.PRO + + +@pytest.mark.asyncio +async def test_array_format_with_list_schema_hydrates_chunks_and_response() -> None: + ai = _ai_with_reply( + '[{"sku": "CH-1", "quantity": 2}, {"sku": "DK-2", "quantity": 5}]', + chunks=['[{"sku": "CH-1", "quantity": 2}, ', '{"sku": "DK-2", "quantity": 5}]'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=list[InvoiceItem], output_format='array') + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [[InvoiceItem(sku='CH-1', quantity=2)], [InvoiceItem(sku='DK-2', quantity=5)]] + assert response.output == [InvoiceItem(sku='CH-1', quantity=2), InvoiceItem(sku='DK-2', quantity=5)] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('schema', 'expected_items'), + [ + (list[Vendor], [Vendor('Acme', 12), Vendor('Beta', 5)]), + (list[VendorDict], [{'vendor_name': 'Acme', 'risk_score': 12}, {'vendor_name': 'Beta', 'risk_score': 5}]), + (Annotated[list[Vendor], Field(min_length=2)], [Vendor('Acme', 12), Vendor('Beta', 5)]), + ], + ids=['dataclass', 'typed_dict', 'annotated_min_length'], +) +async def test_array_format_hydrates_per_item_deltas(schema: Any, expected_items: list[Any]) -> None: # noqa: ANN401 + full_text = f'[{VENDOR_JSON}, {BETA_VENDOR_JSON}]' + ai = _ai_with_reply( + full_text, + chunks=['[{"vendor_name": "Ac', 'me", "risk_score": 12}, ', BETA_VENDOR_JSON, ']'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=schema, output_format='array') + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [[], [expected_items[0]], [expected_items[1]], []] + assert response.output == expected_items + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ('schema', 'expected_items'), + [ + (list[Vendor], [Vendor('Acme', 12), Vendor('Beta', 5)]), + (list[VendorDict], [{'vendor_name': 'Acme', 'risk_score': 12}, {'vendor_name': 'Beta', 'risk_score': 5}]), + (Annotated[list[Vendor], Field(min_length=2)], [Vendor('Acme', 12), Vendor('Beta', 5)]), + ], + ids=['dataclass', 'typed_dict', 'annotated_min_length'], +) +async def test_jsonl_format_hydrates_per_item_deltas(schema: Any, expected_items: list[Any]) -> None: # noqa: ANN401 + full_text = f'{VENDOR_JSON}\n{BETA_VENDOR_JSON}\n' + ai = _ai_with_reply( + full_text, + chunks=[f'{VENDOR_JSON}\n{{"vendor_name": "Be', 'ta", "risk_score": 5}\n'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=schema, output_format='jsonl') + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [[expected_items[0]], [expected_items[1]]] + assert response.output == expected_items + + +@pytest.mark.asyncio +async def test_array_format_still_enforces_list_constraints_on_final_response() -> None: + ai = _ai_with_reply(f'[{VENDOR_JSON}]', chunks=[f'[{VENDOR_JSON}', ']']) + stream = ai.generate_stream( + prompt='hi', + output_schema=Annotated[list[Vendor], Field(min_length=2)], + output_format='array', + ) + outputs = [chunk.output async for chunk in stream.stream] + response = await stream.response + + assert outputs == [[Vendor('Acme', 12)], []] + assert response.output is None + assert response.error is not None + assert response.error.details == {'reason': 'INVALID_OUTPUT'} + + +@pytest.mark.asyncio +async def test_stream_model_with_nested_dataclass_and_typed_dict() -> None: + reply = f'{{"lines": [{VENDOR_JSON}], "contact": {{"vendor": {VENDOR_JSON}, "emails": []}}}}' + ai = _ai_with_reply(reply, chunks=[reply[:30], reply[30:]]) + stream = ai.generate_stream(prompt='hi', output_schema=PurchaseOrder) + outputs = [chunk.output async for chunk in stream.stream] + + # Open: the model is partial; the open TypedDict line stays a raw dict. + assert isinstance(outputs[0], PurchaseOrder) + assert outputs[0].lines == [{'vendor_name': 'Ac'}] + assert outputs[0].contact is None + # Closed: the nested dataclass is hydrated, same as the final response. + expected = PurchaseOrder( + lines=[{'vendor_name': 'Acme', 'risk_score': 12}], + contact=Contact(vendor=Vendor(vendor_name='Acme', risk_score=12), emails=[]), + ) + assert outputs[1] == expected + assert (await stream.response).output == expected + + +@pytest.mark.asyncio +async def test_stream_chunks_of_list_schema_are_models() -> None: + ai = _ai_with_reply( + '[{"sku": "CH-1", "quantity": 2}]', + chunks=['[{"sku": "CH-1", "qu', 'antity": 2}]'], + ) + stream = ai.generate_stream(prompt='hi', output_schema=list[InvoiceItem]) + outputs = [chunk.output async for chunk in stream.stream] + + # Open: the half-written item is an InvoiceItem with holes. + first = outputs[0] + assert first is not None + assert isinstance(first[0], InvoiceItem) + assert first[0].sku == 'CH-1' + assert first[0].quantity is None + # Closed: validated like the final response. + assert outputs[1] == [InvoiceItem(sku='CH-1', quantity=2)] + assert (await stream.response).output == outputs[1] + + +@pytest.mark.asyncio +async def test_stream_set_and_frozenset_schemas() -> None: + set_stream = _ai_with_reply('["a", "b"]', chunks=['["a", "b', '"]']).generate_stream( + prompt='hi', output_schema=set[str] + ) + set_chunks = [chunk.output async for chunk in set_stream.stream] + assert set_chunks == [{'a', 'b'}, {'a', 'b'}] + assert (await set_stream.response).output == {'a', 'b'} + + frozen_stream = _ai_with_reply('[1, 2]', chunks=['[1, ', '2]']).generate_stream( + prompt='hi', output_schema=frozenset[int] + ) + frozen_chunks = [chunk.output async for chunk in frozen_stream.stream] + assert frozen_chunks == [frozenset({1}), frozenset({1, 2})] + assert (await frozen_stream.response).output == frozenset({1, 2}) + + +@pytest.mark.asyncio +async def test_define_prompt_accepts_generic_alias_schema() -> None: + ai = _ai_with_reply('[{"sku": "CH-1", "quantity": 2}]') + prompt = ai.define_prompt(name='invoice', prompt='List items.', output_schema=list[InvoiceItem]) + + response = await prompt() + + assert response.output == [InvoiceItem(sku='CH-1', quantity=2)] + + +@pytest.mark.asyncio +async def test_looked_up_prompt_keeps_caller_generic_alias_schema() -> None: + ai = _ai_with_reply('[{"sku": "CH-1", "quantity": 2}]') + ai.define_prompt(name='invoice', prompt='List items.', output_schema={'type': 'array'}) + + prompt = ai.prompt('invoice', output_schema=list[InvoiceItem]) + response = await prompt() + + assert response.output == [InvoiceItem(sku='CH-1', quantity=2)] + + +class Unschemable: + pass + + +@pytest.mark.asyncio +@pytest.mark.parametrize('bad_schema', [[InvoiceItem], 123, Unschemable], ids=['list_instance', 'int', 'plain_class']) +async def test_invalid_output_schema_raises_invalid_output_schema_error(bad_schema: Any) -> None: # noqa: ANN401 + ai = Genkit(model='scriptedModel') + pm, _ = define_scripted_model(ai) + pm.responses = [ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{}')]))] + + with pytest.raises(InvalidOutputSchemaError) as exc_info: + await ai.generate(prompt='hi', output_schema=bad_schema) + + assert isinstance(exc_info.value, GenkitError) + assert exc_info.value.status == 'INVALID_ARGUMENT' + assert exc_info.value.reason is ErrorReason.INVALID_SCHEMA + assert pm.request_count == 0 + + with pytest.raises(InvalidOutputSchemaError): + to_json_schema(bad_schema) + + with pytest.raises(InvalidOutputSchemaError): + output_adapter(bad_schema) + + +class Dish(BaseModel): + name: str + + @field_validator('name') + @classmethod + def _capitalized(cls, v: str) -> str: + if not v[:1].isupper(): + raise ValueError('must be capitalized') + return v + + +def test_construct_partial_closed_raises_instead_of_model_construct() -> None: + with pytest.raises(ValidationError): + construct_partial(schema_type=Dish, data={'name': 'salmon'}, closed=True) + + +def test_construct_partial_open_still_builds() -> None: + out = construct_partial(schema_type=Dish, data={'name': 'salm'}) + + assert isinstance(out, Dish) + assert out.name == 'salm' + + +def test_hydrate_partial_enum_prefix_is_none_until_whole() -> None: + assert hydrate_partial(schema=TriageStr, data='ESC', closed=False) is None + assert hydrate_partial(schema=TriageStr, data='ESCALATE', closed=False) is TriageStr.ESCALATE + assert hydrate_partial(schema=Plan, data='PRO', closed=False) is None + assert hydrate_partial(schema=Plan, data='PRO_PLUS', closed=False) is Plan.PRO_PLUS + assert hydrate_partial(schema=Plan, data='PRO', closed=True) is Plan.PRO + + +def test_hydrate_partial_dataclass_stays_raw_until_closed() -> None: + assert hydrate_partial(schema=Vendor, data={'vendor_name': 'Ac'}, closed=False) == {'vendor_name': 'Ac'} + assert hydrate_partial(schema=Vendor, data={'vendor_name': 'Acme', 'risk_score': 1}, closed=True) == Vendor( + vendor_name='Acme', risk_score=1 + ) + + +def test_unwrap_annotated_unwraps_pep695_type_aliases() -> None: + nested = Annotated[VendorListAlias, Field(min_length=1)] + assert unwrap_annotated(annotation=nested) == list[Vendor] + + std_alias_cls = getattr(typing, 'TypeAliasType', None) + if std_alias_cls is not None and sys.version_info >= (3, 12): + ns: dict[str, Any] = {'InvoiceItem': InvoiceItem} + exec('type Items = list[InvoiceItem]\ntype Box[T] = list[T]', ns) # noqa: S102 + assert unwrap_annotated(annotation=ns['Items']) == list[InvoiceItem] + assert unwrap_annotated(annotation=ns['Box'][InvoiceItem]) == list[InvoiceItem] + partial = hydrate_partial(schema=ns['Items'], data=[{'sku': 'CH-1'}], closed=False) + assert partial == [InvoiceItem.model_construct(sku='CH-1', quantity=None)] + + +def test_anchor_type_skips_stdlib_value_modules() -> None: + assert anchor_type(list[uuid.UUID]) is object + assert anchor_type(list[Decimal]) is object + assert anchor_type(list[datetime.datetime]) is object + assert anchor_type(list[pathlib.Path]) is object + assert anchor_type(list[ipaddress.IPv4Address]) is object + assert anchor_type(dict[uuid.UUID, InvoiceItem]) is InvoiceItem + assert anchor_type(VendorListAlias) is Vendor diff --git a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py index 6ed9115ba..9a7dd8f9b 100644 --- a/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py +++ b/packages/genkit/tests/genkit/ai/streaming_typed_output_test.py @@ -144,12 +144,15 @@ def test_non_dict_parse_result_passes_through(self) -> None: assert _chunk('[1, 2, 3]', schema_type=Recipe).output == [1, 2, 3] def test_wrong_typed_value_does_not_raise(self) -> None: - # Failed validation falls back to the raw value instead of crashing - # the caller's loop; the final response surfaces the ValidationError. - out = _chunk('{"title": 123}', schema_type=Recipe).output + # Mid-stream, a wrong-typed value passes through raw instead of + # crashing the caller's loop. + out = _chunk('{"title": 123', schema_type=Recipe).output assert isinstance(out, Recipe) assert out.title == 123 assert out.steps is None + # The closing chunk is validated like the final response: no + # model_construct that skipped validation, just None. + assert _chunk('{"title": 123}', schema_type=Recipe).output is None def test_camel_case_alias_populates_python_field(self) -> None: class UserProfile(BaseModel): @@ -170,12 +173,14 @@ class User(BaseModel): assert isinstance(out, User) assert out.first_name == 'Ada' - def test_root_model_dict_stays_extracted_json(self) -> None: + def test_root_model_hydrates_like_the_final_response(self) -> None: class DictRoot(RootModel[dict[str, int]]): pass - out = _chunk('{"a": 1, "b": 2}', schema_type=DictRoot).output - assert out == {'a': 1, 'b': 2} + open_out = _chunk('{"a": 1, "b": 2', schema_type=DictRoot).output + assert isinstance(open_out, DictRoot) + assert open_out.root == {'a': 1, 'b': 2} + assert _chunk('{"a": 1, "b": 2}', schema_type=DictRoot).output == DictRoot({'a': 1, 'b': 2}) class TestNestedAndConstrainedOutput: @@ -195,13 +200,15 @@ def _capitalized(cls, v: str) -> str: return v out = _chunk( - '{"servings": -5, "rating": 99, "title": "lowercase"}', + '{"servings": -5, "rating": 99, "title": "lowercase"', schema_type=Strict, ).output assert isinstance(out, Strict) assert out.servings == -5 assert out.rating == 99 assert out.title == 'lowercase' + # Once the object closes, the same values fail validation: None. + assert _chunk('{"servings": -5, "rating": 99, "title": "lowercase"}', schema_type=Strict).output is None def test_union_member_is_the_matching_class(self) -> None: class Cat(BaseModel): @@ -214,7 +221,7 @@ class Dog(BaseModel): class Pet(BaseModel): animal: Cat | Dog - out = _chunk('{"animal": {"bark": "woof"}}', schema_type=Pet).output + out = _chunk('{"animal": {"bark": "woof"}', schema_type=Pet).output assert isinstance(out, Pet) assert isinstance(out.animal, Dog) assert out.animal.bark == 'woof' @@ -234,7 +241,7 @@ class Plan(BaseModel): by_id: Mapping[str, Item] out = _chunk( - '{"steps": [{"title": "mix"}], "by_id": {"a": {"name": "axe"}}}', + '{"steps": [{"title": "mix"}], "by_id": {"a": {"name": "axe"}}', schema_type=Plan, ).output assert isinstance(out, Plan) @@ -255,7 +262,7 @@ class Inventory(BaseModel): featured: tuple[Item, ...] out = _chunk( - '{"by_id": {"a": {"name": "axe"}}, "featured": [{"qty": 2}]}', + '{"by_id": {"a": {"name": "axe"}}, "featured": [{"qty": 2}]', schema_type=Inventory, ).output assert isinstance(out, Inventory) @@ -270,7 +277,7 @@ class Node(BaseModel): child: 'Node | None' = None out = _chunk( - '{"name": "root", "child": {"child": {"name": "leaf"}}}', + '{"name": "root", "child": {"child": {"name": "leaf"}}', schema_type=Node, ).output assert isinstance(out, Node) @@ -283,7 +290,7 @@ class Node(BaseModel): def test_mutually_recursive_models(self) -> None: """A quoted sibling in list['Post'] is a Post, with holes as None.""" out = _chunk( - '{"name": "a", "posts": [{"author": {"posts": []}}]}', + '{"name": "a", "posts": [{"author": {"posts": []}}]', schema_type=Author, ).output assert isinstance(out, Author) @@ -359,7 +366,7 @@ def test_half_arrived_deep_child_name_is_prefix(self) -> None: def test_dict_quoted_post_yields_post_instances(self) -> None: """dict[str, 'QuotedItem'] values are QuotedItem, with holes as None.""" out = _chunk( - '{"by_id": {"a": {"name": "axe"}}, "featured": []}', + '{"by_id": {"a": {"name": "axe"}}, "featured": []', schema_type=QuotedInventory, ).output assert isinstance(out, QuotedInventory) @@ -370,7 +377,7 @@ def test_dict_quoted_post_yields_post_instances(self) -> None: def test_tuple_quoted_post_yields_post_instances(self) -> None: """tuple['QuotedItem', ...] values are QuotedItem, with holes as None.""" out = _chunk( - '{"by_id": {}, "featured": [{"qty": 2}]}', + '{"by_id": {}, "featured": [{"qty": 2}]', schema_type=QuotedInventory, ).output assert isinstance(out, QuotedInventory) @@ -381,7 +388,7 @@ def test_tuple_quoted_post_yields_post_instances(self) -> None: def test_list_quoted_self_yields_node_instances(self) -> None: """list['NodeTree'] children are NodeTree, with holes as None.""" out = _chunk( - '{"name": "root", "children": [{"children": [{"name": "leaf"}]}]}', + '{"name": "root", "children": [{"children": [{"name": "leaf"}]}]', schema_type=NodeTree, ).output assert isinstance(out, NodeTree) @@ -394,7 +401,7 @@ def test_list_quoted_self_yields_node_instances(self) -> None: def test_list_quoted_unknown_name_stays_dicts(self) -> None: """A quoted name that is not a model stays extracted JSON; the loop does not crash.""" out = _chunk( - '{"items": [{"name": "x"}]}', + '{"items": [{"name": "x"}]', schema_type=UnknownQuotedList, ).output assert isinstance(out, UnknownQuotedList) @@ -710,15 +717,16 @@ async def test_stream_final_output_is_validated_instance() -> None: @pytest.mark.asyncio async def test_stream_final_output_missing_field_is_none_after_partial_chunks() -> None: - """Chunks showed a Recipe with steps None, but a final reply that never sends steps gives `output is None`.""" + """Open chunks show a Recipe with steps None; a reply that closes without steps is None, chunk and final.""" outputs, response = await _stream_outputs( - ['{"title": "Fluffy Pancakes"}'], + ['{"title": "Fluffy Pancakes"', '}'], '{"title": "Fluffy Pancakes"}', output_schema=Recipe, ) assert isinstance(outputs[0], Recipe) assert outputs[0].steps is None + assert outputs[1] is None assert response.output is None assert response.error is not None @@ -1071,12 +1079,9 @@ def _after_check(self) -> 'Booking': assert (before_calls, after_calls) == (1, 1) assert b4 == Booking(guest='ANN', nights=2, total=200.0) - # If the closed root violates @model_validator, fallback still preserves @field_validator outputs. + # A closed root that violates @model_validator is None, not an unvalidated Booking. b_invalid = _chunk('{"guest": "ann", "nights": 2, "total": 999.0}', schema_type=Booking).output - assert isinstance(b_invalid, Booking) - assert b_invalid.guest == 'ANN' - assert b_invalid.nights == 2 - assert b_invalid.total == 999.0 + assert b_invalid is None def test_open_numbers_and_invalid_closed_enum_match_documented_edge_cases(self) -> None: class EventPayload(BaseModel):