Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

Genkit Middleware Plugin

A collection of middleware implementations for Genkit Python.

Building with a coding agent? Install the Genkit Python skill first.

npx skills add genkit-ai/skills --skill developing-genkit-python

It teaches your agent the current Genkit Python APIs and common gotchas. Source, manual install and skills for other languages: genkit-ai/skills.

Overview

This plugin provides concrete middleware implementations for common use cases:

  • Retry: Retries model API calls on transient errors with exponential backoff
  • Fallback: Falls back to alternative models when the primary model fails
  • ToolApproval: Requires explicit approval before executing tool calls
  • Skills: Exposes a library of skills as system prompts and tools
  • Filesystem: Provides sandboxed filesystem operations
  • Artifacts (experimental, genkit_middleware.exp): Session artifact listing plus read/write artifact tools

Quick start

Import the middleware classes you need and pass instances directly into use=[]:

from genkit import Genkit
from genkit_google_genai import GoogleAI
from genkit_middleware import Fallback, Middleware, Retry

ai = Genkit(plugins=[GoogleAI(), Middleware()])


async def main() -> None:
    response = await ai.generate(
        model=GoogleAI.gemini('gemini-flash-latest'),
        prompt='Hello!',
        use=[
            Retry(max_retries=5),
            Fallback(models=['googleai/gemini-3.1-pro-preview']),
        ],
    )
    print(response.text)


if __name__ == '__main__':
    ai.run_main(main())

Every middleware works when you pass an instance in use=[]; no plugin registration is needed. Registering Middleware() lists the stable middleware in the Dev UI and lets a .prompt file name them in use:.

Installation

uv add genkit-middleware genkit-google-genai

Usage

Retry

Retries a failed model call with exponential backoff. A GenkitError is retried only when its status is in statuses; any other exception is retried:

from genkit_google_genai import GoogleAI
from genkit_middleware import Retry

retry = Retry(
    max_retries=3,
    statuses=['UNAVAILABLE', 'DEADLINE_EXCEEDED', 'RESOURCE_EXHAUSTED'],
    initial_delay_ms=1000,
    max_delay_ms=60000,
    backoff_factor=2.0,
    no_jitter=False,  # set True for deterministic backoff (tests)
)

response = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='Hello!',
    use=[retry],
)
print(response.text)
# => Hello! How can I help you today?

Fallback

Tries each backup model in order when the primary fails with a listed GenkitError status (defaults: the transient statuses plus NOT_FOUND and UNIMPLEMENTED). Other exceptions are raised as-is. Order matters: use=[Retry(...), Fallback(...)] retries the whole sequence; use=[Fallback(...), Retry(...)] retries only the primary:

from genkit_google_genai import GoogleAI
from genkit_middleware import Fallback

fallback = Fallback(
    models=[
        'googleai/gemini-3.1-pro-preview',
        'googleai/gemini-flash-latest',
    ],
    statuses=['UNAVAILABLE', 'DEADLINE_EXCEEDED'],
)

response = await ai.generate(
    model=GoogleAI.gemini('gemini-pro-latest'),
    prompt='Hello!',
    use=[fallback],
)
print(response.text)
# => Hello! How can I help you today?

ToolApproval

Requires approval before executing tools (useful for sensitive operations):

from pydantic import BaseModel, Field

from genkit_google_genai import GoogleAI
from genkit_middleware import ToolApproval


class DeleteInput(BaseModel):
    name: str = Field(description='Database name to delete')


@ai.tool
async def delete_database(input: DeleteInput) -> str:
    return f'Deleted {input.name}'


approval = ToolApproval(
    allowed_tools=['get_weather', 'search'],  # These tools run without approval
)

first = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='Delete the database',
    tools=['delete_database'],
    use=[approval],
)

When a non-allowed tool is called, execution is interrupted. Approve and re-run the tool by restarting it with resumed_metadata that includes tool_approved. Pass the history in messages= and leave out prompt=: a new prompt appends a user turn after the pending tool request, so the call fails before the model or the tool runs. It doesn't raise; it returns finish_reason='failed' with response.error.status == 'FAILED_PRECONDITION' and response.error.reason == 'INVALID_RESUME'.

response = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    messages=list(first.messages),
    tools=['delete_database'],
    use=[approval],
    resume_restart=first.interrupts[0].restart(resumed_metadata={'tool_approved': True}),
)
print(response.text)
# => The database has been deleted.

