-
Notifications
You must be signed in to change notification settings - Fork 757
feat(py): middleware plugin + samples #5263
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
d679ff1
include sample and plugin
huangjeff5 2f50d75
expose Middleware() type that inherits Plugin
huangjeff5 34f2b29
fix comments
huangjeff5 9e6387d
Update _tool_approval.py
huangjeff5 11e7747
fix import
huangjeff5 c891e0f
Wire plugin to use registry from params
huangjeff5 f453d2c
make comments display better on small viewports
huangjeff5 90395f3
clean up signature
huangjeff5 c9c4e66
fix bad merge
huangjeff5 b1431ac
update usage
huangjeff5 1be4433
update pattern
huangjeff5 cd01032
keep name a kwarg
huangjeff5 8d31bc5
clean up readme model refs, fix skills bug with gemini model
huangjeff5 891bd69
Expose cause in GenkitError if wrappedd
huangjeff5 fb58a61
clean up sample
huangjeff5 d404d98
add middleware coding agent and put cache on instance level
huangjeff5 beae04a
refactor
huangjeff5 a501494
update based on mw core refactor
huangjeff5 dcb7f84
fix sample usage
huangjeff5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,197 @@ | ||
| # Genkit Middleware Plugin | ||
|
|
||
| A collection of middleware implementations for Firebase Genkit Python. | ||
|
|
||
| ## Overview | ||
|
|
||
| This plugin provides five 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 | ||
|
|
||
| ## Quick start | ||
|
|
||
| Import the middleware classes you need and pass instances directly into `use=[]`: | ||
|
|
||
| ```python | ||
| from genkit import Genkit | ||
| from genkit.plugins.middleware import Retry, Fallback, Middleware | ||
|
|
||
| ai = Genkit(plugins=[Middleware()]) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-flash-latest', | ||
| prompt='Hello!', | ||
| use=[ | ||
| Retry(max_retries=5), | ||
| Fallback(models=['googleai/gemini-2.5-pro']), | ||
| ], | ||
| ) | ||
| ``` | ||
|
|
||
| These pre-packaged middlewares will be available to play with in the Dev UI by default. | ||
|
|
||
| ## Installation | ||
|
|
||
| ```bash | ||
| pip install genkit-plugin-middleware | ||
| ``` | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Retry | ||
|
|
||
| Automatically retries model calls on transient failures with configurable exponential backoff: | ||
|
|
||
| ```python | ||
| from genkit.plugins.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, | ||
| jitter=True, # set False for deterministic backoff (tests) | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-2.5-flash', | ||
| prompt='Hello!', | ||
| use=[retry], | ||
| ) | ||
| ``` | ||
|
|
||
| ### Fallback | ||
|
|
||
| Falls back to alternative models on retryable errors: | ||
|
|
||
| ```python | ||
| from genkit.plugins.middleware import Fallback | ||
|
|
||
| fallback = Fallback( | ||
| models=['googleai/gemini-2.5-pro', 'googleai/gemini-2.5-flash'], | ||
| statuses=['UNAVAILABLE', 'DEADLINE_EXCEEDED'], | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-2.5-ultra', | ||
| prompt='Hello!', | ||
| use=[fallback], | ||
| ) | ||
| ``` | ||
|
|
||
| ### ToolApproval | ||
|
|
||
| Requires approval before executing tools (useful for sensitive operations): | ||
|
|
||
| ```python | ||
| from genkit.plugins.middleware import ToolApproval | ||
|
|
||
| approval = ToolApproval( | ||
| allowed_tools=['get_weather', 'search'], # These tools run without approval | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-2.5-flash', | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. gemini-flash-latest |
||
| prompt='Delete the database', | ||
| tools=[delete_database_tool], | ||
| 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 ``toolApproved`` | ||
| (the middleware only treats explicit dict metadata as approval): | ||
|
|
||
| ```python | ||
| first = await ai.generate( | ||
| model='googleai/gemini-flash-latest', | ||
| prompt='Delete the database', | ||
| tools=[delete_database_tool], | ||
| use=[approval], | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-flash-latest', | ||
| prompt='Delete the database', | ||
| messages=list(first.messages), | ||
| tools=[delete_database_tool], | ||
| use=[approval], | ||
| resume_restart=delete_database_tool.restart( | ||
| None, | ||
| interrupt=first.interrupts[0], | ||
| resumed_metadata={'toolApproved': True}, | ||
| ), | ||
| ) | ||
| ``` | ||
|
|
||
| ### Skills | ||
|
|
||
| Scans directories for SKILL.md files and exposes them as loadable instructions: | ||
|
|
||
| ```python | ||
| from genkit.plugins.middleware import Skills | ||
|
|
||
| skills = Skills( | ||
| skill_paths=['skills', 'prompts/skills'], | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-flash-latest', | ||
| prompt='Help me with Python', | ||
| use=[skills], | ||
| ) | ||
| ``` | ||
|
|
||
| Skills are discovered by scanning for directories containing `SKILL.md` files. Each `SKILL.md` can have optional YAML frontmatter: | ||
|
|
||
| ```markdown | ||
| --- | ||
| name: python-expert | ||
| description: Expert Python programming assistance | ||
| --- | ||
|
|
||
| You are an expert Python programmer... | ||
| ``` | ||
|
|
||
| ### Filesystem | ||
|
|
||
| Provides sandboxed file operations confined to a root directory: | ||
|
|
||
| ```python | ||
| from genkit.plugins.middleware import Filesystem | ||
|
|
||
| fs = Filesystem( | ||
| root_dir='./workspace', | ||
| allow_write_access=True, | ||
| tool_name_prefix='', | ||
| ) | ||
|
|
||
| response = await ai.generate( | ||
| model='googleai/gemini-flash-latest', | ||
| prompt='List files in the current directory', | ||
| use=[fs], | ||
| ) | ||
| ``` | ||
|
|
||
| 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`) | ||
|
|
||
| ## Development | ||
|
|
||
| ```bash | ||
| cd py/plugins/middleware | ||
| pip install -e ".[dev]" | ||
| pytest tests/ | ||
| ``` | ||
|
|
||
| ## License | ||
|
|
||
| Apache 2.0 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| # Copyright 2025 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 | ||
|
|
||
| [project] | ||
| authors = [ | ||
| { name = "Google" }, | ||
| ] | ||
| classifiers = [ | ||
| "Development Status :: 3 - Alpha", | ||
| "Environment :: Console", | ||
| "Environment :: Web Environment", | ||
| "Framework :: AsyncIO", | ||
| "Framework :: Pydantic", | ||
| "Framework :: Pydantic :: 2", | ||
| "Intended Audience :: Developers", | ||
| "Operating System :: OS Independent", | ||
| "Programming Language :: Python", | ||
| "Programming Language :: Python :: 3 :: Only", | ||
| "Programming Language :: Python :: 3.10", | ||
| "Programming Language :: Python :: 3.11", | ||
| "Programming Language :: Python :: 3.12", | ||
| "Programming Language :: Python :: 3.13", | ||
| "Programming Language :: Python :: 3.14", | ||
| "Topic :: Scientific/Engineering :: Artificial Intelligence", | ||
| "Topic :: Software Development :: Libraries", | ||
| "Typing :: Typed", | ||
| "License :: OSI Approved :: Apache Software License", | ||
| ] | ||
| dependencies = [ | ||
| "genkit>=0.5.2", | ||
| "pyyaml>=6.0", | ||
| ] | ||
| description = "A collection of middleware implementations for Genkit." | ||
| keywords = [ | ||
| "genkit", | ||
| "ai", | ||
| "llm", | ||
| "middleware", | ||
| ] | ||
| license = "Apache-2.0" | ||
| name = "genkit-plugin-middleware" | ||
| readme = "README.md" | ||
| requires-python = ">=3.10" | ||
| version = "0.5.2" | ||
|
|
||
| [project.optional-dependencies] | ||
| dev = [ | ||
| "pytest>=8.3.4", | ||
| "pytest-asyncio>=0.25.2", | ||
| "pytest-cov>=6.0.0", | ||
| "pytest-xdist>=3.6.1", | ||
| ] | ||
|
|
||
| [project.urls] | ||
| "Bug Tracker" = "https://github.com/genkit-ai/genkit/issues" | ||
| "Documentation" = "https://firebase.google.com/docs/genkit" | ||
| "Homepage" = "https://github.com/genkit-ai/genkit" | ||
| "Repository" = "https://github.com/genkit-ai/genkit/tree/main/py" | ||
|
|
||
| [build-system] | ||
| build-backend = "hatchling.build" | ||
| requires = ["hatchling"] | ||
|
|
||
| [tool.hatch.build.targets.wheel] | ||
| only-include = ["src/genkit/plugins/middleware"] | ||
| sources = ["src"] |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
gemini-flash-latest