|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import functools |
| 5 | +import inspect |
| 6 | +import logging |
| 7 | +from typing import Any, Callable, Literal, Optional |
| 8 | + |
| 9 | +from dapr.ext.workflow import WorkflowActivityContext # type: ignore |
| 10 | + |
| 11 | +from dapr_agents.agents.base import AgentBase |
| 12 | +from dapr_agents.llm.chat import ChatClientBase |
| 13 | +from dapr_agents.workflow.utils.activities import ( |
| 14 | + build_llm_params, |
| 15 | + convert_result, |
| 16 | + extract_ctx_and_payload, |
| 17 | + format_agent_input, |
| 18 | + format_prompt, |
| 19 | + normalize_input, |
| 20 | + strip_context_parameter, |
| 21 | + validate_result, |
| 22 | +) |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +def llm_activity( |
| 28 | + *, |
| 29 | + prompt: str, |
| 30 | + llm: ChatClientBase, |
| 31 | + structured_mode: Literal["json", "function_call"] = "json", |
| 32 | + **task_kwargs: Any, |
| 33 | +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: |
| 34 | + """Delegate an activity's implementation to an LLM. |
| 35 | +
|
| 36 | + The decorated function's body is not executed directly. Instead: |
| 37 | + 1) Build a prompt from the activity's signature + `prompt` |
| 38 | + 2) Call the provided LLM client |
| 39 | + 3) Validate the result against the activity's return annotation |
| 40 | +
|
| 41 | + Args: |
| 42 | + prompt: Prompt template (e.g., "Summarize {text} in 3 bullets.") |
| 43 | + llm: Chat client capable of `generate(**params)`. |
| 44 | + structured_mode: Provider structured output mode ("json" or "function_call"). |
| 45 | + **task_kwargs: Reserved for future routing/provider knobs. |
| 46 | +
|
| 47 | + Returns: |
| 48 | + A wrapper suitable to register as a Dapr activity. |
| 49 | +
|
| 50 | + Raises: |
| 51 | + ValueError: If `prompt` is empty or `llm` is missing. |
| 52 | + """ |
| 53 | + if not prompt: |
| 54 | + raise ValueError("@llm_activity requires a prompt template.") |
| 55 | + if llm is None: |
| 56 | + raise ValueError("@llm_activity requires an explicit `llm` client instance.") |
| 57 | + |
| 58 | + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: |
| 59 | + if not callable(func): |
| 60 | + raise ValueError("@llm_activity must decorate a callable activity.") |
| 61 | + |
| 62 | + original_sig = inspect.signature(func) |
| 63 | + activity_sig = strip_context_parameter(original_sig) |
| 64 | + effective_structured_mode = task_kwargs.get("structured_mode", structured_mode) |
| 65 | + |
| 66 | + async def _execute(ctx: WorkflowActivityContext, payload: Any = None) -> Any: |
| 67 | + """Run the LLM pipeline inside the worker.""" |
| 68 | + normalized = ( |
| 69 | + normalize_input(activity_sig, payload) if payload is not None else {} |
| 70 | + ) |
| 71 | + |
| 72 | + formatted_prompt = format_prompt(activity_sig, prompt, normalized) |
| 73 | + params = build_llm_params( |
| 74 | + activity_sig, formatted_prompt, effective_structured_mode |
| 75 | + ) |
| 76 | + |
| 77 | + raw = llm.generate(**params) |
| 78 | + if inspect.isawaitable(raw): |
| 79 | + raw = await raw |
| 80 | + |
| 81 | + converted = convert_result(raw) |
| 82 | + validated = await validate_result(converted, activity_sig) |
| 83 | + return validated |
| 84 | + |
| 85 | + @functools.wraps(func) |
| 86 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 87 | + """Sync activity wrapper: execute async pipeline to completion.""" |
| 88 | + ctx, payload = extract_ctx_and_payload(args, dict(kwargs)) |
| 89 | + result = _execute(ctx, payload) # coroutine |
| 90 | + |
| 91 | + # If we're in a thread with an active loop, run thread-safely |
| 92 | + try: |
| 93 | + loop = asyncio.get_running_loop() |
| 94 | + except RuntimeError: |
| 95 | + loop = None |
| 96 | + |
| 97 | + if loop and loop.is_running(): |
| 98 | + fut = asyncio.run_coroutine_threadsafe(result, loop) |
| 99 | + return fut.result() |
| 100 | + |
| 101 | + # Otherwise create and run a fresh loop |
| 102 | + return asyncio.run(result) |
| 103 | + |
| 104 | + # Useful metadata for debugging/inspection |
| 105 | + wrapper._is_llm_activity = True # noqa: SLF001 |
| 106 | + wrapper._llm_activity_config = { # noqa: SLF001 |
| 107 | + "prompt": prompt, |
| 108 | + "structured_mode": effective_structured_mode, |
| 109 | + "task_kwargs": task_kwargs, |
| 110 | + } |
| 111 | + wrapper._original_activity = func # noqa: SLF001 |
| 112 | + return wrapper |
| 113 | + |
| 114 | + return decorator |
| 115 | + |
| 116 | + |
| 117 | +def agent_activity( |
| 118 | + *, |
| 119 | + agent: AgentBase, |
| 120 | + prompt: Optional[str] = None, |
| 121 | + **task_kwargs: Any, |
| 122 | +) -> Callable[[Callable[..., Any]], Callable[..., Any]]: |
| 123 | + """Route an activity through an `AgentBase`. |
| 124 | +
|
| 125 | + The agent receives either a formatted `prompt` or a natural-language |
| 126 | + rendering of the payload. The result is validated against the activity's return |
| 127 | + annotation. |
| 128 | +
|
| 129 | + Args: |
| 130 | + agent: Agent to run the activity through. |
| 131 | + prompt: Optional prompt template for the agent. |
| 132 | + **task_kwargs: Reserved for future routing/provider knobs. |
| 133 | +
|
| 134 | + Returns: |
| 135 | + A wrapper suitable to register as a Dapr activity. |
| 136 | +
|
| 137 | + Raises: |
| 138 | + ValueError: If `agent` is missing. |
| 139 | + """ |
| 140 | + if agent is None: |
| 141 | + raise ValueError("@agent_activity requires an AgentBase instance.") |
| 142 | + |
| 143 | + def decorator(func: Callable[..., Any]) -> Callable[..., Any]: |
| 144 | + if not callable(func): |
| 145 | + raise ValueError("@agent_activity must decorate a callable activity.") |
| 146 | + |
| 147 | + original_sig = inspect.signature(func) |
| 148 | + activity_sig = strip_context_parameter(original_sig) |
| 149 | + prompt_template = prompt or "" |
| 150 | + |
| 151 | + async def _execute(ctx: WorkflowActivityContext, payload: Any = None) -> Any: |
| 152 | + normalized = ( |
| 153 | + normalize_input(activity_sig, payload) if payload is not None else {} |
| 154 | + ) |
| 155 | + |
| 156 | + if prompt_template: |
| 157 | + formatted_prompt = format_prompt( |
| 158 | + activity_sig, prompt_template, normalized |
| 159 | + ) |
| 160 | + else: |
| 161 | + formatted_prompt = format_agent_input(payload, normalized) |
| 162 | + |
| 163 | + raw = await agent.run(formatted_prompt) |
| 164 | + converted = convert_result(raw) |
| 165 | + validated = await validate_result(converted, activity_sig) |
| 166 | + return validated |
| 167 | + |
| 168 | + @functools.wraps(func) |
| 169 | + def wrapper(*args: Any, **kwargs: Any) -> Any: |
| 170 | + """Sync activity wrapper: execute async pipeline to completion.""" |
| 171 | + ctx, payload = extract_ctx_and_payload(args, dict(kwargs)) |
| 172 | + result = _execute(ctx, payload) # coroutine |
| 173 | + |
| 174 | + try: |
| 175 | + loop = asyncio.get_running_loop() |
| 176 | + except RuntimeError: |
| 177 | + loop = None |
| 178 | + |
| 179 | + if loop and loop.is_running(): |
| 180 | + fut = asyncio.run_coroutine_threadsafe(result, loop) |
| 181 | + return fut.result() |
| 182 | + |
| 183 | + return asyncio.run(result) |
| 184 | + |
| 185 | + wrapper._is_agent_activity = True # noqa: SLF001 |
| 186 | + wrapper._agent_activity_config = { # noqa: SLF001 |
| 187 | + "prompt": prompt, |
| 188 | + "task_kwargs": task_kwargs, |
| 189 | + } |
| 190 | + wrapper._original_activity = func # noqa: SLF001 |
| 191 | + return wrapper |
| 192 | + |
| 193 | + return decorator |
0 commit comments