|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | +import json |
| 4 | +from typing import Any, Callable, Optional, TYPE_CHECKING, Union |
| 5 | + |
| 6 | +from azure.durable_functions.models.DurableOrchestrationContext import ( |
| 7 | + DurableOrchestrationContext, |
| 8 | +) |
| 9 | +from azure.durable_functions.models.RetryOptions import RetryOptions |
| 10 | + |
| 11 | +from agents import RunContextWrapper, Tool |
| 12 | +from agents.function_schema import function_schema |
| 13 | +from agents.tool import FunctionTool |
| 14 | + |
| 15 | +from azure.durable_functions.models.Task import TaskBase |
| 16 | +from .task_tracker import TaskTracker |
| 17 | + |
| 18 | + |
| 19 | +if TYPE_CHECKING: |
| 20 | + # At type-check time we want all members / signatures for IDE & linters. |
| 21 | + _BaseDurableContext = DurableOrchestrationContext |
| 22 | +else: |
| 23 | + class _BaseDurableContext: # lightweight runtime stub |
| 24 | + """Runtime stub base class for delegation; real context is wrapped. |
| 25 | +
|
| 26 | + At runtime we avoid inheriting from DurableOrchestrationContext so that |
| 27 | + attribute lookups for its members are delegated via __getattr__ to the |
| 28 | + wrapped ``_context`` instance. |
| 29 | + """ |
| 30 | + |
| 31 | + __slots__ = () |
| 32 | + |
| 33 | + |
| 34 | +class DurableAIAgentContext(_BaseDurableContext): |
| 35 | + """Context for AI agents running in Azure Durable Functions orchestration. |
| 36 | +
|
| 37 | + Design |
| 38 | + ------ |
| 39 | + * Static analysis / IDEs: Appears to subclass ``DurableOrchestrationContext`` so |
| 40 | + you get autocompletion and type hints (under TYPE_CHECKING branch). |
| 41 | + * Runtime: Inherits from a trivial stub. All durable orchestration operations |
| 42 | + are delegated to the real ``DurableOrchestrationContext`` instance provided |
| 43 | + as ``context`` and stored in ``_context``. |
| 44 | +
|
| 45 | + Consequences |
| 46 | + ------------ |
| 47 | + * ``isinstance(DurableAIAgentContext, DurableOrchestrationContext)`` is **False** at |
| 48 | + runtime (expected). |
| 49 | + * Delegation via ``__getattr__`` works for every member of the real context. |
| 50 | + * No reliance on internal initialization side-effects of the durable SDK. |
| 51 | + """ |
| 52 | + |
| 53 | + def __init__( |
| 54 | + self, |
| 55 | + context: DurableOrchestrationContext, |
| 56 | + task_tracker: TaskTracker, |
| 57 | + model_retry_options: Optional[RetryOptions], |
| 58 | + ): |
| 59 | + self._context = context |
| 60 | + self._task_tracker = task_tracker |
| 61 | + self._model_retry_options = model_retry_options |
| 62 | + |
| 63 | + def call_activity( |
| 64 | + self, name: Union[str, Callable], input_: Optional[Any] = None |
| 65 | + ) -> TaskBase: |
| 66 | + """Schedule an activity for execution. |
| 67 | +
|
| 68 | + Parameters |
| 69 | + ---------- |
| 70 | + name: str | Callable |
| 71 | + Either the name of the activity function to call, as a string or, |
| 72 | + in the Python V2 programming model, the activity function itself. |
| 73 | + input_: Optional[Any] |
| 74 | + The JSON-serializable input to pass to the activity function. |
| 75 | +
|
| 76 | + Returns |
| 77 | + ------- |
| 78 | + Task |
| 79 | + A Durable Task that completes when the called activity function completes or fails. |
| 80 | + """ |
| 81 | + task = self._context.call_activity(name, input_) |
| 82 | + self._task_tracker.record_activity_call() |
| 83 | + return task |
| 84 | + |
| 85 | + def call_activity_with_retry( |
| 86 | + self, |
| 87 | + name: Union[str, Callable], |
| 88 | + retry_options: RetryOptions, |
| 89 | + input_: Optional[Any] = None, |
| 90 | + ) -> TaskBase: |
| 91 | + """Schedule an activity for execution with retry options. |
| 92 | +
|
| 93 | + Parameters |
| 94 | + ---------- |
| 95 | + name: str | Callable |
| 96 | + Either the name of the activity function to call, as a string or, |
| 97 | + in the Python V2 programming model, the activity function itself. |
| 98 | + retry_options: RetryOptions |
| 99 | + The retry options for the activity function. |
| 100 | + input_: Optional[Any] |
| 101 | + The JSON-serializable input to pass to the activity function. |
| 102 | +
|
| 103 | + Returns |
| 104 | + ------- |
| 105 | + Task |
| 106 | + A Durable Task that completes when the called activity function completes or |
| 107 | + fails completely. |
| 108 | + """ |
| 109 | + task = self._context.call_activity_with_retry(name, retry_options, input_) |
| 110 | + self._task_tracker.record_activity_call() |
| 111 | + return task |
| 112 | + |
| 113 | + def create_activity_tool( |
| 114 | + self, |
| 115 | + activity_func: Callable, |
| 116 | + *, |
| 117 | + description: Optional[str] = None, |
| 118 | + retry_options: Optional[RetryOptions] = RetryOptions( |
| 119 | + first_retry_interval_in_milliseconds=2000, max_number_of_attempts=5 |
| 120 | + ), |
| 121 | + ) -> Tool: |
| 122 | + """Convert an Azure Durable Functions activity to an OpenAI Agents SDK Tool. |
| 123 | +
|
| 124 | + Args |
| 125 | + ---- |
| 126 | + activity_func: The Azure Functions activity function to convert |
| 127 | + description: Optional description override for the tool |
| 128 | + retry_options: The retry options for the activity function |
| 129 | +
|
| 130 | + Returns |
| 131 | + ------- |
| 132 | + Tool: An OpenAI Agents SDK Tool object |
| 133 | +
|
| 134 | + """ |
| 135 | + if activity_func._function is None: |
| 136 | + raise ValueError("The provided function is not a valid Azure Function.") |
| 137 | + |
| 138 | + if (activity_func._function._trigger is not None |
| 139 | + and activity_func._function._trigger.activity is not None): |
| 140 | + activity_name = activity_func._function._trigger.activity |
| 141 | + else: |
| 142 | + activity_name = activity_func._function._name |
| 143 | + |
| 144 | + input_name = None |
| 145 | + if (activity_func._function._trigger is not None |
| 146 | + and hasattr(activity_func._function._trigger, 'name')): |
| 147 | + input_name = activity_func._function._trigger.name |
| 148 | + |
| 149 | + async def run_activity(ctx: RunContextWrapper[Any], input: str) -> Any: |
| 150 | + # Parse JSON input and extract the named value if input_name is specified |
| 151 | + activity_input = input |
| 152 | + if input_name: |
| 153 | + try: |
| 154 | + parsed_input = json.loads(input) |
| 155 | + if isinstance(parsed_input, dict) and input_name in parsed_input: |
| 156 | + activity_input = parsed_input[input_name] |
| 157 | + # If parsing fails or the named parameter is not found, pass the original input |
| 158 | + except (json.JSONDecodeError, TypeError): |
| 159 | + pass |
| 160 | + |
| 161 | + if retry_options: |
| 162 | + result = self._task_tracker.get_activity_call_result_with_retry( |
| 163 | + activity_name, retry_options, activity_input |
| 164 | + ) |
| 165 | + else: |
| 166 | + result = self._task_tracker.get_activity_call_result(activity_name, activity_input) |
| 167 | + return result |
| 168 | + |
| 169 | + schema = function_schema( |
| 170 | + func=activity_func._function._func, |
| 171 | + docstring_style=None, |
| 172 | + description_override=description, |
| 173 | + use_docstring_info=True, |
| 174 | + strict_json_schema=True, |
| 175 | + ) |
| 176 | + |
| 177 | + return FunctionTool( |
| 178 | + name=schema.name, |
| 179 | + description=schema.description or "", |
| 180 | + params_json_schema=schema.params_json_schema, |
| 181 | + on_invoke_tool=run_activity, |
| 182 | + strict_json_schema=True, |
| 183 | + ) |
| 184 | + |
| 185 | + def __getattr__(self, name): |
| 186 | + """Delegate missing attributes to the underlying DurableOrchestrationContext.""" |
| 187 | + try: |
| 188 | + return getattr(self._context, name) |
| 189 | + except AttributeError: |
| 190 | + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") |
| 191 | + |
| 192 | + def __dir__(self): |
| 193 | + """Improve introspection and tab-completion by including delegated attributes.""" |
| 194 | + return sorted(set(dir(type(self)) + list(self.__dict__) + dir(self._context))) |
0 commit comments