|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass |
| 4 | +from datetime import timedelta |
| 5 | +from typing import Any, Callable |
| 6 | + |
| 7 | +from temporalio.common import Priority, RetryPolicy |
| 8 | +from temporalio.workflow import ActivityCancellationType, VersioningIntent |
| 9 | + |
| 10 | +from pydantic_ai._run_context import AgentDepsT, RunContext |
| 11 | + |
| 12 | + |
| 13 | +class _TemporalRunContext(RunContext[AgentDepsT]): |
| 14 | + _data: dict[str, Any] |
| 15 | + |
| 16 | + def __init__(self, **kwargs: Any): |
| 17 | + self._data = kwargs |
| 18 | + setattr( |
| 19 | + self, |
| 20 | + '__dataclass_fields__', |
| 21 | + {name: field for name, field in RunContext.__dataclass_fields__.items() if name in kwargs}, |
| 22 | + ) |
| 23 | + |
| 24 | + def __getattribute__(self, name: str) -> Any: |
| 25 | + try: |
| 26 | + return super().__getattribute__(name) |
| 27 | + except AttributeError as e: |
| 28 | + data = super().__getattribute__('_data') |
| 29 | + if name in data: |
| 30 | + return data[name] |
| 31 | + raise e # TODO: Explain how to make a new run context attribute available |
| 32 | + |
| 33 | + @classmethod |
| 34 | + def serialize_run_context(cls, ctx: RunContext[AgentDepsT]) -> dict[str, Any]: |
| 35 | + return { |
| 36 | + 'deps': ctx.deps, |
| 37 | + 'retries': ctx.retries, |
| 38 | + 'tool_call_id': ctx.tool_call_id, |
| 39 | + 'tool_name': ctx.tool_name, |
| 40 | + 'retry': ctx.retry, |
| 41 | + 'run_step': ctx.run_step, |
| 42 | + } |
| 43 | + |
| 44 | + @classmethod |
| 45 | + def deserialize_run_context(cls, ctx: dict[str, Any]) -> RunContext[AgentDepsT]: |
| 46 | + return cls(**ctx) |
| 47 | + |
| 48 | + |
| 49 | +@dataclass |
| 50 | +class TemporalSettings: |
| 51 | + """Settings for Temporal `execute_activity` and Pydantic AI-specific Temporal activity behavior.""" |
| 52 | + |
| 53 | + # Temporal settings |
| 54 | + task_queue: str | None = None |
| 55 | + schedule_to_close_timeout: timedelta | None = None |
| 56 | + schedule_to_start_timeout: timedelta | None = None |
| 57 | + start_to_close_timeout: timedelta | None = None |
| 58 | + heartbeat_timeout: timedelta | None = None |
| 59 | + retry_policy: RetryPolicy | None = None |
| 60 | + cancellation_type: ActivityCancellationType = ActivityCancellationType.TRY_CANCEL |
| 61 | + activity_id: str | None = None |
| 62 | + versioning_intent: VersioningIntent | None = None |
| 63 | + summary: str | None = None |
| 64 | + priority: Priority = Priority.default |
| 65 | + |
| 66 | + # Pydantic AI specific |
| 67 | + tool_settings: dict[str, dict[str, TemporalSettings]] | None = None |
| 68 | + |
| 69 | + def for_tool(self, toolset_id: str, tool_id: str) -> TemporalSettings: |
| 70 | + if self.tool_settings is None: |
| 71 | + return self |
| 72 | + return self.tool_settings.get(toolset_id, {}).get(tool_id, self) |
| 73 | + |
| 74 | + serialize_run_context: Callable[[RunContext], Any] = _TemporalRunContext.serialize_run_context |
| 75 | + deserialize_run_context: Callable[[dict[str, Any]], RunContext] = _TemporalRunContext.deserialize_run_context |
| 76 | + |
| 77 | + @property |
| 78 | + def execute_activity_kwargs(self) -> dict[str, Any]: |
| 79 | + return { |
| 80 | + 'task_queue': self.task_queue, |
| 81 | + 'schedule_to_close_timeout': self.schedule_to_close_timeout, |
| 82 | + 'schedule_to_start_timeout': self.schedule_to_start_timeout, |
| 83 | + 'start_to_close_timeout': self.start_to_close_timeout, |
| 84 | + 'heartbeat_timeout': self.heartbeat_timeout, |
| 85 | + 'retry_policy': self.retry_policy, |
| 86 | + 'cancellation_type': self.cancellation_type, |
| 87 | + 'activity_id': self.activity_id, |
| 88 | + 'versioning_intent': self.versioning_intent, |
| 89 | + 'summary': self.summary, |
| 90 | + 'priority': self.priority, |
| 91 | + } |
| 92 | + |
| 93 | + |
| 94 | +def initialize_temporal(): |
| 95 | + """Explicitly import types without which Temporal will not be able to serialize/deserialize `ModelMessage`s.""" |
| 96 | + from pydantic_ai.messages import ( # noqa F401 |
| 97 | + ModelResponse, # pyright: ignore[reportUnusedImport] |
| 98 | + ImageUrl, # pyright: ignore[reportUnusedImport] |
| 99 | + AudioUrl, # pyright: ignore[reportUnusedImport] |
| 100 | + DocumentUrl, # pyright: ignore[reportUnusedImport] |
| 101 | + VideoUrl, # pyright: ignore[reportUnusedImport] |
| 102 | + BinaryContent, # pyright: ignore[reportUnusedImport] |
| 103 | + UserContent, # pyright: ignore[reportUnusedImport] |
| 104 | + ) |
0 commit comments