|
1 | 1 | import json |
2 | 2 | from concurrent.futures import ThreadPoolExecutor |
3 | 3 | from typing import Any, Callable, Dict, List, Optional, Union |
4 | | - |
| 4 | +import asyncio |
5 | 5 | from swarms.structs.agent import Agent |
6 | 6 | from swarms.structs.conversation import Conversation |
7 | 7 | from swarms.structs.multi_agent_exec import run_agents_concurrently |
@@ -908,6 +908,45 @@ def concurrent_run( |
908 | 908 | except Exception as e: |
909 | 909 | self._catch_error(e) |
910 | 910 |
|
| 911 | + async def run_async( |
| 912 | + self, |
| 913 | + task: str, |
| 914 | + img: Optional[str] = None, |
| 915 | + *args, |
| 916 | + **kwargs, |
| 917 | + ) -> Any: |
| 918 | + """ |
| 919 | + Asynchronously executes a task through the agent workflow. |
| 920 | +
|
| 921 | + This method enables asynchronous execution of tasks by running the |
| 922 | + synchronous run method in a separate thread using asyncio.to_thread. |
| 923 | + This is ideal for integrating the agent workflow into async applications |
| 924 | + or when you want non-blocking execution. |
| 925 | +
|
| 926 | + Args: |
| 927 | + task (str): The task to be executed through the agent workflow. |
| 928 | + img (Optional[str]): Optional image input for the task. Defaults to None. |
| 929 | + *args: Additional positional arguments passed to the run method. |
| 930 | + **kwargs: Additional keyword arguments passed to the run method. |
| 931 | +
|
| 932 | + Returns: |
| 933 | + Any: The result of the task execution, format depends on output_type setting. |
| 934 | +
|
| 935 | + Raises: |
| 936 | + Exception: If an error occurs during task execution. |
| 937 | +
|
| 938 | + Note: |
| 939 | + This method uses asyncio.to_thread to run the synchronous run method |
| 940 | + asynchronously, allowing integration with async/await patterns. |
| 941 | + """ |
| 942 | + |
| 943 | + try: |
| 944 | + return await asyncio.to_thread( |
| 945 | + self.run, task=task, img=img, *args, **kwargs |
| 946 | + ) |
| 947 | + except Exception as e: |
| 948 | + self._catch_error(e) |
| 949 | + |
911 | 950 | def _serialize_callable( |
912 | 951 | self, attr_value: Callable |
913 | 952 | ) -> Dict[str, Any]: |
|
0 commit comments