Inside the tool, ctx.is_resumed() is True on the approved re-run and ctx.resumed_metadata holds the dict you passed ({'tool_approved': True}).

Skills

Scans directories for SKILL.md files and exposes them as loadable instructions:

from genkit_google_genai import GoogleAI
from genkit_middleware import Skills

skills = Skills(
    skill_paths=['skills', 'prompts/skills'],
)

response = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='Help me with Python',
    use=[skills],
)
print(response.text)
# => Sure. Loaded python-expert. What are you working on?

Each direct subdirectory of a skill path that holds a SKILL.md is a skill, named after the directory (skills/python-expert/SKILL.md is python-expert). Frontmatter description shows up in the catalog; frontmatter name doesn't rename the skill:

---
name: python-expert
description: Expert Python programming assistance
---

You are an expert Python programmer...

When two skill paths hold the same name, the later path wins. A symlinked skill directory is followed, so skills/plating -> ~/shared/plating works. A SKILL.md that is itself a symlink, not a regular file, or over 1 MiB isn't read.

Filesystem

Provides sandboxed file operations confined to a root directory:

from genkit_google_genai import GoogleAI
from genkit_middleware import Filesystem

fs = Filesystem(
    root_dir='./workspace',
    allow_write_access=True,
    tool_name_prefix='',
)

response = await ai.generate(
    model=GoogleAI.gemini('gemini-flash-latest'),
    prompt='List files in the current directory',
    use=[fs],
)
print(response.text)
# => The workspace has menu.md and orders.csv.

Provides four tools:

  • list_files: List files in a directory
  • read_file: Read file content
  • write_file: Write to a file (requires allow_write_access=True)
  • edit_file: Edit file with string replacements (requires allow_write_access=True)

Paths resolve against root_dir. An absolute path works only if it already points inside the root; /etc/hosts is refused, not read as {root}/etc/hosts. Symlinks are resolved first, so a link out of the root is refused and left out of list_files. Tool errors come back as the tool response with the host root path removed.

Artifacts

Exposes read_artifact / write_artifact tools and lists session artifacts in the system prompt. It only works inside an agent, so it's experimental and lives in genkit_middleware.exp. Pass it straight to the agent; Middleware() doesn't register it, so it isn't listed in the Dev UI and a .prompt file can't name it:

from genkit.exp import Genkit
from genkit.exp.agent import InMemorySessionStore
from genkit_google_genai import GoogleAI
from genkit_middleware import Middleware
from genkit_middleware.exp import Artifacts

ai = Genkit(plugins=[GoogleAI(), Middleware()])

agent = ai.define_agent(
    name='workspaceAgent',
    model=GoogleAI.gemini('gemini-flash-latest'),
    use=[Artifacts()],
    store=InMemorySessionStore(),
)

chat = agent.chat()
await chat.send('Write poem.txt with a short poem about Python agents.')
print([a.name for a in chat.artifacts])
# => ['poem.txt']

Metadata

Release files for genkit-middleware 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

Source distribution for genkit-middleware 0.14.0
File Size Uploaded Provenance Actions
genkit_middleware-0.14.0.tar.gz 53.2 kB With provenance Details for genkit_middleware-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for genkit-middleware 0.14.0
File Interpreter ABI Platform Actions
genkit_middleware-0.14.0-py3-none-any.whl Python 3 none any Details for genkit_middleware-0.14.0-py3-none-any.whl

Total release size: 88.4 kB

Release files / genkit_middleware-0.14.0.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL genkit_middleware-0.14.0.tar.gz
Size 53.2 kB
Tags Source
SHA-256 checksum
How to use checksums
f48eab01f386ebeb93c6376c39b6b94a54f3adbcb73223ab74e8a2139013bdf6
BLAKE2b-256 checksum
How to use checksums
119d9f7d82b728bf059f534a1d6810464254ed08347423632436d0b3427b66a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Release files / genkit_middleware-0.14.0-py3-none-any.whl

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL genkit_middleware-0.14.0-py3-none-any.whl
Size 35.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1f9408c5ecfab2b32423888dbb2ea2008252a29cee80a42ef73bbcdc180fa1c3
BLAKE2b-256 checksum
How to use checksums
a65e4e3a0145e61e6dbdd53f98c81630410a5a230fed39f4e75427343404cc35
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

Security for genkit-middleware 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Change of provenance

The repository and configuration that created this release differ from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for genkit_middleware-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 19, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page