-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Add DynamicToolset support in Temporal
#3682
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
dsfaccini
wants to merge
9
commits into
pydantic:main
Choose a base branch
from
dsfaccini:add-support-for-toolset-decorator-in-temporal
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.
+1,681
−53
Open
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
eefa9bf
add support for toolset decorator in temporal
dsfaccini 130be84
Merge branch 'main' into add-support-for-toolset-decorator-in-temporal
dsfaccini 1fc6afc
Merge branch 'main' into add-support-for-toolset-decorator-in-temporal
dsfaccini cb1e005
fix tests
dsfaccini 548c2d5
small review changes
dsfaccini e585bfc
refactor: address review feedback for DynamicToolset Temporal support
dsfaccini e0e183d
fix example
dsfaccini a3580c8
coverage
dsfaccini c2d05ce
apply review fixes
dsfaccini 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
172 changes: 172 additions & 0 deletions
172
pydantic_ai_slim/pydantic_ai/durable_exec/temporal/_dynamic_toolset.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,172 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Callable | ||
| from dataclasses import dataclass | ||
| from typing import Any, Literal | ||
|
|
||
| from pydantic import ConfigDict, with_config | ||
| from temporalio import activity, workflow | ||
| from temporalio.workflow import ActivityConfig | ||
| from typing_extensions import Self | ||
|
|
||
| from pydantic_ai import ToolsetTool | ||
| from pydantic_ai.exceptions import UserError | ||
| from pydantic_ai.tools import AgentDepsT, RunContext, ToolDefinition | ||
| from pydantic_ai.toolsets._dynamic import DynamicToolset | ||
| from pydantic_ai.toolsets.external import TOOL_SCHEMA_VALIDATOR | ||
|
|
||
| from ._run_context import TemporalRunContext | ||
| from ._toolset import ( | ||
| CallToolParams, | ||
| CallToolResult, | ||
| TemporalWrapperToolset, | ||
| ) | ||
|
|
||
|
|
||
| @dataclass | ||
| @with_config(ConfigDict(arbitrary_types_allowed=True)) | ||
| class _GetToolsParams: | ||
| serialized_run_context: Any | ||
|
|
||
|
|
||
| @dataclass | ||
| class _ToolInfo: | ||
| """Serializable tool information returned from get_tools_activity.""" | ||
|
|
||
| tool_def: ToolDefinition | ||
| max_retries: int | ||
|
|
||
|
|
||
| class TemporalDynamicToolset(TemporalWrapperToolset[AgentDepsT]): | ||
| """Temporal wrapper for DynamicToolset. | ||
|
|
||
| This provides static activities (get_tools, call_tool) that are registered at worker start time, | ||
| while the actual toolset selection happens dynamically inside the activities where I/O is allowed. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| toolset: DynamicToolset[AgentDepsT], | ||
| *, | ||
| activity_name_prefix: str, | ||
| activity_config: ActivityConfig, | ||
| tool_activity_config: dict[str, ActivityConfig | Literal[False]], | ||
| deps_type: type[AgentDepsT], | ||
| run_context_type: type[TemporalRunContext[AgentDepsT]] = TemporalRunContext[AgentDepsT], | ||
| ): | ||
| super().__init__(toolset) | ||
| self.activity_config = activity_config | ||
| self.tool_activity_config = tool_activity_config | ||
| self.run_context_type = run_context_type | ||
|
|
||
| async def get_tools_activity(params: _GetToolsParams, deps: AgentDepsT) -> dict[str, _ToolInfo]: | ||
| """Activity that calls the dynamic function and returns tool definitions.""" | ||
| ctx = self.run_context_type.deserialize_run_context(params.serialized_run_context, deps=deps) | ||
|
|
||
| async with self.wrapped: | ||
| tools = await self.wrapped.get_tools(ctx) | ||
| return { | ||
| name: _ToolInfo(tool_def=tool.tool_def, max_retries=tool.max_retries) | ||
| for name, tool in tools.items() | ||
| } | ||
|
|
||
| get_tools_activity.__annotations__['deps'] = deps_type | ||
|
|
||
| self.get_tools_activity = activity.defn(name=f'{activity_name_prefix}__dynamic_toolset__{self.id}__get_tools')( | ||
| get_tools_activity | ||
| ) | ||
|
|
||
| async def call_tool_activity(params: CallToolParams, deps: AgentDepsT) -> CallToolResult: | ||
| """Activity that instantiates the dynamic toolset and calls the tool.""" | ||
| ctx = self.run_context_type.deserialize_run_context(params.serialized_run_context, deps=deps) | ||
|
|
||
| async with self.wrapped: | ||
| tools = await self.wrapped.get_tools(ctx) | ||
| tool = tools.get(params.name) | ||
| if tool is None: # pragma: no cover | ||
| raise UserError( | ||
| f'Tool {params.name!r} not found in dynamic toolset {self.id!r}. ' | ||
| 'The dynamic toolset function may have returned a different toolset than expected.' | ||
| ) | ||
|
|
||
| return await self._call_tool_in_activity(params.name, params.tool_args, ctx, tool) | ||
|
|
||
| call_tool_activity.__annotations__['deps'] = deps_type | ||
|
|
||
| self.call_tool_activity = activity.defn(name=f'{activity_name_prefix}__dynamic_toolset__{self.id}__call_tool')( | ||
| call_tool_activity | ||
| ) | ||
|
|
||
| @property | ||
| def temporal_activities(self) -> list[Callable[..., Any]]: | ||
| return [self.get_tools_activity, self.call_tool_activity] | ||
|
|
||
| async def __aenter__(self) -> Self: | ||
| if not workflow.in_workflow(): | ||
| await self.wrapped.__aenter__() | ||
| return self | ||
|
|
||
| async def __aexit__(self, *args: Any) -> bool | None: | ||
| if not workflow.in_workflow(): | ||
| return await self.wrapped.__aexit__(*args) | ||
| return None | ||
|
|
||
| async def get_tools(self, ctx: RunContext[AgentDepsT]) -> dict[str, ToolsetTool[AgentDepsT]]: | ||
| if not workflow.in_workflow(): | ||
| return await super().get_tools(ctx) | ||
|
|
||
| serialized_run_context = self.run_context_type.serialize_run_context(ctx) | ||
| tool_infos = await workflow.execute_activity( | ||
| activity=self.get_tools_activity, | ||
| args=[ | ||
| _GetToolsParams(serialized_run_context=serialized_run_context), | ||
| ctx.deps, | ||
| ], | ||
| **self.activity_config, | ||
| ) | ||
| return {name: self._tool_for_tool_info(tool_info) for name, tool_info in tool_infos.items()} | ||
|
|
||
| async def call_tool( | ||
| self, | ||
| name: str, | ||
| tool_args: dict[str, Any], | ||
| ctx: RunContext[AgentDepsT], | ||
| tool: ToolsetTool[AgentDepsT], | ||
| ) -> Any: | ||
| if not workflow.in_workflow(): | ||
| return await super().call_tool(name, tool_args, ctx, tool) | ||
|
|
||
| tool_activity_config = self.tool_activity_config.get(name) | ||
| if tool_activity_config is False: # pragma: no cover | ||
| return await super().call_tool(name, tool_args, ctx, tool) | ||
|
|
||
| merged_config = self.activity_config | (tool_activity_config or {}) | ||
| serialized_run_context = self.run_context_type.serialize_run_context(ctx) | ||
| return self._unwrap_call_tool_result( | ||
| await workflow.execute_activity( | ||
| activity=self.call_tool_activity, | ||
| args=[ | ||
| CallToolParams( | ||
| name=name, | ||
| tool_args=tool_args, | ||
| serialized_run_context=serialized_run_context, | ||
| tool_def=tool.tool_def, | ||
| ), | ||
| ctx.deps, | ||
| ], | ||
| **merged_config, | ||
| ) | ||
| ) | ||
|
|
||
| def _tool_for_tool_info(self, tool_info: _ToolInfo) -> ToolsetTool[AgentDepsT]: | ||
| """Create a ToolsetTool from a _ToolInfo for use outside activities. | ||
|
|
||
| We use `TOOL_SCHEMA_VALIDATOR` here which just parses JSON without additional validation, | ||
| because the actual args validation happens inside `call_tool_activity`. | ||
| """ | ||
| return ToolsetTool( | ||
| toolset=self, | ||
| tool_def=tool_info.tool_def, | ||
| max_retries=tool_info.max_retries, | ||
| args_validator=TOOL_SCHEMA_VALIDATOR, | ||
| ) | ||
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
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.