genkit-middleware 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Genkit middleware plugin.
18
+
19
+ Provides concrete middleware implementations:
20
+
21
+ * ``Retry`` — retries model calls on transient errors with exponential
22
+ backoff.
23
+ * ``Fallback`` — falls back to alternative models on failure.
24
+ * ``ToolApproval`` — requires approval before executing tools.
25
+ * ``Skills`` — exposes a ``SKILL.md`` library as system prompts plus a
26
+ ``use_skill`` tool.
27
+ * ``Filesystem`` — sandboxed filesystem operations (list / read / write /
28
+ edit).
29
+ * ``Artifacts`` — ``read_artifact`` / ``write_artifact`` plus artifact listing in the system prompt.
30
+
31
+ Import the classes you need and pass instances into ``use=[...]``.
32
+ See below for an example.
33
+ """
34
+
35
+ from genkit.plugin_api import MiddlewarePlugin, new_middleware
36
+ from genkit_middleware._artifacts import Artifacts
37
+ from genkit_middleware._fallback import Fallback
38
+ from genkit_middleware._filesystem import Filesystem
39
+ from genkit_middleware._retry import Retry
40
+ from genkit_middleware._skills import Skills
41
+ from genkit_middleware._tool_approval import ToolApproval
42
+
43
+ _MIDDLEWARE_DESCS = [
44
+ new_middleware(
45
+ Retry,
46
+ name='retry',
47
+ description='Retries model calls on transient failures with exponential backoff',
48
+ ),
49
+ new_middleware(
50
+ Fallback,
51
+ name='fallback',
52
+ description='Falls back to alternative models on failure',
53
+ ),
54
+ new_middleware(
55
+ ToolApproval,
56
+ name='tool_approval',
57
+ description='Requires approval before executing tools',
58
+ ),
59
+ new_middleware(
60
+ Skills,
61
+ name='skills',
62
+ description='Provides access to skill library for specialized instructions',
63
+ ),
64
+ new_middleware(
65
+ Filesystem,
66
+ name='filesystem',
67
+ description='Sandboxed filesystem operations',
68
+ ),
69
+ new_middleware(
70
+ Artifacts,
71
+ name='artifacts',
72
+ description='read_artifact and write_artifact tools with session artifact listing in system prompt',
73
+ ),
74
+ ]
75
+
76
+
77
+ class Middleware(MiddlewarePlugin):
78
+ """Plugin that registers Retry, Fallback, ToolApproval, Skills, Filesystem, and Artifacts.
79
+
80
+ Registers all six middleware descriptors so they show up in the Dev
81
+ UI.
82
+
83
+ ``Filesystem`` has no default root — supply ``root_dir`` when
84
+ constructing an instance, for example
85
+ ``Filesystem(root_dir='./workspace')``.
86
+
87
+ Example:
88
+ ```python
89
+ from genkit import Genkit
90
+ from genkit_google_genai import GoogleAI
91
+ from genkit_middleware import Middleware, Retry
92
+
93
+ # 1. Register middleware plugin
94
+ ai = Genkit(plugins=[GoogleAI(), Middleware()])
95
+
96
+ # 2. Generate with automatic retry resilience
97
+ res = await ai.generate(
98
+ model='googleai/gemini-flash-latest',
99
+ prompt='Summarize quantum computing.',
100
+ use=[Retry(max_retries=3)],
101
+ )
102
+
103
+ # 3. Inspect output
104
+ print(res.text)
105
+ # => Quantum computing uses quantum mechanics for complex calculations...
106
+ ```
107
+ """
108
+
109
+ name = 'genkit-middleware'
110
+ middleware = list(_MIDDLEWARE_DESCS)
111
+
112
+
113
+ __all__ = [
114
+ 'Artifacts',
115
+ 'Fallback',
116
+ 'Filesystem',
117
+ 'Middleware',
118
+ 'Retry',
119
+ 'Skills',
120
+ 'ToolApproval',
121
+ ]
@@ -0,0 +1,222 @@
1
+ # Copyright 2026 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Artifacts middleware for Genkit agents."""
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Awaitable, Callable
22
+
23
+ from pydantic import BaseModel, Field
24
+
25
+ from genkit._ai._model import Message
26
+ from genkit._ai._tools import tool
27
+ from genkit._core._action import Action
28
+ from genkit._core._model import GenerateActionOptions, ModelResponse
29
+ from genkit._core._typing import Artifact, Part, Role, TextPart
30
+ from genkit.middleware import BaseMiddleware, GenerateHookParams, GenerateMiddlewareContext
31
+
32
+ ARTIFACTS_LISTING_MARKER = 'artifacts-middleware-listing'
33
+
34
+
35
+ class ArtifactsConfig(BaseModel):
36
+ """Options for session artifact tools and prompt injection."""
37
+
38
+ readonly: bool = Field(
39
+ default=False,
40
+ description=('When true, only read_artifact is provided — the model cannot create or update artifacts.'),
41
+ )
42
+
43
+
44
+ class ReadArtifactInput(BaseModel):
45
+ name: str = Field(description='The name of the artifact to read.')
46
+
47
+
48
+ class ReadArtifactOutput(BaseModel):
49
+ name: str = Field(description='The artifact name.')
50
+ content: str = Field(description='The text content of the artifact.')
51
+ found: bool = Field(description='Whether the artifact was found in the session.')
52
+
53
+
54
+ class WriteArtifactInput(BaseModel):
55
+ name: str = Field(description='A unique name for the artifact (e.g. a filename like "report.md").')
56
+ content: str = Field(description='The full text content of the artifact.')
57
+
58
+
59
+ class WriteArtifactOutput(BaseModel):
60
+ status: str = Field(description='Confirmation that the artifact was created or updated.')
61
+
62
+
63
+ def extract_artifact_text(artifact: Artifact) -> str:
64
+ parts: list[str] = []
65
+ for part in artifact.parts:
66
+ root = part.root
67
+ if isinstance(root, TextPart) and root.text:
68
+ parts.append(root.text)
69
+ return '\n'.join(parts)
70
+
71
+
72
+ def artifact_source(artifact: Artifact) -> str | None:
73
+ meta = artifact.metadata
74
+ if isinstance(meta, dict):
75
+ source = meta.get('source')
76
+ return str(source) if source is not None else None
77
+ return None
78
+
79
+
80
+ def build_artifact_listing(artifacts: list[Artifact]) -> str:
81
+ if not artifacts:
82
+ return '<artifacts>\nNo artifacts are currently available in the session.\n</artifacts>'
83
+
84
+ lines = [
85
+ '<artifacts>',
86
+ 'The following artifacts are available in the session. Use the read_artifact tool to view their content.',
87
+ ]
88
+ for art in artifacts:
89
+ text = extract_artifact_text(art)
90
+ size_hint = f' ({len(text)} chars)' if text else ''
91
+ source = artifact_source(art)
92
+ source_hint = f' [from: {source}]' if source else ''
93
+ label = art.name or '(unnamed)'
94
+ lines.append(f' - {label}{size_hint}{source_hint}')
95
+ lines.append('</artifacts>')
96
+ return '\n'.join(lines)
97
+
98
+
99
+ def inject_artifact_listing_messages(messages: list[Message], listing: str) -> list[Message]:
100
+ """Strip prior listing parts and append a fresh listing to the system message."""
101
+ out = list(messages)
102
+
103
+ for i, msg in enumerate(out):
104
+ filtered: list[Part] = []
105
+ for part in msg.content or []:
106
+ root = part.root
107
+ meta = root.metadata if isinstance(root, TextPart) else None
108
+ if isinstance(meta, dict) and meta.get(ARTIFACTS_LISTING_MARKER):
109
+ continue
110
+ filtered.append(part)
111
+ if len(filtered) != len(msg.content or []):
112
+ out[i] = Message(role=msg.role, content=filtered)
113
+
114
+ listing_part = Part(
115
+ root=TextPart(text=listing, metadata={ARTIFACTS_LISTING_MARKER: True}),
116
+ )
117
+
118
+ system_idx: int | None = None
119
+ for i, msg in enumerate(out):
120
+ if msg.role == Role.SYSTEM:
121
+ system_idx = i
122
+ break
123
+
124
+ if system_idx is not None:
125
+ msg = out[system_idx]
126
+ out[system_idx] = Message(
127
+ role=Role.SYSTEM,
128
+ content=[*msg.content, listing_part],
129
+ )
130
+ else:
131
+ out.insert(0, Message(role=Role.SYSTEM, content=[listing_part]))
132
+
133
+ return out
134
+
135
+
136
+ def inject_artifact_listing(options: GenerateActionOptions, listing: str) -> GenerateActionOptions:
137
+ new_options = options.model_copy()
138
+ new_options.messages = inject_artifact_listing_messages(list(options.messages), listing)
139
+ return new_options
140
+
141
+
142
+ class Artifacts(BaseMiddleware[ArtifactsConfig]):
143
+ """Session artifact tools plus an injected artifact listing in the system prompt."""
144
+
145
+ def tools(self, ctx: GenerateMiddlewareContext) -> list[Action]:
146
+ tools: list[Action] = []
147
+
148
+ async def read_artifact(input: ReadArtifactInput) -> ReadArtifactOutput:
149
+ session = ctx.ai.current_session()
150
+ if session is None:
151
+ return ReadArtifactOutput(
152
+ name=input.name,
153
+ content=(
154
+ 'Artifacts-based tools are not available, as there is no active agent '
155
+ 'session detected. Artifacts middleware only work when passed to an agent.'
156
+ ),
157
+ found=False,
158
+ )
159
+
160
+ artifacts = await session.get_artifacts()
161
+ match = next((a for a in artifacts if a.name == input.name), None)
162
+ if match is None:
163
+ return ReadArtifactOutput(
164
+ name=input.name,
165
+ content=f'Artifact "{input.name}" not found.',
166
+ found=False,
167
+ )
168
+
169
+ return ReadArtifactOutput(
170
+ name=input.name,
171
+ content=extract_artifact_text(match),
172
+ found=True,
173
+ )
174
+
175
+ tools.append(
176
+ tool(
177
+ read_artifact,
178
+ name='read_artifact',
179
+ description=(
180
+ 'Reads the content of a named artifact from the session. '
181
+ 'Use this to inspect artifacts produced by sub-agents or '
182
+ 'previously created artifacts.'
183
+ ),
184
+ ).action()
185
+ )
186
+
187
+ if not self.config.readonly:
188
+
189
+ async def write_artifact(input: WriteArtifactInput) -> WriteArtifactOutput:
190
+ session = ctx.ai.current_session()
191
+ if session is None:
192
+ return WriteArtifactOutput(status='Error: no active session.')
193
+
194
+ await session.add_artifacts([Artifact(name=input.name, parts=[Part(TextPart(text=input.content))])])
195
+ return WriteArtifactOutput(status=f'Artifact "{input.name}" saved successfully.')
196
+
197
+ tools.append(
198
+ tool(
199
+ write_artifact,
200
+ name='write_artifact',
201
+ description=(
202
+ 'Creates or updates a named artifact in the session. '
203
+ 'If an artifact with the same name already exists, it will be '
204
+ 'replaced. Use this to produce files, reports, code, or other '
205
+ 'deliverables.'
206
+ ),
207
+ ).action()
208
+ )
209
+
210
+ return tools
211
+
212
+ async def wrap_generate(
213
+ self,
214
+ params: GenerateHookParams,
215
+ ctx: GenerateMiddlewareContext,
216
+ next_fn: Callable[[GenerateHookParams, GenerateMiddlewareContext], Awaitable[ModelResponse]],
217
+ ) -> ModelResponse:
218
+ session = ctx.ai.current_session()
219
+ artifacts = await session.get_artifacts() if session is not None else []
220
+ listing = build_artifact_listing(artifacts)
221
+ params.options = inject_artifact_listing(params.options, listing)
222
+ return await next_fn(params, ctx)
@@ -0,0 +1,98 @@
1
+ # Copyright 2025 Google LLC
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ """Fallback middleware for Genkit model calls."""
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Awaitable, Callable
22
+ from typing import Any
23
+
24
+ from pydantic import BaseModel, Field
25
+
26
+ from genkit import GenkitError
27
+ from genkit._core._action import Action, ActionKind
28
+ from genkit._core._model import ModelResponse
29
+ from genkit.middleware import BaseMiddleware, GenerateMiddlewareContext, ModelHookParams
30
+
31
+ _DEFAULT_FALLBACK_STATUSES: list[str] = [
32
+ 'UNAVAILABLE',
33
+ 'DEADLINE_EXCEEDED',
34
+ 'RESOURCE_EXHAUSTED',
35
+ 'ABORTED',
36
+ 'INTERNAL',
37
+ 'NOT_FOUND',
38
+ 'UNIMPLEMENTED',
39
+ ]
40
+
41
+
42
+ class FallbackConfig(BaseModel):
43
+ """Models and statuses that trigger fallback."""
44
+
45
+ models: list[str] = Field(default_factory=list)
46
+ statuses: list[str] = Field(default_factory=lambda: list(_DEFAULT_FALLBACK_STATUSES))
47
+
48
+
49
+ class Fallback(BaseMiddleware[FallbackConfig]):
50
+ """Fallback middleware to try alternative models on failure."""
51
+
52
+ async def _resolve_fallback_model(
53
+ self,
54
+ ctx: GenerateMiddlewareContext,
55
+ model_name: str,
56
+ ) -> Action[Any, Any, Any]:
57
+ """Look up a fallback model on the per-call registry."""
58
+ action = await ctx.ai.registry.resolve_action(ActionKind.MODEL, model_name)
59
+ if action is None:
60
+ raise GenkitError(
61
+ status='NOT_FOUND',
62
+ message=f'No model named "{model_name}" is registered on this app.',
63
+ )
64
+ return action
65
+
66
+ async def wrap_model(
67
+ self,
68
+ params: ModelHookParams,
69
+ ctx: GenerateMiddlewareContext,
70
+ next_fn: Callable[[ModelHookParams, GenerateMiddlewareContext], Awaitable[ModelResponse]],
71
+ ) -> ModelResponse:
72
+ """Try the primary model, then fall back to alternates on retryable errors."""
73
+ last_error: Exception | None = None
74
+ try:
75
+ return await next_fn(params, ctx)
76
+ except Exception as exc:
77
+ if not isinstance(exc, GenkitError) or exc.status not in self.config.statuses:
78
+ raise
79
+ last_error = exc
80
+
81
+ assert last_error is not None # noqa: S101
82
+ on_chunk = ctx.on_chunk
83
+ for model_name in self.config.models:
84
+ fallback_action = await self._resolve_fallback_model(ctx, model_name)
85
+ try:
86
+ result = await fallback_action.run(
87
+ input=params.request,
88
+ context=ctx.custom_context,
89
+ on_chunk=on_chunk,
90
+ abort_signal=ctx.abort_signal,
91
+ )
92
+ return result.response # type: ignore[return-value]
93
+ except Exception as e2:
94
+ last_error = e2
95
+ if not isinstance(e2, GenkitError) or e2.status not in self.config.statuses:
96
+ raise
97
+
98
+ raise last_error