Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
e02fcbb
feat(py): Add DAP helpers to registry
huangjeff5 Apr 8, 2026
2430401
child registry support
huangjeff5 Apr 8, 2026
f3807df
address comments
huangjeff5 Apr 8, 2026
7163a19
format
huangjeff5 Apr 8, 2026
2ecdab4
fix format
huangjeff5 Apr 8, 2026
ba80440
fix comment
huangjeff5 Apr 8, 2026
8c94e4d
address feedback
huangjeff5 Apr 15, 2026
e43ce55
fix type issue
huangjeff5 Apr 20, 2026
b50d6cf
more refactor
huangjeff5 Apr 23, 2026
007b158
fix format and pyrefly
huangjeff5 Apr 23, 2026
1c730cd
address comments
huangjeff5 Apr 30, 2026
4b66855
format
huangjeff5 Apr 30, 2026
d0d9027
dynamic tool support
huangjeff5 Apr 30, 2026
bdbea5a
add tool surface
huangjeff5 Apr 30, 2026
4b7af0b
Merge branch 'main' into jh-dynamic-tools
huangjeff5 May 6, 2026
bcfc235
fixes
huangjeff5 May 6, 2026
10828d6
revert dict support
huangjeff5 May 6, 2026
d963659
clean up
huangjeff5 May 6, 2026
a8a6097
Simplify comments
huangjeff5 May 6, 2026
2b366f4
format
huangjeff5 May 6, 2026
d070a62
feat(py): generate middleware
huangjeff5 May 6, 2026
bdfe5a6
update comment
huangjeff5 May 6, 2026
d22c7a4
refactor to remove resolved_middleware, other cleanup
huangjeff5 May 6, 2026
7206f67
break cycle
huangjeff5 May 7, 2026
d359c3f
fix
huangjeff5 May 7, 2026
60223a3
format
huangjeff5 May 7, 2026
e4af768
Merge branch 'jh-dynamic-tools' into jh-mw
huangjeff5 May 7, 2026
6176396
address comments
huangjeff5 May 7, 2026
6361900
fixes
huangjeff5 May 7, 2026
5fca6df
fix format
huangjeff5 May 7, 2026
a2a7c17
use decorator instead of classvar
huangjeff5 May 7, 2026
57c3e0d
Update pyproject.toml
huangjeff5 May 7, 2026
d43ba8e
fix format
huangjeff5 May 8, 2026
8b0db35
fix format
huangjeff5 May 8, 2026
ea62faf
remove middleware plugin (moved to jh-mw-plugin)
huangjeff5 May 8, 2026
24e463f
remove
huangjeff5 May 8, 2026
a555065
update uv lock
huangjeff5 May 8, 2026
72f0c5f
address comments
huangjeff5 May 8, 2026
20cd6d2
Update _prompt.py
huangjeff5 May 8, 2026
4063c6e
fix format
huangjeff5 May 8, 2026
573b5f7
Merge branch 'jh-mw' of https://github.com/firebase/genkit into jh-mw
huangjeff5 May 8, 2026
a9e5e40
Refactor to expose registry thru hook params
huangjeff5 May 12, 2026
0260151
fix lint
huangjeff5 May 12, 2026
067c3ac
revert uv lock changes
huangjeff5 May 12, 2026
12a749b
make comments more readable on narrow viewports
huangjeff5 May 12, 2026
f514f84
bind call state at resolve time
huangjeff5 May 12, 2026
6dbf2fe
clean up wrap_tool signature
huangjeff5 May 12, 2026
b8ca46e
wire up executable prompt flow to use middleware
huangjeff5 May 12, 2026
d5c9067
fix bug bash issue
huangjeff5 May 13, 2026
298c31a
apply loop local fix
huangjeff5 May 14, 2026
229946d
Merge branch 'main' into jh-mw
huangjeff5 May 14, 2026
48c2dc5
fix bug bash bug
huangjeff5 May 15, 2026
22267ec
Merge branch 'main' into jh-mw
huangjeff5 May 15, 2026
6d672c5
fix mw not being applied in dev UI
huangjeff5 May 17, 2026
a102b4b
fix format
huangjeff5 May 17, 2026
f1715e4
clarify comment
huangjeff5 May 17, 2026
79889e1
clean up comments
huangjeff5 May 17, 2026
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
3 changes: 3 additions & 0 deletions py/packages/genkit/src/genkit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
Media,
MediaPart,
Metadata,
MiddlewareRef,
Part,
ReasoningPart,
Role,
Expand Down Expand Up @@ -131,6 +132,8 @@
'DocumentPart',
# Plugin interface
'Plugin',
# Middleware references (wire form for use= parameter)
'MiddlewareRef',
Comment thread
huangjeff5 marked this conversation as resolved.
# AI runtime
'ActionKind',
'ActionRunContext',
Expand Down
90 changes: 70 additions & 20 deletions py/packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,16 @@
)
from genkit._ai._formats import built_in_formats
from genkit._ai._formats._types import FormatDef
from genkit._ai._generate import define_generate_action, generate_action, registry_with_inline_tools
from genkit._ai._generate import (
define_generate_action,
generate_action,
registry_with_inline_middleware,
registry_with_inline_tools,
)
from genkit._ai._model import (
Message,
ModelConfig,
ModelFn,
ModelMiddleware,
ModelResponse,
ModelResponseChunk,
define_model,
Expand Down Expand Up @@ -90,6 +94,7 @@
from genkit._core._environment import is_dev_environment
from genkit._core._error import GenkitError
from genkit._core._logger import get_logger
from genkit._core._middleware import BaseMiddleware, MiddlewareDesc, new_middleware
from genkit._core._model import Document
from genkit._core._plugin import Plugin
from genkit._core._reflection import ReflectionServer, ServerSpec, create_reflection_asgi_app
Expand All @@ -102,6 +107,7 @@
EmbedRequest,
EvalRequest,
EvalResponse,
MiddlewareRef,
ModelInfo,
Operation,
Part,
Expand Down Expand Up @@ -157,6 +163,7 @@ def __init__(
self._initialize_registry(model, plugins)
# Ensure the default generate action is registered for async usage.
define_generate_action(self.registry)
self._register_plugin_middleware(plugins)
# In dev mode, start the reflection server immediately in a background
# daemon thread so it's available regardless of which web framework (or
# none) the user chooses.
Expand Down Expand Up @@ -425,7 +432,7 @@ def define_prompt(
metadata: dict[str, object] | None = None,
tools: Sequence[str | Tool] | None = None,
tool_choice: ToolChoice | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
input_schema: type[InputT],
output_schema: type[OutputT],
Expand Down Expand Up @@ -453,7 +460,7 @@ def define_prompt(
metadata: dict[str, object] | None = None,
tools: Sequence[str | Tool] | None = None,
tool_choice: ToolChoice | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
input_schema: type[InputT],
output_schema: dict[str, object] | str | None = None,
Expand Down Expand Up @@ -481,7 +488,7 @@ def define_prompt(
metadata: dict[str, object] | None = None,
tools: Sequence[str | Tool] | None = None,
tool_choice: ToolChoice | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
input_schema: dict[str, object] | str | None = None,
output_schema: type[OutputT],
Expand Down Expand Up @@ -509,7 +516,7 @@ def define_prompt(
metadata: dict[str, object] | None = None,
tools: Sequence[str | Tool] | None = None,
tool_choice: ToolChoice | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
input_schema: dict[str, object] | str | None = None,
output_schema: dict[str, object] | str | None = None,
Expand All @@ -535,7 +542,7 @@ def define_prompt(
metadata: dict[str, object] | None = None,
tools: Sequence[str | Tool] | None = None,
tool_choice: ToolChoice | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
input_schema: type | dict[str, object] | str | None = None,
output_schema: type | dict[str, object] | str | None = None,
Expand Down Expand Up @@ -725,6 +732,45 @@ def _initialize_registry(self, model: str | None, plugins: list[Plugin] | None)
else:
raise ValueError(f'Invalid {plugin=} provided to Genkit: must be of type `genkit.ai.Plugin`')

def _register_plugin_middleware(self, plugins: list[Plugin] | None) -> None:
"""Register middleware descriptors returned by ``Plugin.list_middleware``."""
if not plugins:
return
for plugin in plugins:
for desc in plugin.list_middleware():
self.registry.register_value('middleware', desc.name, desc)

def new_middleware(self, middleware_cls: type[BaseMiddleware]) -> MiddlewareDesc:
"""Build a ``MiddlewareDesc`` from a class."""
return new_middleware(middleware_cls)

def define_middleware(self, middleware_cls: type[BaseMiddleware]) -> MiddlewareDesc:
"""Register a middleware class on this app and return the descriptor.

Registering a class:

* Makes it visible to the **Dev UI** through the reflection API.
* Allows it to be referenced by name via :class:`MiddlewareRef`.

Equivalent to building the descriptor with ``new_middleware(cls)``
and wiring it through ``middleware_plugin([...])`` at construction
time, but usable after ``Genkit`` has already been built.

The factory instantiates ``middleware_cls(**config)`` each time a
request resolves the name via :class:`MiddlewareRef`, so the same
pydantic fields drive both:

* the inline path: ``use=[cls(...)]``
* the registered path: ``use=[MiddlewareRef(name=cls.name)]``

Returns:
The registered :class:`MiddlewareDesc`. Also available via
``registry.lookup_value('middleware', cls.name)``.
"""
desc = new_middleware(middleware_cls)
self.registry.register_value('middleware', desc.name, desc)
return desc

def run_main(self, coro: Coroutine[Any, Any, T]) -> T | None:
"""Run the user's main coroutine, blocking in dev mode for the reflection server."""
if not is_dev_environment():
Expand Down Expand Up @@ -799,7 +845,7 @@ async def generate(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
) -> ModelResponse[OutputT]: ...

Expand All @@ -826,7 +872,7 @@ async def generate(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
) -> ModelResponse[Any]: ...

Expand All @@ -851,7 +897,7 @@ async def generate(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
) -> ModelResponse[Any]:
"""Generate text or structured data using a language model.
Expand All @@ -860,6 +906,9 @@ async def generate(
is covariant: ``list[Tool]`` or ``list[str]`` are both assignable to
``Sequence[str | Tool]``, but not to ``list[str | Tool]``.
"""
registry = await registry_with_inline_tools(self.registry, tools)
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

child_registry = registry.new_child()
await register_tools(child_registry, tools)
refs = register_middleware(child_registry, middleware) # unnamed middleware get auto-generated names

child_registry = registry if registry.is_child else registry.new_child()
refs = registry_with_inline_middleware(child_registry, use) or None
prompt_config = PromptConfig(
model=model,
prompt=prompt,
Expand All @@ -879,13 +928,12 @@ async def generate(
output_schema=output_schema,
output_constrained=output_constrained,
docs=docs,
use=refs,
)
registry = await registry_with_inline_tools(self.registry, prompt_config.tools)
gen_options = await to_generate_action_options(registry, prompt_config)
return await generate_action(
registry,
child_registry,
gen_options,
middleware=use,
context=context if context else ActionRunContext._current_context(), # pyright: ignore[reportPrivateUsage]
)

Expand All @@ -912,7 +960,7 @@ def generate_stream(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
timeout: float | None = None,
) -> ModelStreamResponse[OutputT]: ...
Expand Down Expand Up @@ -940,7 +988,7 @@ def generate_stream(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
timeout: float | None = None,
) -> ModelStreamResponse[Any]: ...
Expand All @@ -966,14 +1014,17 @@ def generate_stream(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
timeout: float | None = None,
) -> ModelStreamResponse[Any]:
"""Stream generated text, returning a ModelStreamResponse with .stream and .response."""
channel: Channel[ModelResponseChunk, ModelResponse[Any]] = Channel(timeout=timeout)

async def _run_generate() -> ModelResponse[Any]:
registry = await registry_with_inline_tools(self.registry, tools)
Comment thread
huangjeff5 marked this conversation as resolved.
child_registry = registry if registry.is_child else registry.new_child()
refs = registry_with_inline_middleware(child_registry, use) or None
prompt_config = PromptConfig(
model=model,
prompt=prompt,
Expand All @@ -993,14 +1044,13 @@ async def _run_generate() -> ModelResponse[Any]:
output_schema=output_schema,
output_constrained=output_constrained,
docs=docs,
use=refs,
)
registry = await registry_with_inline_tools(self.registry, prompt_config.tools)
gen_options = await to_generate_action_options(registry, prompt_config)
return await generate_action(
registry,
child_registry,
gen_options,
on_chunk=lambda c: channel.send(c),
middleware=use,
context=context if context else ActionRunContext._current_context(), # pyright: ignore[reportPrivateUsage]
)

Expand Down Expand Up @@ -1184,7 +1234,7 @@ async def generate_operation(
output_content_type: str | None = None,
output_instructions: str | None = None,
output_constrained: bool | None = None,
use: list[ModelMiddleware] | None = None,
use: list[BaseMiddleware | MiddlewareRef] | None = None,
docs: list[Document] | None = None,
) -> Operation:
"""Generate content using a long-running model, returning an Operation to poll."""
Expand Down
Loading
Loading