-
Notifications
You must be signed in to change notification settings - Fork 712
feat(py): integrate DAP into generate call, expand wildcards #5075
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
11
commits into
jh-dap-pr1
Choose a base branch
from
jh-dap-pr2
base: jh-dap-pr1
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 1 commit
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
0a78bed
feat(py): effective registry per generate call, wildcard DAP tools, g…
huangjeff5 f134af9
fix
huangjeff5 76f32e5
format and address comment
huangjeff5 190050c
refactor resolve action
huangjeff5 3a523ce
Merge branch 'jh-dap-pr1' into jh-dap-pr2
huangjeff5 8391a4e
Add shadowing teest
huangjeff5 2fa7db6
Merge branch 'jh-dap-pr2' of https://github.com/firebase/genkit into …
huangjeff5 67dffed
fixes
huangjeff5 9dd5e54
fix format
huangjeff5 15b1ece
Stop doing the plugin search fallback
huangjeff5 5b0d390
add comment
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
236 changes: 236 additions & 0 deletions
236
py/packages/genkit/tests/genkit/ai/dynamic_tools_generate_test.py
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,236 @@ | ||
| # Copyright 2026 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 | ||
|
|
||
| """Tests for DAP-backed tool resolution in the generate loop.""" | ||
|
|
||
| import pytest | ||
| from pydantic import BaseModel | ||
|
|
||
| from genkit._ai._generate import expand_wildcard_tools, generate_action | ||
| from genkit._ai._testing import define_programmable_model | ||
| from genkit._core._action import Action, ActionKind, ActionRunContext | ||
| from genkit._core._dap import DapValue, define_dynamic_action_provider | ||
| from genkit._core._model import GenerateActionOptions, ModelRequest | ||
| from genkit._core._registry import Registry | ||
| from genkit._core._typing import ( | ||
| FinishReason, | ||
| Part, | ||
| Role, | ||
| TextPart, | ||
| ToolRequest, | ||
| ToolRequestPart, | ||
| ) | ||
| from genkit import Genkit, Message, ModelResponse, ModelResponseChunk | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # Helpers | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| def _text_response(text: str) -> ModelResponse: | ||
| return ModelResponse( | ||
| message=Message(role=Role.MODEL, content=[Part(root=TextPart(text=text))]), | ||
| finish_reason=FinishReason.STOP, | ||
| ) | ||
|
|
||
|
|
||
| def _tool_call_response(tool_name: str, input: dict) -> ModelResponse: | ||
| return ModelResponse( | ||
| message=Message( | ||
| role=Role.MODEL, | ||
| content=[Part(root=ToolRequestPart(tool_request=ToolRequest(name=tool_name, input=input, ref=tool_name)))], | ||
| ), | ||
| finish_reason=FinishReason.STOP, | ||
| ) | ||
|
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # expand_wildcard_tools | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_expand_wildcard_all() -> None: | ||
| """'provider:tool/*' expands to all tools from the DAP.""" | ||
| registry = Registry() | ||
|
|
||
| async def tool_fn(x: str) -> str: | ||
| return x | ||
|
|
||
| t1 = registry.register_action(name='echo', kind=ActionKind.TOOL, fn=tool_fn, metadata={'name': 'echo'}) | ||
| t2 = registry.register_action(name='ping', kind=ActionKind.TOOL, fn=tool_fn, metadata={'name': 'ping'}) | ||
|
|
||
| async def dap_fn() -> DapValue: | ||
| return {'tool': [t1, t2]} | ||
|
|
||
| define_dynamic_action_provider(registry, 'mcp', dap_fn) | ||
|
|
||
| result = await expand_wildcard_tools(registry, ['mcp:tool/*']) | ||
| assert sorted(result) == ['echo', 'ping'] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_expand_wildcard_prefix() -> None: | ||
| """'provider:tool/prefix*' expands only matching tools.""" | ||
| registry = Registry() | ||
|
|
||
| async def tool_fn(x: str) -> str: | ||
| return x | ||
|
|
||
| t1 = registry.register_action(name='get_weather', kind=ActionKind.TOOL, fn=tool_fn, metadata={'name': 'get_weather'}) | ||
| t2 = registry.register_action(name='get_time', kind=ActionKind.TOOL, fn=tool_fn, metadata={'name': 'get_time'}) | ||
| t3 = registry.register_action(name='set_alarm', kind=ActionKind.TOOL, fn=tool_fn, metadata={'name': 'set_alarm'}) | ||
|
|
||
| async def dap_fn() -> DapValue: | ||
| return {'tool': [t1, t2, t3]} | ||
|
|
||
| define_dynamic_action_provider(registry, 'mcp', dap_fn) | ||
|
|
||
| result = await expand_wildcard_tools(registry, ['mcp:tool/get_*']) | ||
| assert sorted(result) == ['get_time', 'get_weather'] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_non_wildcard_names_pass_through() -> None: | ||
| """Non-wildcard names are returned unchanged.""" | ||
| registry = Registry() | ||
| result = await expand_wildcard_tools(registry, ['my_tool', 'other_tool']) | ||
| assert result == ['my_tool', 'other_tool'] | ||
|
|
||
|
huangjeff5 marked this conversation as resolved.
|
||
|
|
||
| # --------------------------------------------------------------------------- | ||
| # DAP tools resolved inside generate loop | ||
| # --------------------------------------------------------------------------- | ||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_dap_tool_resolved_in_generate() -> None: | ||
| """generate resolves a tool that lives only in a DAP, calls it, and gets final answer.""" | ||
| ai = Genkit() | ||
| pm, _ = define_programmable_model(ai) | ||
|
|
||
| call_log: list[str] = [] | ||
|
|
||
| class EchoInput(BaseModel): | ||
| text: str | ||
|
|
||
| async def echo_fn(inp: EchoInput) -> str: | ||
| call_log.append(inp.text) | ||
| return f'echoed:{inp.text}' | ||
|
|
||
| echo_action = ai.registry.register_action( | ||
|
huangjeff5 marked this conversation as resolved.
Outdated
|
||
| name='echo', | ||
| kind=ActionKind.TOOL, | ||
| fn=echo_fn, | ||
| metadata={'name': 'echo'}, | ||
| ) | ||
|
|
||
| async def dap_fn() -> DapValue: | ||
| return {'tool': [echo_action]} | ||
|
|
||
| ai.define_dynamic_action_provider('mcp', dap_fn) | ||
|
|
||
| # Turn 1: model asks to call 'echo' | ||
| pm.responses = [ | ||
| _tool_call_response('echo', {'text': 'hello'}), | ||
| _text_response('done'), | ||
| ] | ||
|
|
||
| response = await ai.generate( | ||
| model='programmableModel', | ||
| prompt='use echo', | ||
| tools=['echo'], | ||
| ) | ||
|
|
||
| assert response.text == 'done' | ||
| assert call_log == ['hello'] | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_dap_tools_do_not_pollute_root_registry() -> None: | ||
| """After generate, DAP-resolved tools are not cached in the root registry.""" | ||
| ai = Genkit() | ||
| pm, _ = define_programmable_model(ai) | ||
|
|
||
| class Inp(BaseModel): | ||
| x: str | ||
|
|
||
| async def tool_fn(inp: Inp) -> str: | ||
| return inp.x | ||
|
|
||
| # Create an Action directly — NOT registered in root via register_action | ||
| dap_only_action = Action(name='dap_only_tool', kind=ActionKind.TOOL, fn=tool_fn, | ||
| metadata={'name': 'dap_only_tool'}) | ||
|
|
||
| async def dap_fn() -> DapValue: | ||
| return {'tool': [dap_only_action]} | ||
|
|
||
| ai.define_dynamic_action_provider('mcp', dap_fn) | ||
|
|
||
| pm.responses = [_text_response('no tools called')] | ||
|
|
||
| await ai.generate( | ||
| model='programmableModel', | ||
| prompt='hi', | ||
| tools=['dap_only_tool'], | ||
| ) | ||
|
|
||
| # Root registry should NOT have dap_only_tool cached — it was never registered there | ||
| root_tools = ai.registry._entries.get(ActionKind.TOOL, {}) | ||
| assert 'dap_only_tool' not in root_tools | ||
|
|
||
|
|
||
| @pytest.mark.asyncio | ||
| async def test_wildcard_tools_in_generate() -> None: | ||
| """Wildcard tool pattern is expanded before generate resolves tools.""" | ||
| ai = Genkit() | ||
| pm, _ = define_programmable_model(ai) | ||
|
|
||
| call_log: list[str] = [] | ||
|
|
||
| class InpA(BaseModel): | ||
| x: str | ||
|
|
||
| class InpB(BaseModel): | ||
| x: str | ||
|
|
||
| async def tool_a_fn(inp: InpA) -> str: | ||
| call_log.append(f'a:{inp.x}') | ||
| return f'a:{inp.x}' | ||
|
|
||
| async def tool_b_fn(inp: InpB) -> str: | ||
| call_log.append(f'b:{inp.x}') | ||
| return f'b:{inp.x}' | ||
|
|
||
| tool_a = ai.registry.register_action(name='tool_a', kind=ActionKind.TOOL, fn=tool_a_fn, metadata={'name': 'tool_a'}) | ||
| tool_b = ai.registry.register_action(name='tool_b', kind=ActionKind.TOOL, fn=tool_b_fn, metadata={'name': 'tool_b'}) | ||
|
|
||
| async def dap_fn() -> DapValue: | ||
| return {'tool': [tool_a, tool_b]} | ||
|
|
||
| ai.define_dynamic_action_provider('mcp', dap_fn) | ||
|
|
||
| pm.responses = [ | ||
| _tool_call_response('tool_a', {'x': 'hi'}), | ||
| _text_response('finished'), | ||
| ] | ||
|
|
||
| response = await ai.generate( | ||
| model='programmableModel', | ||
| prompt='use a tool', | ||
| tools=['mcp:tool/*'], | ||
| ) | ||
|
|
||
| assert response.text == 'finished' | ||
| assert call_log == ['a:hi'] | ||
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.
This works a bit differently from the javascript implementation and there is a critical bug here regarding how the expanded tool names are returned.
Currently, the function strips the provider prefix and appends only the unqualified tool name:
This creates a serious conflict resolution issue because it drops the explicit provider binding. When the generation loop later attempts to resolve this unqualified name (e.g.,
'echo'), the registry will fall back to querying all registered DAPs in registration order to find a match.The Bug Scenario:
mcp1(registered first) andmcp2(registered second).'echo'.tools=['mcp2:tool/*'].['echo'].'echo', it asks the DAPs in order.mcp1replies first saying "I have echo!" and its tool is executed instead ofmcp2's.The Fix: To maintain the explicit provider binding (and match how the JS implementation behaves), we should reconstruct the fully-qualified DAP key so the registry knows exactly which provider to query later on:
This guarantees the executed tool will strictly belong to the provider the user requested.
It would also be a good idea to have a test for this scenario.
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.
OK good catch, fixed this issue. The scenario above should also be blocked by
assert_valid_tool_names(), since if there are two tools in scope with the same short name that will raise.