diff --git a/packages/genkit-middleware/src/genkit_middleware/_fallback.py b/packages/genkit-middleware/src/genkit_middleware/_fallback.py index a172c0a52..0d54f2f80 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_fallback.py +++ b/packages/genkit-middleware/src/genkit_middleware/_fallback.py @@ -20,20 +20,22 @@ import asyncio import sys -from collections.abc import Awaitable, Callable -from typing import Any, cast +from collections.abc import Awaitable, Callable, Sequence +from typing import Any, cast, overload -from pydantic import Field, field_validator +from pydantic import BaseModel, Field, ValidationError, field_validator from genkit import GenkitError, ModelResponse, ModelResponseChunk from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams from genkit.model import ModelRef, ModelRequest from genkit.plugin_api import Action, GenkitConfig from genkit_middleware._statuses import TRANSIENT_STATUSES +from genkit_middleware._streaming import watch_stream # Everything Retry would retry, plus failures another model may not have: # this model doesn't exist or can't do what the request asks. _DEFAULT_FALLBACK_STATUSES: list[str] = [*TRANSIENT_STATUSES, 'NOT_FOUND', 'UNIMPLEMENTED'] +_UNSET: Any = cast(Any, object()) class FallbackModelEntry(GenkitConfig): @@ -53,7 +55,7 @@ class FallbackConfig(GenkitConfig): @classmethod def coerce_models(cls, value: object) -> object: """A string is the model name; a ref carries that model's own config.""" - if not isinstance(value, list): + if isinstance(value, (str, bytes)) or not isinstance(value, Sequence): return value entries: list[str | FallbackModelEntry | dict[str, Any]] = [] for item in value: @@ -86,19 +88,147 @@ def config_from_ref(model: ModelRef[Any]) -> dict[str, Any] | None: return bag or None -def fallback_request_config(entry: str | FallbackModelEntry) -> dict[str, Any] | None: - """A string entry uses the model's defaults; a ref entry uses only its config.""" - if isinstance(entry, str): +# Generation settings every provider understands (GenerationCommonConfig). +_PORTABLE_CONFIG_KEYS: dict[str, str] = { + 'temperature': 'temperature', + 'max_output_tokens': 'max_output_tokens', + 'maxOutputTokens': 'max_output_tokens', + 'top_k': 'top_k', + 'topK': 'top_k', + 'top_p': 'top_p', + 'topP': 'top_p', + 'stop_sequences': 'stop_sequences', + 'stopSequences': 'stop_sequences', +} + + +def _config_dict(config: object) -> dict[str, Any]: + if isinstance(config, BaseModel): + return config.model_dump(exclude_none=True) + if isinstance(config, dict): + return {k: v for k, v in cast(dict[str, Any], config).items() if v is not None} + return {} + + +def _accepted_keys(schema: object) -> set[str] | None: + """Keys a backup model's config class validates, or None when it has none.""" + if not (isinstance(schema, type) and issubclass(schema, BaseModel)): return None - return entry.config + keys: set[str] = set() + for name, info in schema.model_fields.items(): + keys.add(name) + for alias in (info.alias, info.validation_alias, info.serialization_alias): + if isinstance(alias, str): + keys.add(alias) + return keys + + +def _field_keys(schema: type[BaseModel], field_name: str) -> set[str]: + """Return the field name and any string aliases for ``field_name``.""" + keys = {field_name} + info = schema.model_fields.get(field_name) + if info is not None: + for alias in (info.alias, info.validation_alias, info.serialization_alias): + if isinstance(alias, str): + keys.add(alias) + return keys + + +def _drop_invalid_fields(narrowed: dict[str, Any], schema: type[BaseModel]) -> dict[str, Any]: + """Drop inherited keys that fail the backup's own bounds or type checks.""" + remaining = dict(narrowed) + while remaining: + try: + schema.model_validate(remaining) + return remaining + except ValidationError as exc: + to_drop: set[str] = set() + for err in exc.errors(): + loc = err.get('loc') + if loc: + to_drop.update(_field_keys(schema, str(loc[0]))) + matched = to_drop & remaining.keys() + if not matched: + return {} + for key in matched: + remaining.pop(key, None) + return remaining + + +def inherited_config(primary: object, backup_schema: object) -> dict[str, Any]: + """The caller's config, narrowed to what the backup model accepts. + + Keys the backup's config class declares carry over when they also satisfy + the backup's own validation (for example, ``temperature=1.5`` is dropped + for a backup declaring ``le=1.0``). A backup with no config class gets + only the portable generation keys, so a provider-specific key + (``safety_settings``) does not fail validation. ``version`` and ``extra`` + belong to the primary's provider, so they never carry over. + """ + source = _config_dict(primary) + # version names the primary's model; extra is that provider's passthrough. + source.pop('version', None) + source.pop('extra', None) + if isinstance(backup_schema, type) and issubclass(backup_schema, BaseModel): + accepted = _accepted_keys(backup_schema) or set() + narrowed = {k: v for k, v in source.items() if k in accepted} + return _drop_invalid_fields(narrowed, backup_schema) + return {_PORTABLE_CONFIG_KEYS[k]: v for k, v in source.items() if k in _PORTABLE_CONFIG_KEYS} + + +def fallback_request_config( + entry: str | FallbackModelEntry, + *, + primary: object = None, + backup_schema: object = None, +) -> dict[str, Any] | None: + """A ref entry with config uses only that config; any other entry inherits the caller's. + + Matches JS: ``normalizedModel.config ?? req.config``, narrowed so the + backup model can validate it. + """ + if isinstance(entry, FallbackModelEntry) and entry.config is not None: + return entry.config + return inherited_config(primary, backup_schema) or None class Fallback(Middleware[FallbackConfig]): - """Fallback middleware to try alternative models on failure.""" + """Fallback middleware to try alternative models on failure. + + A backup named by string, or a ``ModelRef`` with no config or version, + inherits the caller's config, narrowed to keys the backup accepts; a + ``ModelRef`` with config uses only that config. Once + an attempt has streamed chunks, its failure is raised rather than failed + over. Backups run directly, not through middleware listed after + ``Fallback``, so ``use=[Fallback(...), Retry(...)]`` retries only the + primary; ``use=[Retry(...), Fallback(...)]`` retries the whole sequence. + """ name = 'fallback' description = 'Falls back to alternative models on failure' + @overload + def __init__( + self, + *, + models: Sequence[str | ModelRef[Any] | FallbackModelEntry | dict[str, Any]] = ..., + statuses: Sequence[str] = ..., + ) -> None: ... + + @overload + def __init__(self, *, config: FallbackConfig) -> None: ... + + def __init__( + self, + *, + models: Sequence[str | ModelRef[Any] | FallbackModelEntry | dict[str, Any]] = _UNSET, + statuses: Sequence[str] = _UNSET, + config: FallbackConfig | None = None, + **kwargs: Any, # noqa: ANN401 + ) -> None: + fields = {k: v for k, v in (('models', models), ('statuses', statuses)) if v is not _UNSET} + super().__init__(config=config, **fields, **kwargs) + async def _resolve_fallback_model( self, ctx: MiddlewareContext, @@ -122,14 +252,16 @@ async def wrap_model( """Try the primary model, then fall back to alternates on retryable errors.""" last_error: Exception | None = None try: - return await next_fn(params, ctx) + with watch_stream(ctx) as stream: + return await next_fn(params, ctx) except Exception as exc: - if not self._should_fall_back(exc): + # Once chunks reached the caller, a backup's answer would be + # spliced onto the failed one; surface the failure instead. + if stream.committed or not self._should_fall_back(exc): raise last_error = exc assert last_error is not None # noqa: S101 - on_chunk = ctx.on_chunk for entry in self.config.models: model_name = entry if isinstance(entry, str) else entry.name fallback_action = await self._resolve_fallback_model(ctx, model_name) @@ -137,19 +269,21 @@ async def wrap_model( # it into its own class like any other call. A copy of the primary's # typed request would pass a dict straight through when both models # share a config class. - fallback_request = ModelRequest.model_validate( - {**dict(params.request), 'config': fallback_request_config(entry) or {}}, + config = fallback_request_config( + entry, primary=params.request.config, backup_schema=fallback_action.config_schema ) + fallback_request = ModelRequest.model_validate({**dict(params.request), 'config': config or {}}) try: - result = await fallback_action._run( - input=fallback_request, - context=ctx.context, - on_chunk=on_chunk, - ) + with watch_stream(ctx) as stream: + result = await fallback_action._run( + input=fallback_request, + context=ctx.context, + on_chunk=ctx.on_chunk, + ) return result.response # type: ignore[return-value] except Exception as e2: last_error = e2 - if not self._should_fall_back(e2): + if stream.committed or not self._should_fall_back(e2): raise raise last_error diff --git a/packages/genkit-middleware/src/genkit_middleware/_filesystem.py b/packages/genkit-middleware/src/genkit_middleware/_filesystem.py index e6b590c2e..a05472d3d 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_filesystem.py +++ b/packages/genkit-middleware/src/genkit_middleware/_filesystem.py @@ -28,9 +28,9 @@ path redacted, so the model can self-correct without a user turn landing between the tool response and the next model turn. -Each ``generate()`` gets a fresh middleware instance with its own message -queue; ``wrap_generate`` drains queued messages into the request before the -next model call. +Each ``generate()`` gets a per-call copy of the middleware with its own +message queue; ``wrap_generate`` drains queued messages into the request +before the next model call. """ from __future__ import annotations @@ -44,7 +44,7 @@ import stat from collections.abc import Awaitable, Callable from pathlib import Path -from typing import Any +from typing import Any, cast, overload from pydantic import AliasChoices, BaseModel as PydanticBaseModel, Field @@ -109,6 +109,7 @@ class _EditFileInput(PydanticBaseModel): _MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024 # 10 MB — absolute ceiling for reading _MAX_READ_SLICE_BYTES = 256 * 1024 # 256 KB — max bytes returned per slice +_UNSET: Any = cast(Any, object()) def _attr_text(value: str) -> str: @@ -148,13 +149,51 @@ class Filesystem(Middleware[FilesystemConfig]): name = 'filesystem' description = 'Sandboxed filesystem operations' - def __init__(self, **kwargs: Any) -> None: # noqa: ANN401 - super().__init__(**kwargs) + @overload + def __init__( + self, + *, + root_dir: str, + allow_write_access: bool = False, + tool_name_prefix: str = '', + ) -> None: ... + + @overload + def __init__(self, *, config: FilesystemConfig) -> None: ... + + def __init__( + self, + *, + root_dir: str = _UNSET, + allow_write_access: bool = _UNSET, + tool_name_prefix: str = _UNSET, + config: FilesystemConfig | None = None, + **kwargs: Any, # noqa: ANN401 + ) -> None: + fields = { + k: v + for k, v in ( + ('root_dir', root_dir), + ('allow_write_access', allow_write_access), + ('tool_name_prefix', tool_name_prefix), + ) + if v is not _UNSET + } + super().__init__(config=config, **fields, **kwargs) if not self.config.root_dir or not self.config.root_dir.strip(): raise ValueError('Filesystem.root_dir must not be empty.') # One queue per generate() — the engine copies middleware per call. self._message_queue: list[Message] = [] + def __copy__(self) -> Filesystem: + # The engine shallow-copies middleware per generate(); without a new + # list, concurrent calls on one instance would share queued file + # contents and inject one request's reads into another's turn. + clone = type(self).__new__(type(self)) + clone.__dict__.update(self.__dict__) + clone._message_queue = [] + return clone + @property def _root_abs(self) -> str: return str(Path(self.config.root_dir).resolve()) diff --git a/packages/genkit-middleware/src/genkit_middleware/_retry.py b/packages/genkit-middleware/src/genkit_middleware/_retry.py index acfa10cc9..1760cbfac 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_retry.py +++ b/packages/genkit-middleware/src/genkit_middleware/_retry.py @@ -22,7 +22,8 @@ import math import random import sys -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence +from typing import Any, cast, overload from pydantic import Field @@ -30,9 +31,11 @@ from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams from genkit.plugin_api import GenkitConfig from genkit_middleware._statuses import TRANSIENT_STATUSES +from genkit_middleware._streaming import watch_stream _DEFAULT_RETRY_STATUSES: list[str] = list(TRANSIENT_STATUSES) _sleep = asyncio.sleep +_UNSET: Any = cast(Any, object()) class RetryConfig(GenkitConfig): @@ -52,6 +55,47 @@ class Retry(Middleware[RetryConfig]): name = 'retry' description = 'Retries model calls on transient failures with exponential backoff' + @overload + def __init__( + self, + *, + max_retries: int = 3, + statuses: Sequence[str] = ..., + initial_delay_ms: int = 1000, + max_delay_ms: int = 60000, + backoff_factor: float = 2.0, + no_jitter: bool = False, + ) -> None: ... + + @overload + def __init__(self, *, config: RetryConfig) -> None: ... + + def __init__( + self, + *, + max_retries: int = _UNSET, + statuses: Sequence[str] = _UNSET, + initial_delay_ms: int = _UNSET, + max_delay_ms: int = _UNSET, + backoff_factor: float = _UNSET, + no_jitter: bool = _UNSET, + config: RetryConfig | None = None, + **kwargs: Any, # noqa: ANN401 + ) -> None: + fields = { + k: v + for k, v in ( + ('max_retries', max_retries), + ('statuses', statuses), + ('initial_delay_ms', initial_delay_ms), + ('max_delay_ms', max_delay_ms), + ('backoff_factor', backoff_factor), + ('no_jitter', no_jitter), + ) + if v is not _UNSET + } + super().__init__(config=config, **fields, **kwargs) + async def wrap_model( self, params: ModelHookParams, @@ -63,13 +107,18 @@ async def wrap_model( for attempt in range(self.config.max_retries + 1): try: - return await next_fn(params, ctx) + with watch_stream(ctx) as stream: + return await next_fn(params, ctx) except Exception as e: curr = asyncio.current_task() if curr is not None and sys.version_info >= (3, 11) and curr.cancelling() > 0: raise if attempt == self.config.max_retries: raise + # The caller already has part of this answer; a retry would + # append a second one to it. + if stream.committed: + raise # A GenkitError is retried only when its status is listed. Any # other exception is retried. diff --git a/packages/genkit-middleware/src/genkit_middleware/_skills.py b/packages/genkit-middleware/src/genkit_middleware/_skills.py index d9307a409..ceb373f94 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_skills.py +++ b/packages/genkit-middleware/src/genkit_middleware/_skills.py @@ -33,9 +33,9 @@ import stat import unicodedata import weakref -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence from pathlib import Path -from typing import Any +from typing import Any, cast, overload import yaml from pydantic import BaseModel as PydanticBaseModel, Field @@ -62,6 +62,7 @@ _O_NOFOLLOW = getattr(os, 'O_NOFOLLOW', 0) _O_NONBLOCK = getattr(os, 'O_NONBLOCK', 0) +_UNSET: Any = cast(Any, object()) class _UseSkillInput(PydanticBaseModel): @@ -151,6 +152,26 @@ class Skills(Middleware[SkillsConfig]): description = 'Provides access to skill library for specialized instructions' _cached_scan: tuple[weakref.ref[MiddlewareContext], dict[str, dict[str, str]]] | None = None + @overload + def __init__( + self, + *, + skill_paths: Sequence[str] = ..., + ) -> None: ... + + @overload + def __init__(self, *, config: SkillsConfig) -> None: ... + + def __init__( + self, + *, + skill_paths: Sequence[str] = _UNSET, + config: SkillsConfig | None = None, + **kwargs: Any, # noqa: ANN401 + ) -> None: + fields = {'skill_paths': skill_paths} if skill_paths is not _UNSET else {} + super().__init__(config=config, **fields, **kwargs) + def _scan_skills(self) -> dict[str, dict[str, str]]: skills: dict[str, dict[str, str]] = {} for path_str in self.config.skill_paths: diff --git a/packages/genkit-middleware/src/genkit_middleware/_streaming.py b/packages/genkit-middleware/src/genkit_middleware/_streaming.py new file mode 100644 index 000000000..4d45e1c66 --- /dev/null +++ b/packages/genkit-middleware/src/genkit_middleware/_streaming.py @@ -0,0 +1,74 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Track whether a model attempt already streamed chunks to the caller.""" + +from __future__ import annotations + +import contextlib +from collections.abc import Callable, Iterator +from typing import cast + +from genkit import ModelResponseChunk +from genkit.middleware import MiddlewareContext + + +class StreamWatch: + """Counts chunks one model attempt sent downstream.""" + + __slots__ = ('chunks',) + + def __init__(self) -> None: + self.chunks = 0 + + @property + def committed(self) -> bool: + """True once the caller has seen part of this attempt's answer.""" + return self.chunks > 0 + + +@contextlib.contextmanager +def watch_stream(ctx: MiddlewareContext) -> Iterator[StreamWatch]: + """Count chunks sent through ``ctx`` while the block runs. + + Retrying or failing over after chunks reached the caller would splice a + second answer onto a partial first one, so callers check ``committed``. + """ + watch = StreamWatch() + inner = ctx.on_chunk + if inner is None: + yield watch + return + + def counting(chunk: ModelResponseChunk) -> None: + inner(chunk) + watch.chunks += 1 + + # Preserve _EngineOnChunk so engine stamping errors stay retryable Exceptions + # rather than being wrapped in _GuardedOnChunk (STREAM_CALLBACK_FAILED). + wrapper = ( + cast( + Callable[[Callable[[ModelResponseChunk], None]], Callable[[ModelResponseChunk], None]], + type(inner), + )(counting) + if type(inner).__name__ in ('_EngineOnChunk', '_GuardedOnChunk') + else counting + ) + previous = ctx.replace_on_chunk(wrapper) + try: + yield watch + finally: + ctx.replace_on_chunk(previous) diff --git a/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py b/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py index 8e0a82316..4d6c7a1ce 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py +++ b/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py @@ -18,7 +18,8 @@ from __future__ import annotations -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Sequence +from typing import Any, cast, overload from pydantic import Field @@ -27,6 +28,8 @@ from genkit.plugin_api import ActionKind, GenkitConfig from genkit.telemetry import SpanContext, run_in_new_span +_UNSET: Any = cast(Any, object()) + class ToolApprovalConfig(GenkitConfig): """Tools that may run without an approval interrupt.""" @@ -40,6 +43,26 @@ class ToolApproval(Middleware[ToolApprovalConfig]): name = 'tool_approval' description = 'Requires approval before executing tools' + @overload + def __init__( + self, + *, + allowed_tools: Sequence[str] = ..., + ) -> None: ... + + @overload + def __init__(self, *, config: ToolApprovalConfig) -> None: ... + + def __init__( + self, + *, + allowed_tools: Sequence[str] = _UNSET, + config: ToolApprovalConfig | None = None, + **kwargs: Any, # noqa: ANN401 + ) -> None: + fields = {'allowed_tools': allowed_tools} if allowed_tools is not _UNSET else {} + super().__init__(config=config, **fields, **kwargs) + async def wrap_tool( self, params: ToolHookParams, diff --git a/packages/genkit-middleware/tests/exports_test.py b/packages/genkit-middleware/tests/exports_test.py new file mode 100644 index 000000000..68426ed84 --- /dev/null +++ b/packages/genkit-middleware/tests/exports_test.py @@ -0,0 +1,87 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Public surface of ``genkit_middleware``, typed constructors, and wrong-class plugin error.""" + +from pathlib import Path + +import genkit_middleware +import pytest +from genkit_middleware import ( + Fallback, + Filesystem, + Middleware, + Retry, + Skills, + ToolApproval, +) +from genkit_middleware._fallback import FallbackConfig, FallbackModelEntry +from genkit_middleware._filesystem import FilesystemConfig +from genkit_middleware._retry import RetryConfig +from genkit_middleware._skills import SkillsConfig +from genkit_middleware._tool_approval import ToolApprovalConfig + +from genkit import Genkit + + +def test_public_exports_stay_tight() -> None: + """``genkit_middleware`` exports only the plugin and middleware classes, not internal Config types.""" + assert set(genkit_middleware.__all__) == { + 'Fallback', + 'Filesystem', + 'Middleware', + 'Retry', + 'Skills', + 'ToolApproval', + } + assert Middleware().name == 'genkit-middleware' + + +def test_typed_keyword_and_config_constructors(tmp_path: Path) -> None: + """Each shipped middleware accepts typed keyword arguments and ``config=``, rejecting both together.""" + retry = Retry(max_retries=5, initial_delay_ms=250, max_delay_ms=5000, backoff_factor=1.5, no_jitter=True) + assert retry.config.max_retries == 5 + assert retry.config.no_jitter is True + assert Retry(config=RetryConfig(max_retries=2)).config.max_retries == 2 + with pytest.raises(TypeError, match='pass either config= or keyword config fields'): + Retry(config=RetryConfig(max_retries=2), max_retries=5) # type: ignore[call-overload] + + entry = FallbackModelEntry(name='googleai/gemini-flash-lite-latest', config={'temperature': 0}) + fallback = Fallback(models=['googleai/gemini-pro-latest', entry], statuses=['UNAVAILABLE']) + assert len(fallback.config.models) == 2 + assert Fallback(config=FallbackConfig(models=['backup'])).config.models == ['backup'] + + fs = Filesystem(root_dir=str(tmp_path), allow_write_access=True, tool_name_prefix='ws_') + assert fs.config.allow_write_access is True + assert fs.config.tool_name_prefix == 'ws_' + assert Filesystem(config=FilesystemConfig(root_dir=str(tmp_path))).config.root_dir == str(tmp_path) + + skills = Skills(skill_paths=[str(tmp_path)]) + assert skills.config.skill_paths == [str(tmp_path)] + assert Skills(config=SkillsConfig(skill_paths=[str(tmp_path)])).config.skill_paths == [str(tmp_path)] + + approval = ToolApproval(allowed_tools=['check_allergens']) + assert approval.config.allowed_tools == ['check_allergens'] + assert ToolApproval(config=ToolApprovalConfig(allowed_tools=['check_allergens'])).config.allowed_tools == [ + 'check_allergens' + ] + + +def test_middleware_class_in_plugins_names_plugin_api() -> None: + with pytest.raises(ValueError, match=r'genkit\.plugin_api\.Plugin') as exc: + Genkit(plugins=[Retry()]) # pyright: ignore[reportArgumentType] + assert 'genkit.ai.Plugin' not in str(exc.value) + assert 'genkit_middleware.Middleware()' in str(exc.value) diff --git a/packages/genkit-middleware/tests/fallback_test.py b/packages/genkit-middleware/tests/fallback_test.py index a33005fae..218a9744a 100644 --- a/packages/genkit-middleware/tests/fallback_test.py +++ b/packages/genkit-middleware/tests/fallback_test.py @@ -114,7 +114,7 @@ class ThinkingConfig(ModelConfig): @pytest.mark.asyncio async def test_fallback_to_other_model_sends_only_the_entry_config() -> None: - """When the primary fails, a string backup runs with that model's defaults — no thinkingConfig.""" + """A string backup inherits the keys its config class accepts (temperature), not thinkingConfig.""" ai = Genkit() seen: list[object] = [] @@ -144,7 +144,7 @@ async def backup(request: ModelRequest, _ctx: ModelContext) -> ModelResponse: assert len(seen) == 1 assert _config_value(seen[0], 'thinkingConfig') is None assert _config_value(seen[0], 'thinking_config') is None - assert _config_value(seen[0], 'temperature') is None + assert _config_value(seen[0], 'temperature') == 0.2 assert _config_value(seen[0], 'version') is None assert _config_value(seen[0], 'extra') is None @@ -211,12 +211,15 @@ async def backup(request: ModelRequest, _ctx: ModelContext) -> ModelResponse: ('entry', 'temperature'), [ (ModelRef(name='backup', config_schema=ThinkingConfig, config=ThinkingConfig(temperature=0.2)), 0.2), - ('backup', None), + ('backup', 0.9), ], ids=['ref_entry', 'string_entry'], ) async def test_fallback_backup_with_same_config_class_gets_that_class(entry: object, temperature: float | None) -> None: - """A backup that shares the primary's config class gets a ThinkingConfig, not a dict or None.""" + """A backup that shares the primary's config class gets a ThinkingConfig. + + A ref entry runs with its own config; a string entry inherits the caller's. + """ ai = Genkit() seen: list[object] = [] @@ -651,3 +654,148 @@ async def backup(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: assert final.finish_reason == FinishReason.ABORTED assert final.error is not None assert final.error.status == 'CANCELLED' + + +@pytest.mark.asyncio +async def test_fallback_string_entry_keeps_portable_caller_config() -> None: + """`max_output_tokens` survives a failover to a backup with no config class.""" + ai = Genkit() + seen: list[object] = [] + + async def primary(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + raise GenkitError(status='UNAVAILABLE', message='down') + + async def backup(request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + seen.append(request.config) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) + + ai.define_model(name='gem', fn=primary, config_schema=ThinkingConfig) + ai.define_model(name='plain', fn=backup) + + await ai.generate( + model='gem', + prompt='hi', + config={'maxOutputTokens': 64, 'temperature': 0.1, 'thinkingConfig': {'thinkingBudget': 0}}, + use=[Fallback(models=['plain'])], + ) + + assert _config_value(seen[0], 'max_output_tokens') == 64 + assert _config_value(seen[0], 'temperature') == 0.1 + assert _config_value(seen[0], 'thinkingConfig') is None + assert _config_value(seen[0], 'thinking_config') is None + + +@pytest.mark.asyncio +async def test_fallback_does_not_fail_over_after_chunks_reached_the_caller() -> None: + """Mid-stream failure surfaces instead of splicing the backup's answer onto partial JSON.""" + ai = Genkit() + backup_calls = 0 + + async def primary(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('{"dish": "Sal')])) + raise GenkitError(status='UNAVAILABLE', message='RST_STREAM') + + async def backup(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + nonlocal backup_calls + backup_calls += 1 + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('{"dish": "Tartine"}')])) + + ai.define_model(name='primary', fn=primary) + ai.define_model(name='backup', fn=backup) + + chunks: list[str] = [] + try: + async with ai.generate_stream(model='primary', prompt='hi', use=[Fallback(models=['backup'])]) as stream: + async for c in stream: + chunks.append(c.text) + response = await stream.response + assert response.finish_reason == FinishReason.FAILED + except GenkitError as e: + assert 'RST_STREAM' in str(e) + + assert chunks == ['{"dish": "Sal'] + assert backup_calls == 0 + + +@pytest.mark.asyncio +async def test_fallback_before_first_chunk_streams_the_backup() -> None: + ai = Genkit() + + async def primary(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + raise GenkitError(status='UNAVAILABLE', message='503') + + async def backup(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('Tartine')])) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('Tartine')])) + + ai.define_model(name='primary', fn=primary) + ai.define_model(name='backup', fn=backup) + + async with ai.generate_stream(model='primary', prompt='hi', use=[Fallback(models=['backup'])]) as stream: + chunks = [c.text async for c in stream] + response = await stream.response + + assert chunks == ['Tartine'] + assert response.text == 'Tartine' + + +@pytest.mark.asyncio +async def test_fallback_drops_inherited_keys_exceeding_backup_bounds() -> None: + """Out-of-bounds inherited keys (e.g. temperature=1.5 vs le=1.0) are dropped so backup runs.""" + + class PrimaryConfig(ModelConfig): + temperature: float | None = Field(default=None, ge=0.0, le=2.0) + + class BackupConfig(ModelConfig): + temperature: float | None = Field(default=None, ge=0.0, le=1.0) + + ai = Genkit() + seen: list[object] = [] + + async def primary(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + raise GenkitError(status='UNAVAILABLE', message='503') + + async def backup(request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + seen.append(request.config) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) + + ai.define_model(name='primary', fn=primary, config_schema=PrimaryConfig) + ai.define_model(name='backup', fn=backup, config_schema=BackupConfig) + + response = await ai.generate( + model='primary', + prompt='hi', + config={'temperature': 1.5, 'max_output_tokens': 128}, + use=[Fallback(models=['backup'])], + ) + + assert response.text == 'ok' + assert _config_value(seen[0], 'temperature') is None + assert _config_value(seen[0], 'max_output_tokens') == 128 + + +@pytest.mark.asyncio +async def test_fallback_accepts_tuple_of_model_refs() -> None: + """A tuple of ModelRef satisfies the Sequence overload and coerces cleanly.""" + ai = Genkit() + seen: list[object] = [] + + async def primary(_request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + raise GenkitError(status='UNAVAILABLE', message='503') + + async def backup(request: ModelRequest, _ctx: ModelContext) -> ModelResponse: + seen.append(request.config) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('ok')])) + + ai.define_model(name='primary', fn=primary, config_schema=ModelConfig) + ai.define_model(name='backup', fn=backup, config_schema=ModelConfig) + ref = ModelRef(name='backup', config_schema=ModelConfig, config=ModelConfig(temperature=0.2)) + + response = await ai.generate( + model='primary', + prompt='hi', + use=[Fallback(models=(ref,))], + ) + + assert response.text == 'ok' + assert _config_value(seen[0], 'temperature') == 0.2 diff --git a/packages/genkit-middleware/tests/filesystem_test.py b/packages/genkit-middleware/tests/filesystem_test.py index b3894274c..c396cde29 100644 --- a/packages/genkit-middleware/tests/filesystem_test.py +++ b/packages/genkit-middleware/tests/filesystem_test.py @@ -16,6 +16,7 @@ """Tests for Filesystem middleware.""" +import copy import tempfile from pathlib import Path @@ -278,3 +279,18 @@ def test_fifo_is_hidden_from_list_files_and_rejected_by_write_without_blocking(t fs._read_file_impl('kitchen.pipe', 0, 0) with pytest.raises(ValueError, match='Cannot write to non-regular file'): fs._write_file_impl('kitchen.pipe', 'blocked forever if opened') + + +def test_per_call_copies_do_not_share_the_message_queue() -> None: + """Two generate() calls reusing one instance must not see each other's file reads.""" + with tempfile.TemporaryDirectory() as tmpdir: + fs = Filesystem(root_dir=tmpdir) + # The engine shallow-copies middleware once per generate() call. + first_call = copy.copy(fs) + second_call = copy.copy(fs) + + first_call._enqueue_parts([Part.from_text('contents of allergens.csv')]) # noqa: SLF001 + + assert second_call._message_queue == [] # noqa: SLF001 + assert fs._message_queue == [] # noqa: SLF001 + assert second_call.config is fs.config diff --git a/packages/genkit-middleware/tests/retry_test.py b/packages/genkit-middleware/tests/retry_test.py index 6e53f5342..18bec2052 100644 --- a/packages/genkit-middleware/tests/retry_test.py +++ b/packages/genkit-middleware/tests/retry_test.py @@ -533,32 +533,58 @@ async def test_retry_generate_stream_break_during_backoff_stops_immediately() -> async def flaky(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: nonlocal call_count call_count += 1 - ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('partial')])) + # No chunk: an attempt that streamed would not be retried at all. first_failed.set() raise GenkitError(message='Service unavailable', status='UNAVAILABLE') ai.define_model(name='flaky', fn=flaky) started = time.monotonic() - seen: list[str] = [] async with ai.generate_stream( model='flaky', prompt='hi', use=[Retry(max_retries=3, initial_delay_ms=30_000, no_jitter=True)], ) as stream: - async for chunk in stream: - seen.append(chunk.text) - await asyncio.wait_for(first_failed.wait(), timeout=2.0) - await asyncio.sleep(0.01) - break + await asyncio.wait_for(first_failed.wait(), timeout=2.0) + await asyncio.sleep(0.01) response = await asyncio.wait_for(stream.response, timeout=2.0) assert time.monotonic() - started < 2 - assert seen == ['partial'] assert call_count == 1 assert response.finish_reason == FinishReason.ABORTED +@pytest.mark.asyncio +async def test_retry_does_not_retry_after_chunks_reached_the_caller() -> None: + """A mid-stream failure surfaces; a retry would splice a second answer onto the first.""" + ai = Genkit() + call_count = 0 + + async def flaky(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + nonlocal call_count + call_count += 1 + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('{"dish": "Sal')])) + raise GenkitError(message='RST_STREAM', status='UNAVAILABLE') + + ai.define_model(name='flaky', fn=flaky) + + seen: list[str] = [] + # Boxed on main; raises once the D1 error contract lands. Either way, one call. + try: + async with ai.generate_stream( + model='flaky', prompt='hi', use=[Retry(max_retries=3, initial_delay_ms=1, no_jitter=True)] + ) as stream: + async for chunk in stream: + seen.append(chunk.text) + response = await stream.response + assert response.finish_reason == FinishReason.FAILED + except GenkitError as e: + assert 'RST_STREAM' in str(e) + + assert call_count == 1 + assert seen == ['{"dish": "Sal'] + + @pytest.mark.asyncio async def test_retry_waits_out_the_backoff_when_caller_has_not_stopped( ctx: MiddlewareContext, @@ -760,3 +786,50 @@ async def next_fn(_params: ModelHookParams, _ctx: MiddlewareContext) -> ModelRes assert time.monotonic() - started < 2 assert call_count == 1 assert err.value.status == 'UNAVAILABLE' + + +@pytest.mark.asyncio +async def test_retry_retries_when_provider_chunk_fails_stamping() -> None: + """A bad provider chunk that fails stamping stays retryable rather than becoming STREAM_CALLBACK_FAILED.""" + ai = Genkit() + calls = 0 + + async def flaky_chunk(_request: ModelRequest, ctx: ModelContext) -> ModelResponse: + nonlocal calls + calls += 1 + if calls == 1: + # Malformed chunk fails stamping inside the engine's _EngineOnChunk wrapper. + ctx.send_chunk(ModelResponseChunk.model_construct(content=12345)) # type: ignore[arg-type] + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('ok')])) + return ModelResponse( + finish_reason=FinishReason.STOP, + message=Message(role=Role.MODEL, content=[Part.from_text('ok')]), + ) + + ai.define_model(name='flaky_chunk', fn=flaky_chunk) + + stream = ai.generate_stream( + model='flaky_chunk', + prompt='hi', + use=[Retry(max_retries=2, initial_delay_ms=0, no_jitter=True)], + ) + chunks = [chunk.text async for chunk in stream] + response = await stream.response + + assert calls == 2 + assert chunks == ['ok'] + assert response.text == 'ok' + + +def test_watch_stream_does_not_mark_committed_when_inner_chunk_raises() -> None: + """watch_stream only marks a chunk committed after inner(chunk) returns.""" + from genkit_middleware._streaming import watch_stream + + def failing_inner(_chunk: ModelResponseChunk) -> None: + raise RuntimeError('stamp failed') + + ctx = MiddlewareContext(Genkit(), on_chunk=failing_inner) + with watch_stream(ctx) as watch: + with pytest.raises(BaseException, match='stamp failed'): + ctx.send_chunk(ModelResponseChunk(role=Role.MODEL, content=[Part.from_text('x')])) + assert not watch.committed diff --git a/packages/genkit-middleware/tests/typecheck/middleware_constructor_test.py b/packages/genkit-middleware/tests/typecheck/middleware_constructor_test.py new file mode 100644 index 000000000..07ca27cf2 --- /dev/null +++ b/packages/genkit-middleware/tests/typecheck/middleware_constructor_test.py @@ -0,0 +1,77 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Type-checker contract for shipped middleware constructors in ``genkit_middleware``. + +pyright, pyrefly, and ty include ``packages/*/tests/typecheck/`` with strict +argument, overload, and unused-ignore checks enabled. +""" + +from pathlib import Path + +from genkit_middleware import Fallback, Filesystem, Retry, Skills, ToolApproval +from genkit_middleware._fallback import FallbackConfig +from genkit_middleware._filesystem import FilesystemConfig +from genkit_middleware._retry import RetryConfig +from genkit_middleware._skills import SkillsConfig +from genkit_middleware._tool_approval import ToolApprovalConfig +from typing_extensions import assert_type + +from genkit.middleware import Middleware +from genkit.model import ModelConfig, ModelRef + + +class _MenuModelConfig(ModelConfig): + pass + + +def test_middleware_keyword_constructors_typecheck(tmp_path: Path) -> None: + """Callers get typed keyword constructors without importing separate Config classes.""" + backup_ref = ModelRef( + name='bistro/backup', + config_schema=_MenuModelConfig, + config=_MenuModelConfig(temperature=0.2), + ) + + retry = Retry(max_retries=3, statuses=['UNAVAILABLE'], initial_delay_ms=250, no_jitter=True) + fallback = Fallback(models=['bistro/primary', backup_ref], statuses=['UNAVAILABLE']) + filesystem = Filesystem(root_dir=str(tmp_path), allow_write_access=True, tool_name_prefix='ws_') + skills = Skills(skill_paths=[str(tmp_path)]) + approval = ToolApproval(allowed_tools=['check_allergens']) + + assert_type(retry, Retry) + assert_type(fallback, Fallback) + assert_type(filesystem, Filesystem) + assert_type(skills, Skills) + assert_type(approval, ToolApproval) + + use_list: list[Middleware] = [retry, fallback, filesystem, skills, approval] + assert len(use_list) == 5 + + +def test_middleware_config_constructors_typecheck(tmp_path: Path) -> None: + """Explicit ``config=`` construction keeps working alongside keyword fields.""" + assert_type(Retry(config=RetryConfig(max_retries=2)), Retry) + assert_type(Fallback(config=FallbackConfig(models=['bistro/backup'])), Fallback) + assert_type(Filesystem(config=FilesystemConfig(root_dir=str(tmp_path))), Filesystem) + assert_type(Skills(config=SkillsConfig(skill_paths=[str(tmp_path)])), Skills) + assert_type(ToolApproval(config=ToolApprovalConfig(allowed_tools=['check_allergens'])), ToolApproval) + + +def _negative_contract_typos_and_missing_root_are_static_errors() -> None: + """Misspelled kwargs and missing required ``root_dir`` fail pyright, pyrefly, and ty.""" + Retry(max_retry=3) # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] + Filesystem() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[no-matching-overload] diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index cd8d47ec7..2bfbaf782 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -1237,7 +1237,11 @@ def _initialize_registry(self, model: ModelArg | None, plugins: list[Plugin] | N if isinstance(plugin, Plugin): # pyright: ignore[reportUnnecessaryIsInstance] self._registry.register_plugin(plugin) else: - raise ValueError(f'Invalid {plugin=} provided to Genkit: must be of type `genkit.ai.Plugin`') + raise ValueError( + f'Invalid {plugin=} provided to Genkit: must be a `genkit.plugin_api.Plugin` instance. ' + 'Middleware classes such as `genkit.middleware.Middleware` subclasses go in `use=[...]`; ' + 'register the `genkit_middleware.Middleware()` plugin in `plugins=[...]`.' + ) def _register_plugin_middleware(self, plugins: list[Plugin] | None) -> None: """Register middleware classes returned by ``Plugin.list_middleware``.""" diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 6b7b9d867..595376a54 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -285,16 +285,21 @@ def register_middleware( ) -> list[MiddlewareRef] | None: """Normalize ``use=`` to ``MiddlewareRef`` entries (name + config only). - Inline ``Middleware`` instances are not stored on the registry. Their - config is serialized onto the ref and, when the class is not registered on - a parent registry, a ``_MiddlewareMetadata`` is registered on this layer so - ``resolve_middleware_from_use`` can build a fresh instance per ``generate()``. + Inline ``Middleware`` instances keep their config on the ref for traces + and the Dev UI. When the class is not registered on a parent registry, a + ``_MiddlewareMetadata`` is registered on this layer under a synthetic + name. The instances themselves are stored on this layer so + ``resolve_middleware_from_use`` hands back the caller's instance instead + of rebuilding it from the serialized config. """ if use is None: return None refs: list[MiddlewareRef] = [] # Build the class→name index once so resolving the use list is O(M+N). cls_index = middleware_class_index(registry) + # (ref name, instance) per entry, so resolve can hand back the caller's + # instance instead of rebuilding it from serialized config. + inline: list[tuple[str, Middleware | None]] = [] for i, entry in enumerate(use): if isinstance(entry, Middleware): # Prefer the registered name so traces show ``concise_reply_mw`` @@ -303,8 +308,8 @@ def register_middleware( # with any globally registered middleware. mw_cls = type(entry) registered = cls_index.get(mw_cls) - # Each ref carries its own config and resolves to a fresh instance, - # so the same registered name can appear more than once. + # Each entry keeps its own instance and ref, so the same + # registered name can appear more than once. reg_name = registered or f'dynamic-middleware-{i}-{secrets.token_hex(5)}' if registered is None: registry.register_value( @@ -313,26 +318,60 @@ def register_middleware( mw_cls._middleware_metadata(reg_name), ) # Dump keys that match the schema and that the config class validates. + # The ref is for traces and the Dev UI; a config that is not JSON + # (a callable, a client) still runs because resolve uses the instance. config = _dump_middleware_ref_config(entry.config) refs.append(MiddlewareRef(name=reg_name, config=config)) + inline.append((reg_name, entry)) else: refs.append(entry) + inline.append((entry.name, None)) + if any(mw is not None for _, mw in inline): + registry.register_value(_INLINE_MIDDLEWARE_KIND, _INLINE_MIDDLEWARE_KEY, inline) return refs +# Child-registry slot for the instances behind this call's inline ``use=[...]``. +_INLINE_MIDDLEWARE_KIND = 'genkit:inline-middleware' +_INLINE_MIDDLEWARE_KEY = 'use' + + def resolve_middleware_from_use( registry: Registry, use: Sequence[MiddlewareRef] | None, ) -> list[Middleware]: - """Resolve ``MiddlewareRef`` entries to fresh ``Middleware`` instances. + """Resolve ``MiddlewareRef`` entries to ``Middleware`` instances. - Each ref is instantiated from the registered ``_MiddlewareMetadata`` and - ``ref.config`` (same path for Dev UI, dotprompt, and inline ``use=[Mw(...)]``). + Inline ``use=[Mw(...)]`` entries keep the caller's instance registered on + the per-call child registry; ref entries (Dev UI, dotprompt) are + instantiated from the registered ``_MiddlewareMetadata`` and ``ref.config``. """ if not use: return [] + inline = registry.lookup_value(_INLINE_MIDDLEWARE_KIND, _INLINE_MIDDLEWARE_KEY) + instances: list[tuple[str, Middleware | None]] | None = None + if isinstance(inline, list): + typed_inline = cast(list[tuple[str, Middleware | None]], inline) + if len(typed_inline) != len(use) or any( + inst is not None and reg_name != entry.name + for (reg_name, inst), entry in zip(typed_inline, use, strict=True) + ): + raise GenkitError( + status='INTERNAL', + message=( + 'Inline middleware instances on the per-call registry do not match use= ' + f'({[name for name, _ in typed_inline]} vs {[entry.name for entry in use]}).' + ), + source='genkit.generate', + ) + instances = typed_inline out: list[Middleware] = [] - for entry in use: + for i, entry in enumerate(use): + if instances is not None and instances[i][1] is not None: + # Inline use=[Mw(...)]: keep the caller's instance (custom __init__, + # clients, compiled regex flags, callables) rather than rebuild it. + out.append(cast(Middleware, instances[i][1])) + continue defn = registry.lookup_value('middleware', entry.name) if defn is None: raise GenkitError( diff --git a/packages/genkit/src/genkit/_core/_middleware.py b/packages/genkit/src/genkit/_core/_middleware.py index ecc61281f..cc9b70879 100644 --- a/packages/genkit/src/genkit/_core/_middleware.py +++ b/packages/genkit/src/genkit/_core/_middleware.py @@ -18,12 +18,21 @@ from __future__ import annotations +import copy import inspect import re from collections.abc import Awaitable, Callable, Iterable from typing import Any, ClassVar, Generic, NamedTuple, Protocol, cast, get_args, get_origin -from pydantic import AliasChoices, BaseModel, ConfigDict, PrivateAttr, ValidationError, field_validator +from pydantic import ( + AliasChoices, + BaseModel, + ConfigDict, + PrivateAttr, + ValidationError, + field_validator, +) +from pydantic_core import PydanticSerializationError from typing_extensions import TypeVar from genkit._core._action import Action @@ -145,15 +154,19 @@ def _dump_middleware_ref_config(config: BaseModel) -> dict[str, Any] | None: """Dump a middleware config for ``MiddlewareRef`` using keys the class validates. Excludes ``@computed_field``s and falls back to the validation alias or - field name when ``serialization_alias`` is output-only. + field name when ``serialization_alias`` is output-only. Returns ``None`` + when the config contains non-JSON values (such as a callable or client). """ cfg_cls = type(config) computed = set(cfg_cls.model_computed_fields) - dumped = config.model_dump(exclude_none=True, by_alias=True, mode='json', exclude=computed) - spellings = _config_key_spellings(cfg_cls) - if spellings is None or all(k in spellings for k in dumped): - return dumped or None - raw = config.model_dump(exclude_none=True, by_alias=False, mode='json', exclude=computed) + try: + dumped = config.model_dump(exclude_none=True, by_alias=True, mode='json', exclude=computed) + spellings = _config_key_spellings(cfg_cls) + if spellings is None or all(k in spellings for k in dumped): + return dumped or None + raw = config.model_dump(exclude_none=True, by_alias=False, mode='json', exclude=computed) + except PydanticSerializationError: + return None out: dict[str, Any] = {} for name, val in raw.items(): info = cfg_cls.model_fields.get(name) @@ -436,6 +449,31 @@ async def wrap_model(self, params, ctx, next_fn): ``self.config`` is set once at construction. The attribute is read-only; treat the config object as read-only too (Pydantic models are not frozen). + + Choose where to store state based on its lifetime: + + * **Shared across all requests** (e.g., an audit client, rate limiter, + or compiled regex): set on ``self`` in ``__init__``. + * **Scoped to one ``generate()`` call** (e.g., retry counters or loop + budgets): use local variables inside ``wrap_generate``. + * **Scoped to one turn or tool call** (e.g., per-call timing or header + injection): use local variables inside ``wrap_model`` or ``wrap_tool``. + * **Shared between hooks in one ``generate()`` call** (e.g., recording + a tool call in ``wrap_tool`` and reading it in the next ``wrap_model`` + turn): pass it through ``ctx.context``, or store a fresh container on + ``self`` in ``__copy__``. + + Per-request containers via ``__copy__``: + Genkit calls ``copy.copy(mw)`` once at the start of each ``generate()`` + call. Because a shallow copy shares any ``list`` or ``dict`` created in + ``__init__`` across concurrent requests, override ``__copy__`` when you + need a fresh per-request container without re-running ``__init__``:: + + def __copy__(self) -> Self: + clone = type(self).__new__(type(self)) + clone.__dict__.update(self.__dict__) + clone._seen_tools = [] # isolated per generate() call + return clone """ name: ClassVar[str] = '' @@ -477,6 +515,7 @@ def __init_subclass__(cls, **kwargs: Any) -> None: # noqa: ANN401 # Handle the case where no config type is specified, e.g. class Logging(Middleware): # This means there is no user-facing configuration for the middleware. cls.Config = config_cls or _EmptyMiddlewareConfig + _reject_legacy_hooks(cls) def __init__(self, *, config: TConfig | None = None, **kwargs: Any) -> None: # noqa: ANN401 if config is not None: @@ -547,9 +586,48 @@ async def wrap_tool( return await next_fn(params, ctx) +# 0.12 hook names and their 0.13+ replacements. +_LEGACY_HOOKS: dict[str, str] = {'model': 'wrap_model', 'generate': 'wrap_generate', 'tool': 'wrap_tool'} + + +def _reject_legacy_hooks(cls: type[Middleware]) -> None: + """Fail at class definition when a 0.12 hook name would be a silent no-op. + + A guardrail written as ``async def model(self, req, ctx, next)`` inherits + the no-op ``wrap_model`` and never runs. Only an ``async def`` with the + 0.12 hook shape (self plus three positional parameters) is rejected, so a + helper like ``def tool(self, name)``, a property, or an attribute stays + legal, as does defining both names. + """ + for legacy, hook in _LEGACY_HOOKS.items(): + if not _looks_like_legacy_hook(cls.__dict__.get(legacy)): + continue + if getattr(cls, hook) is not getattr(Middleware, hook): + continue + raise TypeError( + f'{cls.__name__} defines `{legacy}()`, a 0.12 middleware hook that no longer runs. ' + f'Rename it to `{hook}(self, params, ctx, next_fn)`.' + ) + + +def _looks_like_legacy_hook(fn: object) -> bool: + """True for ``async def name(self, req, ctx, next)``, the 0.12 hook shape.""" + if not inspect.iscoroutinefunction(fn): + return False + positional = (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) + params = [p for p in inspect.signature(cast(Callable[..., Any], fn)).parameters.values() if p.kind in positional] + return len(params) == 4 + + def _copy_middleware_instance(impl: Middleware) -> Middleware: - """Return a fresh instance with the same config; internal hook state is not copied.""" - return type(impl)(config=impl._config.model_copy(deep=True)) + """Per-call shallow copy of a middleware instance. + + Keeps ``__init__`` state and the config object as the caller built them, so + a custom ``__init__``, a client, or a ``re.Pattern`` with flags survives. + Rebinding an attribute in a hook does not leak into the caller's instance; + mutating a shared container does, by design. + """ + return copy.copy(impl) class MiddlewareDef(Protocol): diff --git a/packages/genkit/tests/genkit/ai/middleware_instance_test.py b/packages/genkit/tests/genkit/ai/middleware_instance_test.py new file mode 100644 index 000000000..2018ae969 --- /dev/null +++ b/packages/genkit/tests/genkit/ai/middleware_instance_test.py @@ -0,0 +1,188 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 + +"""``use=[instance]`` keeps the caller's instance; 0.12 hook names fail loudly.""" + +import re +from collections.abc import Awaitable, Callable +from typing import Any + +import pytest +from pydantic import BaseModel, ConfigDict + +from genkit import Genkit, Message, ModelResponse, Part, Role +from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams +from genkit.model import ModelContext, ModelRequest + +Next = Callable[[ModelHookParams, MiddlewareContext], Awaitable[ModelResponse]] + + +def _echo_app() -> Genkit: + ai = Genkit() + + async def echo(request: ModelRequest, ctx: ModelContext) -> ModelResponse: + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text(request.messages[-1].text)])) + + ai.define_model(name='echo', fn=echo) + return ai + + +class SecretGuard(Middleware): + """Blocks prompts matching a pattern; holds a client set up in ``__init__``.""" + + name = 'secret_guard' + + def __init__(self, pattern: re.Pattern[str], audit: list[str]) -> None: + super().__init__() + self.pattern = pattern + self.audit = audit + + async def wrap_model(self, params: ModelHookParams, ctx: MiddlewareContext, next_fn: Next) -> ModelResponse: + text = params.request.messages[-1].text + if self.pattern.search(text): + self.audit.append(text) + return ModelResponse(message=Message(role=Role.MODEL, content=[Part.from_text('[blocked]')])) + return await next_fn(params, ctx) + + +@pytest.mark.asyncio +async def test_custom_init_and_regex_flags_survive_use() -> None: + """The instance runs as built: no ``cls(config=...)`` crash, IGNORECASE kept.""" + ai = _echo_app() + audit: list[str] = [] + guard = SecretGuard(re.compile('secret', re.IGNORECASE), audit) + + response = await ai.generate(model='echo', prompt='the SECRET menu', use=[guard]) + + assert response.text == '[blocked]' + assert audit == ['the SECRET menu'] + + +class _CallableConfig(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + redact: Callable[[str], str] + + +class Redact(Middleware[_CallableConfig]): + name = 'redact' + + async def wrap_model(self, params: ModelHookParams, ctx: MiddlewareContext, next_fn: Next) -> ModelResponse: + response = await next_fn(params, ctx) + return ModelResponse( + message=Message(role=Role.MODEL, content=[Part.from_text(self.config.redact(response.text))]) + ) + + +@pytest.mark.asyncio +async def test_callable_config_field_does_not_crash() -> None: + ai = _echo_app() + + response = await ai.generate( + model='echo', prompt='card 4111', use=[Redact(redact=lambda s: s.replace('4111', '****'))] + ) + + assert response.text == 'card ****' + + +@pytest.mark.asyncio +async def test_registered_middleware_instance_keeps_state() -> None: + """A registered class passed as an instance still runs that instance.""" + ai = _echo_app() + ai.define_middleware(SecretGuard) + audit: list[str] = [] + + await ai.generate(model='echo', prompt='secret sauce', use=[SecretGuard(re.compile('SECRET', re.I), audit)]) + + assert audit == ['secret sauce'] + + +def test_legacy_model_hook_raises_at_class_definition() -> None: + with pytest.raises(TypeError, match=r'`model\(\)`.*wrap_model'): + + class PiiRedact(Middleware): # pyright: ignore[reportUnusedClass] + async def model(self, req: Any, ctx: Any, next_fn: Any) -> Any: # noqa: ANN401 + return await next_fn(req, ctx) + + +def test_legacy_name_alongside_wrap_hook_is_allowed() -> None: + class Both(Middleware): # pyright: ignore[reportUnusedClass] + async def tool(self, *args: Any) -> None: # noqa: ANN401 + return None + + async def wrap_tool(self, params: Any, ctx: Any, next_fn: Any) -> Any: # noqa: ANN401 + return await next_fn(params, ctx) + + class WithAttr(Middleware): # pyright: ignore[reportUnusedClass] + model = 'googleai/gemini-flash-lite-latest' + + +def test_helper_method_named_like_a_legacy_hook_is_allowed() -> None: + """Only the 0.12 hook shape is rejected; a sync helper or other arity passes.""" + + class AuditLog(Middleware): # pyright: ignore[reportUnusedClass] + def tool(self, name: str) -> str: + return f'tool:{name}' + + async def model(self, order_id: str) -> str: + return order_id + + def generate(self, req: Any, ctx: Any, next_fn: Any) -> None: # noqa: ANN401 + return None + + +def test_legacy_tool_and_generate_hooks_raise() -> None: + with pytest.raises(TypeError, match=r'`tool\(\)`.*wrap_tool'): + + class AllergyGate(Middleware): # pyright: ignore[reportUnusedClass] + async def tool(self, req: Any, ctx: Any, next_fn: Any) -> Any: # noqa: ANN401 + return await next_fn(req, ctx) + + with pytest.raises(TypeError, match=r'`generate\(\)`.*wrap_generate'): + + class TurnLimit(Middleware): # pyright: ignore[reportUnusedClass] + async def generate(self, req: Any, ctx: Any, next_fn: Any) -> Any: # noqa: ANN401 + return await next_fn(req, ctx) + + +@pytest.mark.asyncio +async def test_define_prompt_with_registered_callable_config_middleware() -> None: + """ai.define_prompt(use=[Redact(...)]) does not crash on non-JSON config fields.""" + ai = _echo_app() + ai.define_middleware(Redact) + + prompt = ai.define_prompt( + name='p', + model='echo', + prompt='card 4111', + use=[Redact(redact=lambda s: s.replace('4111', '****'))], + ) + response = await prompt() + + assert response.text == 'card ****' + + +def test_resolve_middleware_from_use_mismatch_raises_genkit_error() -> None: + """A mismatch between registered inline instances and use= fails with a clear GenkitError.""" + from genkit import GenkitError + from genkit._ai._generate import register_middleware, resolve_middleware_from_use + from genkit._core._typing import MiddlewareRef + + ai = _echo_app() + registry: Any = ai._registry + register_middleware(registry, [SecretGuard(re.compile('secret'), [])]) + + with pytest.raises(GenkitError, match='Inline middleware instances on the per-call registry do not match'): + resolve_middleware_from_use(registry, [MiddlewareRef(name='other')])