-
Notifications
You must be signed in to change notification settings - Fork 352
/
Copy pathexecutor.py
277 lines (237 loc) · 9.14 KB
/
executor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import asyncio
import functools
from abc import ABC, abstractmethod
from contextlib import asynccontextmanager
from datetime import timedelta
from typing import Any, AsyncIterator, Callable, Coroutine, Dict, List, Type, TypeVar
from pydantic import BaseModel, ConfigDict
from mcp_agent.executor.workflow_signal import (
AsyncioSignalHandler,
Signal,
SignalHandler,
SignalValueT,
)
from mcp_agent.context import get_current_context
from mcp_agent.logging.logger import get_logger
logger = get_logger(__name__)
# Type variable for the return type of tasks
R = TypeVar("R")
class ExecutorConfig(BaseModel):
"""Configuration for executors."""
max_concurrent_activities: int | None = None # Unbounded by default
timeout_seconds: timedelta | None = None # No timeout by default
retry_policy: Dict[str, Any] | None = None
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
class Executor(ABC):
"""Abstract base class for different execution backends"""
def __init__(
self,
engine: str,
config: ExecutorConfig | None = None,
signal_bus: SignalHandler = None,
):
self.execution_engine = engine
if config:
self.config = config
else:
# TODO: saqadri - executor config should be loaded from settings
# ctx = get_current_context()
self.config = ExecutorConfig()
self.signal_bus = signal_bus
@asynccontextmanager
async def execution_context(self):
"""Context manager for execution setup/teardown."""
try:
yield
except Exception as e:
# TODO: saqadri - add logging or other error handling here
raise e
@abstractmethod
async def execute(
self,
*tasks: Callable[..., R] | Coroutine[Any, Any, R],
**kwargs: Any,
) -> List[R | BaseException]:
"""Execute a list of tasks and return their results"""
@abstractmethod
async def execute_streaming(
self,
*tasks: List[Callable[..., R] | Coroutine[Any, Any, R]],
**kwargs: Any,
) -> AsyncIterator[R | BaseException]:
"""Execute tasks and yield results as they complete"""
async def map(
self,
func: Callable[..., R],
inputs: List[Any],
**kwargs: Any,
) -> List[R | BaseException]:
"""
Run `func(item)` for each item in `inputs` with concurrency limit.
"""
results: List[R, BaseException] = []
async def run(item):
if self.config.max_concurrent_activities:
semaphore = asyncio.Semaphore(self.config.max_concurrent_activities)
async with semaphore:
return await self.execute(functools.partial(func, item), **kwargs)
else:
return await self.execute(functools.partial(func, item), **kwargs)
coros = [run(x) for x in inputs]
# gather all, each returns a single-element list
list_of_lists = await asyncio.gather(*coros, return_exceptions=True)
# Flatten results
for entry in list_of_lists:
if isinstance(entry, list):
results.extend(entry)
else:
# Means we got an exception at the gather level
results.append(entry)
return results
async def validate_task(
self, task: Callable[..., R] | Coroutine[Any, Any, R]
) -> None:
"""Validate a task before execution."""
if not (asyncio.iscoroutine(task) or asyncio.iscoroutinefunction(task)):
raise TypeError(f"Task must be async: {task}")
async def signal(
self,
signal_name: str,
payload: SignalValueT = None,
signal_description: str | None = None,
) -> None:
"""
Emit a signal.
"""
signal = Signal[SignalValueT](
name=signal_name, payload=payload, description=signal_description
)
await self.signal_bus.signal(signal)
async def wait_for_signal(
self,
signal_name: str,
request_id: str | None = None,
workflow_id: str | None = None,
signal_description: str | None = None,
timeout_seconds: int | None = None,
signal_type: Type[SignalValueT] = str,
) -> SignalValueT:
"""
Wait until a signal with signal_name is emitted (or timeout).
Return the signal's payload when triggered, or raise on timeout.
"""
# Notify any callbacks that the workflow is about to be paused waiting for a signal
ctx = get_current_context()
if ctx.signal_notification:
ctx.signal_notification(
signal_name=signal_name,
request_id=request_id,
workflow_id=workflow_id,
metadata={
"description": signal_description,
"timeout_seconds": timeout_seconds,
"signal_type": signal_type,
},
)
signal = Signal[signal_type](
name=signal_name, description=signal_description, workflow_id=workflow_id
)
return await self.signal_bus.wait_for_signal(signal)
class AsyncioExecutor(Executor):
"""Default executor using asyncio"""
def __init__(
self,
config: ExecutorConfig | None = None,
signal_bus: SignalHandler | None = None,
):
signal_bus = signal_bus or AsyncioSignalHandler()
super().__init__(engine="asyncio", config=config, signal_bus=signal_bus)
self._activity_semaphore: asyncio.Semaphore | None = None
if self.config.max_concurrent_activities is not None:
self._activity_semaphore = asyncio.Semaphore(
self.config.max_concurrent_activities
)
async def _execute_task(
self, task: Callable[..., R] | Coroutine[Any, Any, R], **kwargs: Any
) -> R | BaseException:
async def run_task(task: Callable[..., R] | Coroutine[Any, Any, R]) -> R:
try:
if asyncio.iscoroutine(task):
return await task
elif asyncio.iscoroutinefunction(task):
return await task(**kwargs)
else:
# Execute the callable and await if it returns a coroutine
loop = asyncio.get_running_loop()
# If kwargs are provided, wrap the function with partial
if kwargs:
wrapped_task = functools.partial(task, **kwargs)
result = await loop.run_in_executor(None, wrapped_task)
else:
result = await loop.run_in_executor(None, task)
# Handle case where the sync function returns a coroutine
if asyncio.iscoroutine(result):
return await result
return result
except Exception as e:
# TODO: saqadri - adding logging or other error handling here
return e
if self._activity_semaphore:
async with self._activity_semaphore:
return await run_task(task)
else:
return await run_task(task)
async def execute(
self,
*tasks: Callable[..., R] | Coroutine[Any, Any, R],
**kwargs: Any,
) -> List[R | BaseException]:
# TODO: saqadri - validate if async with self.execution_context() is needed here
async with self.execution_context():
return await asyncio.gather(
*(self._execute_task(task, **kwargs) for task in tasks),
return_exceptions=True,
)
async def execute_streaming(
self,
*tasks: List[Callable[..., R] | Coroutine[Any, Any, R]],
**kwargs: Any,
) -> AsyncIterator[R | BaseException]:
# TODO: saqadri - validate if async with self.execution_context() is needed here
async with self.execution_context():
# Create futures for all tasks
futures = [
asyncio.create_task(self._execute_task(task, **kwargs))
for task in tasks
]
pending = set(futures)
while pending:
done, pending = await asyncio.wait(
pending, return_when=asyncio.FIRST_COMPLETED
)
for future in done:
yield await future
async def signal(
self,
signal_name: str,
payload: SignalValueT = None,
signal_description: str | None = None,
) -> None:
await super().signal(signal_name, payload, signal_description)
async def wait_for_signal(
self,
signal_name: str,
request_id: str | None = None,
workflow_id: str | None = None,
signal_description: str | None = None,
timeout_seconds: int | None = None,
signal_type: Type[SignalValueT] = str,
) -> SignalValueT:
return await super().wait_for_signal(
signal_name,
request_id,
workflow_id,
signal_description,
timeout_seconds,
signal_type,
)