-
Notifications
You must be signed in to change notification settings - Fork 139
Support Pydantic models #982
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
acroca
wants to merge
4
commits into
dapr:main
Choose a base branch
from
acroca:pydantic
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
4 commits
Select commit
Hold shift + click to select a range
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 |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # Copyright 2026 The Dapr Authors | ||
| # 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. | ||
| """Native Pydantic model support in Dapr workflows and activities. | ||
|
|
||
| Inputs annotated with a Pydantic BaseModel are reconstructed automatically on | ||
| the receiving side — no manual serialization is needed. Outputs are emitted | ||
| as plain JSON so the wire format stays interop-friendly with non-Python Dapr | ||
| apps. | ||
| """ | ||
|
|
||
| from dapr.ext.workflow import ( | ||
| DaprWorkflowClient, | ||
| DaprWorkflowContext, | ||
| WorkflowActivityContext, | ||
| WorkflowRuntime, | ||
| ) | ||
| from pydantic import BaseModel | ||
|
|
||
|
|
||
| class OrderRequest(BaseModel): | ||
| order_id: str | ||
| customer: str | ||
| amount: float | ||
|
|
||
|
|
||
| class OrderResult(BaseModel): | ||
| order_id: str | ||
| approved: bool | ||
| message: str | ||
|
|
||
|
|
||
| wfr = WorkflowRuntime() | ||
| instance_id = 'pydantic-demo' | ||
|
|
||
|
|
||
| @wfr.workflow(name='order_workflow') | ||
| def order_workflow(ctx: DaprWorkflowContext, order: OrderRequest): | ||
| # `order` arrives as a real OrderRequest instance — the runtime reads the | ||
| # annotation and reconstructs the model from the decoded JSON automatically. | ||
| if not ctx.is_replaying: | ||
| print( | ||
| f'[workflow] received order {order.order_id} ' | ||
| f'for {order.customer} amount={order.amount}', | ||
| flush=True, | ||
| ) | ||
| raw = yield ctx.call_activity(approve_order, input=order) | ||
| # Activity results come back as a plain dict. One line turns them into a | ||
| # typed instance. | ||
| result = OrderResult.model_validate(raw) | ||
| if not ctx.is_replaying: | ||
| print( | ||
| f'[workflow] activity returned approved={result.approved}', | ||
| flush=True, | ||
| ) | ||
| return result | ||
|
|
||
|
|
||
| @wfr.activity(name='approve_order') | ||
| def approve_order(ctx: WorkflowActivityContext, order: OrderRequest) -> OrderResult: | ||
| # Same story: `order` is already an OrderRequest instance here. | ||
| print(f'[activity] approving order {order.order_id}', flush=True) | ||
| if order.amount <= 100.0: | ||
| return OrderResult(order_id=order.order_id, approved=True, message='auto-approved') | ||
| return OrderResult(order_id=order.order_id, approved=False, message='needs review') | ||
|
|
||
|
|
||
| def main(): | ||
| wfr.start() | ||
| client = DaprWorkflowClient() | ||
|
|
||
| order = OrderRequest(order_id='O-100', customer='Acme', amount=42.0) | ||
| client.schedule_new_workflow(workflow=order_workflow, input=order, instance_id=instance_id) | ||
| state = client.wait_for_workflow_completion(instance_id, timeout_in_seconds=30) | ||
|
|
||
| # state.serialized_output is a JSON string — reconstruct a typed instance. | ||
| output = OrderResult.model_validate_json(state.serialized_output) | ||
| print( | ||
| f'[client] workflow output: order_id={output.order_id} ' | ||
| f'approved={output.approved} message={output.message}', | ||
| flush=True, | ||
| ) | ||
|
|
||
| client.purge_workflow(instance_id) | ||
| wfr.shutdown() | ||
|
|
||
|
|
||
| if __name__ == '__main__': | ||
| main() | ||
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 |
|---|---|---|
| @@ -1,2 +1,3 @@ | ||
| dapr-ext-workflow>=1.17.0.dev | ||
| dapr>=1.17.0.dev | ||
| pydantic>=2.0 |
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
151 changes: 151 additions & 0 deletions
151
ext/dapr-ext-workflow/dapr/ext/workflow/_model_protocol.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,151 @@ | ||
| # -*- coding: utf-8 -*- | ||
|
|
||
| """ | ||
| Copyright 2026 The Dapr Authors | ||
| 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. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import inspect | ||
| import typing | ||
| from functools import lru_cache | ||
| from types import SimpleNamespace | ||
| from typing import Any, Callable, Optional | ||
|
|
||
| # A "model" here is anything that implements the Pydantic v2 shape: | ||
| # - model_dump(self, ...) -> dict | ||
| # - cls.model_validate(value) -> instance | ||
| # We duck-type on these names rather than importing pydantic so the SDK has no | ||
| # hard dependency on pydantic (or any specific version of it). SQLModel, | ||
| # FastAPI response models, and custom classes mirroring the protocol all work. | ||
|
|
||
|
|
||
| def is_model(obj: Any) -> bool: | ||
| """Whether obj implements the model protocol (model_dump + model_validate).""" | ||
| return is_model_class(type(obj)) | ||
|
|
||
|
|
||
| def is_model_class(cls: Any) -> bool: | ||
| """Whether cls is a class implementing the model protocol.""" | ||
| return ( | ||
| inspect.isclass(cls) | ||
| and callable(getattr(cls, 'model_dump', None)) | ||
| and callable(getattr(cls, 'model_validate', None)) | ||
| ) | ||
|
|
||
|
|
||
| @lru_cache(maxsize=None) | ||
| def _supports_mode_kwarg(cls: type) -> bool: | ||
| """Whether cls.model_dump accepts a `mode` keyword (Pydantic v2 signature).""" | ||
| try: | ||
| sig = inspect.signature(cls.model_dump) | ||
| except (TypeError, ValueError): | ||
| return False | ||
| params = sig.parameters | ||
| if 'mode' in params: | ||
| return True | ||
| return any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) | ||
|
|
||
|
|
||
| def dump_model(model: Any) -> Any: | ||
| """Serialize a model instance to a JSON-compatible primitive graph. | ||
|
|
||
| Prefers model_dump(mode='json') when supported so nested datetimes, enums, | ||
| and UUIDs render into JSON-safe primitives. Falls back to bare model_dump() | ||
| for protocol-compatible classes that don't accept the mode kwarg — those | ||
| classes are responsible for returning JSON-safe values themselves. | ||
| """ | ||
| if not is_model(model): | ||
| raise TypeError( | ||
| f'Expected a model-like object with model_dump/model_validate, ' | ||
| f'got {type(model).__name__}' | ||
| ) | ||
| cls = type(model) | ||
| if _supports_mode_kwarg(cls): | ||
| return model.model_dump(mode='json') | ||
| return model.model_dump() | ||
|
|
||
|
|
||
| def coerce_to_model(value: Any, cls: type) -> Any: | ||
| """Reconstruct a model instance from a decoded JSON payload. | ||
|
|
||
| Accepts dicts, SimpleNamespace (from the InternalJSONDecoder's | ||
| AUTO_SERIALIZED path), or already-instantiated models. Any other shape | ||
| raises TypeError so the failure surfaces at the activity/workflow | ||
| boundary rather than later as an attribute access error. | ||
| """ | ||
| if not is_model_class(cls): | ||
| raise TypeError(f'{cls!r} is not a model class (no model_dump/model_validate)') | ||
| if isinstance(value, cls): | ||
| return value | ||
| if isinstance(value, SimpleNamespace): | ||
| value = vars(value) | ||
| if isinstance(value, dict): | ||
| return cls.model_validate(value) | ||
| raise TypeError( | ||
| f'Cannot coerce value of type {type(value).__name__} into {cls.__name__}; ' | ||
| 'expected a dict, SimpleNamespace, or existing model instance.' | ||
| ) | ||
|
|
||
|
|
||
| def resolve_input(fn: Callable[..., Any]) -> tuple[bool, Optional[type]]: | ||
| """Inspect fn's input parameter. | ||
|
|
||
| Returns (accepts_input, model_class): | ||
| - accepts_input is True when fn declares a second positional parameter | ||
| (beyond the context) — the runtime must then pass the input through | ||
| even when it is None, so `Optional[Model]` works without a default. | ||
| - model_class is the model class annotated on that parameter, or None | ||
| when there is no annotation or the annotation is not a model. | ||
| Optional[Model] and Model | None are unwrapped to Model. | ||
| """ | ||
| try: | ||
| sig = inspect.signature(fn) | ||
| except (TypeError, ValueError): | ||
| return False, None | ||
|
|
||
| params = list(sig.parameters.values()) | ||
| if len(params) < 2: | ||
| return False, None | ||
|
|
||
| annotation = params[1].annotation | ||
| if annotation is inspect.Parameter.empty: | ||
| return True, None | ||
|
|
||
| if isinstance(annotation, str): | ||
| try: | ||
| hints = typing.get_type_hints(fn) | ||
| annotation = hints.get(params[1].name, annotation) | ||
| except Exception: | ||
| return True, None | ||
|
|
||
| annotation = _unwrap_optional(annotation) | ||
| return True, (annotation if is_model_class(annotation) else None) | ||
|
|
||
|
|
||
| def _unwrap_optional(annotation: Any) -> Any: | ||
| """Unwrap Optional[X] / X | None to X. Leaves other annotations unchanged.""" | ||
| origin = typing.get_origin(annotation) | ||
| if origin is typing.Union or _is_pep604_union(origin): | ||
| args = [a for a in typing.get_args(annotation) if a is not type(None)] | ||
| if len(args) == 1: | ||
| return args[0] | ||
| return annotation | ||
|
|
||
|
|
||
| def _is_pep604_union(origin: Any) -> bool: | ||
| try: | ||
| from types import UnionType # type: ignore[attr-defined] | ||
|
|
||
| return origin is UnionType | ||
| except ImportError: | ||
| return False |
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.