Skip to content

Commit dacd290

Browse files
Add a generic stop_when to runtime (#431)
* Add stop_when * Format --------- Co-authored-by: Jack Gerrits <[email protected]>
1 parent 042958e commit dacd290

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

python/packages/autogen-core/src/autogen_core/application/_single_threaded_agent_runtime.py

+22-4
Original file line numberDiff line numberDiff line change
@@ -98,30 +98,41 @@ class RunState(Enum):
9898
def __init__(self, runtime: SingleThreadedAgentRuntime) -> None:
9999
self._runtime = runtime
100100
self._run_state = RunContext.RunState.RUNNING
101+
self._end_condition: Callable[[], bool] = self._stop_when_cancelled
101102
self._run_task = asyncio.create_task(self._run())
102103
self._lock = asyncio.Lock()
103104

104105
async def _run(self) -> None:
105106
while True:
106107
async with self._lock:
107-
if self._run_state == RunContext.RunState.CANCELLED:
108+
if self._end_condition():
108109
return
109-
elif self._run_state == RunContext.RunState.UNTIL_IDLE:
110-
if self._runtime.idle:
111-
return
112110

113111
await self._runtime.process_next()
114112

115113
async def stop(self) -> None:
116114
async with self._lock:
117115
self._run_state = RunContext.RunState.CANCELLED
116+
self._end_condition = self._stop_when_cancelled
118117
await self._run_task
119118

120119
async def stop_when_idle(self) -> None:
121120
async with self._lock:
122121
self._run_state = RunContext.RunState.UNTIL_IDLE
122+
self._end_condition = self._stop_when_idle
123123
await self._run_task
124124

125+
async def stop_when(self, condition: Callable[[], bool]) -> None:
126+
async with self._lock:
127+
self._end_condition = condition
128+
await self._run_task
129+
130+
def _stop_when_cancelled(self) -> bool:
131+
return self._run_state == RunContext.RunState.CANCELLED
132+
133+
def _stop_when_idle(self) -> bool:
134+
return self._run_state == RunContext.RunState.UNTIL_IDLE and self._runtime.idle
135+
125136

126137
class SingleThreadedAgentRuntime(AgentRuntime):
127138
def __init__(self, *, intervention_handlers: List[InterventionHandler] | None = None) -> None:
@@ -449,6 +460,13 @@ async def stop_when_idle(self) -> None:
449460
await self._run_context.stop_when_idle()
450461
self._run_context = None
451462

463+
async def stop_when(self, condition: Callable[[], bool]) -> None:
464+
"""Stop the runtime message processing loop when the condition is met."""
465+
if self._run_context is None:
466+
raise RuntimeError("Runtime is not started")
467+
await self._run_context.stop_when(condition)
468+
self._run_context = None
469+
452470
async def agent_metadata(self, agent: AgentId) -> AgentMetadata:
453471
return (await self._get_agent(agent)).metadata
454472

0 commit comments

Comments
 (0)