Skip to content

Commit 0cd23f6

Browse files
a7m-1stWendong-Fan
andauthored
feat: add termination parameter to ChatAgent step and astep (#2285)
Co-authored-by: Wendong-Fan <[email protected]>
1 parent efcd5ae commit 0cd23f6

File tree

3 files changed

+33
-4
lines changed

3 files changed

+33
-4
lines changed

camel/agents/chat_agent.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import json
1717
import logging
1818
import textwrap
19+
import threading
1920
import uuid
2021
from collections import defaultdict
2122
from datetime import datetime
@@ -151,6 +152,9 @@ class ChatAgent(BaseAgent):
151152
model calling at each step. (default: :obj:`False`)
152153
agent_id (str, optional): The ID of the agent. If not provided, a
153154
random UUID will be generated. (default: :obj:`None`)
155+
stop_event (Optional[threading.Event], optional): Event to signal
156+
termination of the agent's operation. When set, the agent will
157+
terminate its execution. (default: :obj:`None`)
154158
"""
155159

156160
def __init__(
@@ -182,6 +186,7 @@ def __init__(
182186
scheduling_strategy: str = "round_robin",
183187
single_iteration: bool = False,
184188
agent_id: Optional[str] = None,
189+
stop_event: Optional[threading.Event] = None,
185190
) -> None:
186191
# Resolve model backends and set up model manager
187192
resolved_models = self._resolve_models(model)
@@ -252,6 +257,7 @@ def __init__(
252257
self.terminated = False
253258
self.response_terminators = response_terminators or []
254259
self.single_iteration = single_iteration
260+
self.stop_event = stop_event
255261

256262
def reset(self):
257263
r"""Resets the :obj:`ChatAgent` to its initial state."""
@@ -757,6 +763,13 @@ def step(
757763
self._get_full_tool_schemas(),
758764
)
759765

766+
# Terminate Agent if stop_event is set
767+
if self.stop_event and self.stop_event.is_set():
768+
# Use the _step_token_exceed to terminate the agent with reason
769+
return self._step_token_exceed(
770+
num_tokens, tool_call_records, "termination_triggered"
771+
)
772+
760773
if tool_call_requests := response.tool_call_requests:
761774
# Process all tool calls
762775
for tool_call_request in tool_call_requests:
@@ -849,6 +862,13 @@ async def astep(
849862
self._get_full_tool_schemas(),
850863
)
851864

865+
# Terminate Agent if stop_event is set
866+
if self.stop_event and self.stop_event.is_set():
867+
# Use the _step_token_exceed to terminate the agent with reason
868+
return self._step_token_exceed(
869+
num_tokens, tool_call_records, "termination_triggered"
870+
)
871+
852872
if tool_call_requests := response.tool_call_requests:
853873
# Process all tool calls
854874
for tool_call_request in tool_call_requests:

camel/responses/agent_responses.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,5 @@ class ChatAgentResponse(BaseModel):
3939
@property
4040
def msg(self):
4141
if len(self.msgs) != 1:
42-
raise RuntimeError(
43-
"Property msg is only available "
44-
"for a single message in msgs."
45-
)
42+
return None
4643
return self.msgs[0]

camel/societies/role_playing.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# limitations under the License.
1313
# ========= Copyright 2023-2024 @ CAMEL-AI.org. All Rights Reserved. =========
1414
import logging
15+
import threading
1516
from typing import Dict, List, Optional, Sequence, Tuple, Union
1617

1718
from camel.agents import (
@@ -77,6 +78,9 @@ class RolePlaying:
7778
task specify meta dict with. (default: :obj:`None`)
7879
output_language (str, optional): The language to be output by the
7980
agents. (default: :obj:`None`)
81+
stop_event (Optional[threading.Event], optional): Event to signal
82+
termination of the agent's operation. When set, the agent will
83+
terminate its execution. (default: :obj:`None`)
8084
"""
8185

8286
def __init__(
@@ -101,6 +105,7 @@ def __init__(
101105
extend_sys_msg_meta_dicts: Optional[List[Dict]] = None,
102106
extend_task_specify_meta_dict: Optional[Dict] = None,
103107
output_language: Optional[str] = None,
108+
stop_event: Optional[threading.Event] = None,
104109
) -> None:
105110
if model is not None:
106111
logger.warning(
@@ -156,6 +161,7 @@ def __init__(
156161
assistant_agent_kwargs=assistant_agent_kwargs,
157162
user_agent_kwargs=user_agent_kwargs,
158163
output_language=output_language,
164+
stop_event=stop_event,
159165
)
160166
self.critic: Optional[Union[CriticAgent, Human]] = None
161167
self.critic_sys_msg: Optional[BaseMessage] = None
@@ -316,6 +322,7 @@ def _init_agents(
316322
assistant_agent_kwargs: Optional[Dict] = None,
317323
user_agent_kwargs: Optional[Dict] = None,
318324
output_language: Optional[str] = None,
325+
stop_event: Optional[threading.Event] = None,
319326
) -> None:
320327
r"""Initialize assistant and user agents with their system messages.
321328
@@ -330,6 +337,9 @@ def _init_agents(
330337
pass to the user agent. (default: :obj:`None`)
331338
output_language (str, optional): The language to be output by the
332339
agents. (default: :obj:`None`)
340+
stop_event (Optional[threading.Event], optional): Event to signal
341+
termination of the agent's operation. When set, the agent will
342+
terminate its execution. (default: :obj:`None`)
333343
"""
334344
if self.model is not None:
335345
if assistant_agent_kwargs is None:
@@ -344,13 +354,15 @@ def _init_agents(
344354
self.assistant_agent = ChatAgent(
345355
init_assistant_sys_msg,
346356
output_language=output_language,
357+
stop_event=stop_event,
347358
**(assistant_agent_kwargs or {}),
348359
)
349360
self.assistant_sys_msg = self.assistant_agent.system_message
350361

351362
self.user_agent = ChatAgent(
352363
init_user_sys_msg,
353364
output_language=output_language,
365+
stop_event=stop_event,
354366
**(user_agent_kwargs or {}),
355367
)
356368
self.user_sys_msg = self.user_agent.system_message

0 commit comments

Comments
 (0)