Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/genkit/src/genkit/_ai/_formats/_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 3 additions & 1 deletion packages/genkit/src/genkit/_ai/_formats/_jsonl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
1 change: 1 addition & 0 deletions packages/genkit/src/genkit/_ai/_formats/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 4 additions & 4 deletions packages/genkit/src/genkit/_ai/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
21 changes: 11 additions & 10 deletions packages/genkit/src/genkit/_ai/_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand Down
71 changes: 43 additions & 28 deletions packages/genkit/src/genkit/_core/_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@
Field,
GetJsonSchemaHandler,
PrivateAttr,
RootModel,
TypeAdapter,
ValidationError,
ValidationInfo,
Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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``
Expand All @@ -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()
Expand All @@ -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.

Expand Down
Loading
Loading