-
Notifications
You must be signed in to change notification settings - Fork 738
feat(py): generate middleware #5253
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
Open
huangjeff5
wants to merge
57
commits into
main
Choose a base branch
from
jh-mw
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
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 2430401
child registry support
huangjeff5 f3807df
address comments
huangjeff5 7163a19
format
huangjeff5 2ecdab4
fix format
huangjeff5 ba80440
fix comment
huangjeff5 8c94e4d
address feedback
huangjeff5 e43ce55
fix type issue
huangjeff5 b50d6cf
more refactor
huangjeff5 007b158
fix format and pyrefly
huangjeff5 1c730cd
address comments
huangjeff5 4b66855
format
huangjeff5 d0d9027
dynamic tool support
huangjeff5 bdbea5a
add tool surface
huangjeff5 4b7af0b
Merge branch 'main' into jh-dynamic-tools
huangjeff5 bcfc235
fixes
huangjeff5 10828d6
revert dict support
huangjeff5 d963659
clean up
huangjeff5 a8a6097
Simplify comments
huangjeff5 2b366f4
format
huangjeff5 d070a62
feat(py): generate middleware
huangjeff5 bdfe5a6
update comment
huangjeff5 d22c7a4
refactor to remove resolved_middleware, other cleanup
huangjeff5 7206f67
break cycle
huangjeff5 d359c3f
fix
huangjeff5 60223a3
format
huangjeff5 e4af768
Merge branch 'jh-dynamic-tools' into jh-mw
huangjeff5 6176396
address comments
huangjeff5 6361900
fixes
huangjeff5 5fca6df
fix format
huangjeff5 a2a7c17
use decorator instead of classvar
huangjeff5 57c3e0d
Update pyproject.toml
huangjeff5 d43ba8e
fix format
huangjeff5 8b0db35
fix format
huangjeff5 ea62faf
remove middleware plugin (moved to jh-mw-plugin)
huangjeff5 24e463f
remove
huangjeff5 a555065
update uv lock
huangjeff5 72f0c5f
address comments
huangjeff5 20cd6d2
Update _prompt.py
huangjeff5 4063c6e
fix format
huangjeff5 573b5f7
Merge branch 'jh-mw' of https://github.com/firebase/genkit into jh-mw
huangjeff5 a9e5e40
Refactor to expose registry thru hook params
huangjeff5 0260151
fix lint
huangjeff5 067c3ac
revert uv lock changes
huangjeff5 12a749b
make comments more readable on narrow viewports
huangjeff5 f514f84
bind call state at resolve time
huangjeff5 6dbf2fe
clean up wrap_tool signature
huangjeff5 b8ca46e
wire up executable prompt flow to use middleware
huangjeff5 d5c9067
fix bug bash issue
huangjeff5 298c31a
apply loop local fix
huangjeff5 229946d
Merge branch 'main' into jh-mw
huangjeff5 48c2dc5
fix bug bash bug
huangjeff5 22267ec
Merge branch 'main' into jh-mw
huangjeff5 6d672c5
fix mw not being applied in dev UI
huangjeff5 a102b4b
fix format
huangjeff5 f1715e4
clarify comment
huangjeff5 79889e1
clean up comments
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
|
@@ -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 | ||
|
|
@@ -102,6 +107,7 @@ | |
| EmbedRequest, | ||
| EvalRequest, | ||
| EvalResponse, | ||
| MiddlewareRef, | ||
| ModelInfo, | ||
| Operation, | ||
| Part, | ||
|
|
@@ -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. | ||
|
|
@@ -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], | ||
|
|
@@ -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, | ||
|
|
@@ -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], | ||
|
|
@@ -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, | ||
|
|
@@ -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, | ||
|
|
@@ -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(): | ||
|
|
@@ -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]: ... | ||
|
|
||
|
|
@@ -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]: ... | ||
|
|
||
|
|
@@ -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. | ||
|
|
@@ -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) | ||
|
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. child_registry = registry.new_child() |
||
| 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, | ||
|
|
@@ -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] | ||
| ) | ||
|
|
||
|
|
@@ -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]: ... | ||
|
|
@@ -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]: ... | ||
|
|
@@ -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) | ||
|
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, | ||
|
|
@@ -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] | ||
| ) | ||
|
|
||
|
|
@@ -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.""" | ||
|
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.