-
Notifications
You must be signed in to change notification settings - Fork 77
Enable native Dapr workflows with LLM and Agent decorators #232
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
Merged
Merged
Changes from 6 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
34efd78
Added deprecated warning messages
Cyb3rWard0g eae8886
Enforce JSON-Only Prompt only for dapr llm provider
Cyb3rWard0g e71d917
Added llm_activity and agent_activity workflow decorators
Cyb3rWard0g 1d1013b
Updated LLM-based workflows with latest decorators
Cyb3rWard0g ee63cf6
Added agent-based workflows using new decorator
Cyb3rWard0g 4e0e7dd
make lint happy
Cyb3rWard0g 53b1093
Merge remote-tracking branch 'origin/main' into cyb3rward0g/llm-agent…
Cyb3rWard0g 3a05d2e
Updated agent_activity decorator context on quickstart README
Cyb3rWard0g ebabe3d
Fixed quickstart example to only handle dictionaries
Cyb3rWard0g 262571e
Fixed formatting on quickstart
Cyb3rWard0g a9127e6
Made nltk optional
Cyb3rWard0g 016510f
Added test for decorators
Cyb3rWard0g 75c5fdc
Fix async test markers in test_random.py
Cyb3rWard0g 1a16a63
Remove custom event_loop fixture to fix async test failures
Cyb3rWard0g 2f1ac94
Merge remote-tracking branch 'origin/main' into cyb3rward0g/llm-agent…
Cyb3rWard0g 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
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,5 +1,13 @@ | ||
| from .core import task, workflow | ||
| from .fastapi import route | ||
| from .messaging import message_router | ||
| from .activities import llm_activity, agent_activity | ||
|
|
||
| __all__ = ["workflow", "task", "route", "message_router"] | ||
| __all__ = [ | ||
| "workflow", | ||
| "task", | ||
| "route", | ||
| "message_router", | ||
| "llm_activity", | ||
| "agent_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,193 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| import functools | ||
| import inspect | ||
| import logging | ||
| from typing import Any, Callable, Literal, Optional | ||
|
|
||
| from dapr.ext.workflow import WorkflowActivityContext # type: ignore | ||
|
|
||
| from dapr_agents.agents.base import AgentBase | ||
| from dapr_agents.llm.chat import ChatClientBase | ||
| from dapr_agents.workflow.utils.activities import ( | ||
| build_llm_params, | ||
| convert_result, | ||
| extract_ctx_and_payload, | ||
| format_agent_input, | ||
| format_prompt, | ||
| normalize_input, | ||
| strip_context_parameter, | ||
| validate_result, | ||
| ) | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def llm_activity( | ||
| *, | ||
| prompt: str, | ||
| llm: ChatClientBase, | ||
| structured_mode: Literal["json", "function_call"] = "json", | ||
| **task_kwargs: Any, | ||
| ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: | ||
| """Delegate an activity's implementation to an LLM. | ||
|
|
||
| The decorated function's body is not executed directly. Instead: | ||
| 1) Build a prompt from the activity's signature + `prompt` | ||
| 2) Call the provided LLM client | ||
| 3) Validate the result against the activity's return annotation | ||
|
|
||
| Args: | ||
| prompt: Prompt template (e.g., "Summarize {text} in 3 bullets.") | ||
| llm: Chat client capable of `generate(**params)`. | ||
| structured_mode: Provider structured output mode ("json" or "function_call"). | ||
| **task_kwargs: Reserved for future routing/provider knobs. | ||
|
|
||
| Returns: | ||
| A wrapper suitable to register as a Dapr activity. | ||
|
|
||
| Raises: | ||
| ValueError: If `prompt` is empty or `llm` is missing. | ||
| """ | ||
| if not prompt: | ||
| raise ValueError("@llm_activity requires a prompt template.") | ||
| if llm is None: | ||
| raise ValueError("@llm_activity requires an explicit `llm` client instance.") | ||
|
|
||
| def decorator(func: Callable[..., Any]) -> Callable[..., Any]: | ||
| if not callable(func): | ||
| raise ValueError("@llm_activity must decorate a callable activity.") | ||
|
|
||
| original_sig = inspect.signature(func) | ||
| activity_sig = strip_context_parameter(original_sig) | ||
| effective_structured_mode = task_kwargs.get("structured_mode", structured_mode) | ||
|
|
||
| async def _execute(ctx: WorkflowActivityContext, payload: Any = None) -> Any: | ||
| """Run the LLM pipeline inside the worker.""" | ||
| normalized = ( | ||
| normalize_input(activity_sig, payload) if payload is not None else {} | ||
| ) | ||
|
|
||
| formatted_prompt = format_prompt(activity_sig, prompt, normalized) | ||
| params = build_llm_params( | ||
| activity_sig, formatted_prompt, effective_structured_mode | ||
| ) | ||
|
|
||
| raw = llm.generate(**params) | ||
| if inspect.isawaitable(raw): | ||
| raw = await raw | ||
|
|
||
| converted = convert_result(raw) | ||
| validated = await validate_result(converted, activity_sig) | ||
| return validated | ||
|
|
||
| @functools.wraps(func) | ||
| def wrapper(*args: Any, **kwargs: Any) -> Any: | ||
| """Sync activity wrapper: execute async pipeline to completion.""" | ||
| ctx, payload = extract_ctx_and_payload(args, dict(kwargs)) | ||
| result = _execute(ctx, payload) # coroutine | ||
|
|
||
| # If we're in a thread with an active loop, run thread-safely | ||
| try: | ||
| loop = asyncio.get_running_loop() | ||
| except RuntimeError: | ||
| loop = None | ||
|
|
||
| if loop and loop.is_running(): | ||
| fut = asyncio.run_coroutine_threadsafe(result, loop) | ||
| return fut.result() | ||
|
|
||
| # Otherwise create and run a fresh loop | ||
| return asyncio.run(result) | ||
|
|
||
| # Useful metadata for debugging/inspection | ||
| wrapper._is_llm_activity = True # noqa: SLF001 | ||
| wrapper._llm_activity_config = { # noqa: SLF001 | ||
| "prompt": prompt, | ||
| "structured_mode": effective_structured_mode, | ||
| "task_kwargs": task_kwargs, | ||
| } | ||
| wrapper._original_activity = func # noqa: SLF001 | ||
| return wrapper | ||
|
|
||
| return decorator | ||
|
|
||
|
|
||
| def agent_activity( | ||
| *, | ||
| agent: AgentBase, | ||
| prompt: Optional[str] = None, | ||
| **task_kwargs: Any, | ||
| ) -> Callable[[Callable[..., Any]], Callable[..., Any]]: | ||
| """Route an activity through an `AgentBase`. | ||
|
|
||
| The agent receives either a formatted `prompt` or a natural-language | ||
| rendering of the payload. The result is validated against the activity's return | ||
| annotation. | ||
|
|
||
| Args: | ||
| agent: Agent to run the activity through. | ||
| prompt: Optional prompt template for the agent. | ||
| **task_kwargs: Reserved for future routing/provider knobs. | ||
|
|
||
| Returns: | ||
| A wrapper suitable to register as a Dapr activity. | ||
|
|
||
| Raises: | ||
| ValueError: If `agent` is missing. | ||
| """ | ||
| if agent is None: | ||
| raise ValueError("@agent_activity requires an AgentBase instance.") | ||
|
|
||
| def decorator(func: Callable[..., Any]) -> Callable[..., Any]: | ||
| if not callable(func): | ||
| raise ValueError("@agent_activity must decorate a callable activity.") | ||
|
|
||
| original_sig = inspect.signature(func) | ||
| activity_sig = strip_context_parameter(original_sig) | ||
| prompt_template = prompt or "" | ||
|
|
||
| async def _execute(ctx: WorkflowActivityContext, payload: Any = None) -> Any: | ||
| normalized = ( | ||
| normalize_input(activity_sig, payload) if payload is not None else {} | ||
| ) | ||
|
|
||
| if prompt_template: | ||
| formatted_prompt = format_prompt( | ||
| activity_sig, prompt_template, normalized | ||
| ) | ||
| else: | ||
| formatted_prompt = format_agent_input(payload, normalized) | ||
|
|
||
| raw = await agent.run(formatted_prompt) | ||
| converted = convert_result(raw) | ||
| validated = await validate_result(converted, activity_sig) | ||
| return validated | ||
|
|
||
| @functools.wraps(func) | ||
| def wrapper(*args: Any, **kwargs: Any) -> Any: | ||
| """Sync activity wrapper: execute async pipeline to completion.""" | ||
| ctx, payload = extract_ctx_and_payload(args, dict(kwargs)) | ||
| result = _execute(ctx, payload) # coroutine | ||
|
|
||
| try: | ||
| loop = asyncio.get_running_loop() | ||
| except RuntimeError: | ||
| loop = None | ||
|
|
||
| if loop and loop.is_running(): | ||
| fut = asyncio.run_coroutine_threadsafe(result, loop) | ||
| return fut.result() | ||
|
|
||
| return asyncio.run(result) | ||
|
|
||
| wrapper._is_agent_activity = True # noqa: SLF001 | ||
| wrapper._agent_activity_config = { # noqa: SLF001 | ||
| "prompt": prompt, | ||
| "task_kwargs": task_kwargs, | ||
| } | ||
| wrapper._original_activity = func # noqa: SLF001 | ||
| return wrapper | ||
|
|
||
| return decorator |
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.
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.