Skip to content
Merged
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
174 changes: 154 additions & 20 deletions packages/genkit-middleware/src/genkit_middleware/_fallback.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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:
Expand Down Expand Up @@ -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]] = ...,
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
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,
Expand All @@ -122,34 +252,38 @@ 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)
# A plain ModelRequest with a dict config, so the backup model parses
# 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(
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
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
Expand Down
51 changes: 45 additions & 6 deletions packages/genkit-middleware/src/genkit_middleware/_filesystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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())
Expand Down
Loading
Loading