-
Notifications
You must be signed in to change notification settings - Fork 3k
feat: Add Temporal integration and deterministic runtime support #3920
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
Closed
Closed
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
59d946d
feat: Add Temporal integration and deterministic runtime support
marcusmotill 81a5935
test: Add unit tests for runtime and Temporal integration
marcusmotill 1a63985
fix(temporal): Use robust argument binding and remove unused variable
marcusmotill 389f116
update to plugin strategy
marcusmotill b90ee97
add readme and updates
marcusmotill abea6e6
move activity registration
marcusmotill 6b83d77
better naming
marcusmotill 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
Empty file.
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,151 @@ | ||
| # Copyright 2025 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. | ||
|
|
||
| """Temporal integration helpers for ADK.""" | ||
|
|
||
| import functools | ||
marcusmotill marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| from typing import Any, AsyncGenerator, Callable, Optional, List | ||
|
|
||
| from temporalio import workflow, activity | ||
| from google.adk.models import BaseLlm, LlmRequest, LlmResponse, LLMRegistry | ||
| from google.genai import types | ||
|
|
||
|
|
||
| def activity_as_tool( | ||
| activity_def: Callable, | ||
| **activity_options: Any | ||
| ) -> Callable: | ||
| """Wraps a Temporal Activity Definition into an ADK-compatible tool. | ||
|
|
||
| Args: | ||
| activity_def: The Temporal activity definition (decorated with @activity.defn). | ||
| **activity_options: Options to pass to workflow.execute_activity | ||
| (e.g. start_to_close_timeout, retry_policy). | ||
|
|
||
| Returns: | ||
| A callable tool that executes the activity when invoked. | ||
| """ | ||
|
|
||
| # We create a wrapper that delegates to workflow.execute_activity | ||
| async def tool_wrapper(*args, **kwargs) -> Any: | ||
| # Note: ADK tools usually pass args/kwargs strictly matched to signature. | ||
| # Activities expect positional args in a list if 'args' is used. | ||
| # If the tool signature matches the activity signature, we can pass args. | ||
| # It's safer if activity takes Pydantic models or simple types. | ||
|
|
||
| # We assume strict positional argument mapping for now, or simplistic kwargs handling if supported. | ||
| # Temporal Python SDK typically invokes activities with `args=[...]`. | ||
|
|
||
| return await workflow.execute_activity( | ||
| activity_def, | ||
| args=list(args) + list(kwargs.values()) if kwargs else list(args), | ||
| **activity_options | ||
| ) | ||
marcusmotill marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # Copy metadata so ADK can inspect the tool (name, docstring, annotations) | ||
| # ADK uses this to generate the tool schema for the LLM. | ||
| tool_wrapper.__doc__ = activity_def.__doc__ | ||
| tool_wrapper.__name__ = getattr(activity_def, "name", activity_def.__name__) | ||
|
|
||
| # Attempt to copy annotations if they exist | ||
| if hasattr(activity_def, "__annotations__"): | ||
| tool_wrapper.__annotations__ = activity_def.__annotations__ | ||
|
|
||
| # CRITICAL: Copy signature so FunctionTool can generate correct parameters schema | ||
| try: | ||
| import inspect | ||
| tool_wrapper.__signature__ = inspect.signature(activity_def) | ||
marcusmotill marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| except Exception: | ||
| pass # Fallback if signature copy fails (e.g. builtins) | ||
|
|
||
| return tool_wrapper | ||
|
|
||
|
|
||
| @activity.defn | ||
| async def generate_content_activity(request: LlmRequest) -> List[LlmResponse]: | ||
| """Generic activity to invoke an LLM via ADK's LLMRegistry. | ||
|
|
||
| The model name is expected to be in `request.model`. | ||
| """ | ||
| if not request.model: | ||
| raise ValueError("LlmRequest.model must be set when using generate_content_activity.") | ||
|
|
||
| llm = LLMRegistry.new_llm(request.model) | ||
| return [response async for response in llm.generate_content_async(request)] | ||
|
|
||
|
|
||
| class TemporalModel(BaseLlm): | ||
| """An ADK ModelWrapper that executes content generation as a Temporal Activity. | ||
|
|
||
| This effectively delegates the 'generate_content' call to an external Activity, | ||
| ensuring that the network I/O to Vertex/Gemini is recorded in Temporal history. | ||
| """ | ||
|
|
||
| activity_def: Callable | ||
| activity_options: dict[str, Any] | ||
|
|
||
| def __init__( | ||
| self, | ||
| model_name: str, | ||
| activity_def: Callable = generate_content_activity, | ||
| **activity_options: Any | ||
| ): | ||
| """Initializes the TemporalModel. | ||
|
|
||
| Args: | ||
| model_name: The name of the model to report to ADK. | ||
| activity_def: The Temporal activity definition to invoke. | ||
| Defaults to `generate_content_activity`. | ||
| **activity_options: Options for workflow.execute_activity. | ||
| """ | ||
| super().__init__( | ||
| model=model_name, | ||
| activity_def=activity_def, | ||
| activity_options=activity_options | ||
| ) | ||
|
|
||
| async def generate_content_async( | ||
| self, | ||
| llm_request: LlmRequest, | ||
| stream: bool = False | ||
| ) -> AsyncGenerator[LlmResponse, None]: | ||
| """Generates content by calling the configured Temporal Activity.""" | ||
|
|
||
| # Ensure model name is carried in the request for the generic activity | ||
| if not llm_request.model: | ||
| llm_request.model = self.model | ||
|
|
||
| # Note: Temporal Activities are not typically streaming in the Python SDK | ||
| # in the way python async generators work (streaming back to workflow is complex). | ||
| # Standard approach is to return the full response. | ||
| # We will assume non-streaming activity execution for now. | ||
|
|
||
| # Execute the activity | ||
| responses: List[LlmResponse] = await workflow.execute_activity( | ||
| self.activity_def, | ||
| args=[llm_request], | ||
| **self.activity_options | ||
| ) | ||
|
|
||
| # Yield the responses | ||
| for response in responses: | ||
| yield response | ||
|
|
||
| @classmethod | ||
| def default_activities(cls) -> List[Callable]: | ||
| """Returns the default activities used by this model wrapper. | ||
|
|
||
| Useful for registering activities with the Temporal Worker. | ||
| """ | ||
| return [generate_content_activity] | ||
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,53 @@ | ||
| # Copyright 2025 Google LLC | ||
|
Collaborator
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. Thank you for the contribution! Could you move this to the platform folder? Let's have two files, one for uuid and one for time. https://github.com/google/adk-python/tree/main/src/google/adk/platform |
||
| # | ||
| # 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. | ||
|
|
||
| """Runtime module for abstracting system primitives like time and UUIDs.""" | ||
|
|
||
| import time | ||
| import uuid | ||
| from typing import Callable | ||
|
|
||
| _time_provider: Callable[[], float] = time.time | ||
| _id_provider: Callable[[], str] = lambda: str(uuid.uuid4()) | ||
|
|
||
|
|
||
| def set_time_provider(provider: Callable[[], float]) -> None: | ||
| """Sets the provider for the current time. | ||
|
|
||
| Args: | ||
| provider: A callable that returns the current time in seconds since the | ||
| epoch. | ||
| """ | ||
| global _time_provider | ||
| _time_provider = provider | ||
|
|
||
|
|
||
| def set_id_provider(provider: Callable[[], str]) -> None: | ||
| """Sets the provider for generating unique IDs. | ||
|
|
||
| Args: | ||
| provider: A callable that returns a unique ID string. | ||
| """ | ||
| global _id_provider | ||
| _id_provider = provider | ||
|
|
||
|
|
||
| def get_time() -> float: | ||
| """Returns the current time in seconds since the epoch.""" | ||
| return _time_provider() | ||
|
|
||
|
|
||
| def new_uuid() -> str: | ||
| """Returns a new unique ID.""" | ||
| return _id_provider() | ||
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 |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| # Temporal Integration Tests | ||
|
|
||
| The file `manual_test_temporal_integration.py` contains integration tests for ADK's Temporal support. | ||
| It is named `manual_test_...` to be excluded from standard CI/test runs because it requires: | ||
|
|
||
| 1. **Local Temporal Server**: You must have a Temporal server running locally (e.g., via `temporal server start-dev`). | ||
| 2. **GCP Credentials**: Environment variables `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` must be set. | ||
| 3. **Local Environment**: It assumes `localhost:7233`. | ||
|
|
||
| ## How to Run | ||
|
|
||
| 1. Start Temporal Server: | ||
| ```bash | ||
| temporal server start-dev | ||
| ``` | ||
|
|
||
| 2. Run the test directly: | ||
| ```bash | ||
| export GOOGLE_CLOUD_PROJECT="your-project" | ||
| export GOOGLE_CLOUD_LOCATION="us-central1" | ||
|
|
||
| uv run pytest tests/integration/manual_test_temporal_integration.py | ||
| ``` |
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.
Nice, and if you do any logging from workflow contexts in ADK, you'll want to modify thoes calls as well.