ag2 0.3.2b2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of ag2 might be problematic. Click here for more details.

Files changed (112) hide show
  1. ag2-0.3.2b2.dist-info/LICENSE +201 -0
  2. ag2-0.3.2b2.dist-info/METADATA +490 -0
  3. ag2-0.3.2b2.dist-info/NOTICE.md +19 -0
  4. ag2-0.3.2b2.dist-info/RECORD +112 -0
  5. ag2-0.3.2b2.dist-info/WHEEL +5 -0
  6. ag2-0.3.2b2.dist-info/top_level.txt +1 -0
  7. autogen/__init__.py +17 -0
  8. autogen/_pydantic.py +116 -0
  9. autogen/agentchat/__init__.py +26 -0
  10. autogen/agentchat/agent.py +142 -0
  11. autogen/agentchat/assistant_agent.py +85 -0
  12. autogen/agentchat/chat.py +306 -0
  13. autogen/agentchat/contrib/__init__.py +0 -0
  14. autogen/agentchat/contrib/agent_builder.py +785 -0
  15. autogen/agentchat/contrib/agent_optimizer.py +450 -0
  16. autogen/agentchat/contrib/capabilities/__init__.py +0 -0
  17. autogen/agentchat/contrib/capabilities/agent_capability.py +21 -0
  18. autogen/agentchat/contrib/capabilities/generate_images.py +297 -0
  19. autogen/agentchat/contrib/capabilities/teachability.py +406 -0
  20. autogen/agentchat/contrib/capabilities/text_compressors.py +72 -0
  21. autogen/agentchat/contrib/capabilities/transform_messages.py +92 -0
  22. autogen/agentchat/contrib/capabilities/transforms.py +565 -0
  23. autogen/agentchat/contrib/capabilities/transforms_util.py +120 -0
  24. autogen/agentchat/contrib/capabilities/vision_capability.py +217 -0
  25. autogen/agentchat/contrib/gpt_assistant_agent.py +545 -0
  26. autogen/agentchat/contrib/graph_rag/__init__.py +0 -0
  27. autogen/agentchat/contrib/graph_rag/document.py +24 -0
  28. autogen/agentchat/contrib/graph_rag/falkor_graph_query_engine.py +76 -0
  29. autogen/agentchat/contrib/graph_rag/graph_query_engine.py +50 -0
  30. autogen/agentchat/contrib/graph_rag/graph_rag_capability.py +56 -0
  31. autogen/agentchat/contrib/img_utils.py +390 -0
  32. autogen/agentchat/contrib/llamaindex_conversable_agent.py +114 -0
  33. autogen/agentchat/contrib/llava_agent.py +176 -0
  34. autogen/agentchat/contrib/math_user_proxy_agent.py +471 -0
  35. autogen/agentchat/contrib/multimodal_conversable_agent.py +128 -0
  36. autogen/agentchat/contrib/qdrant_retrieve_user_proxy_agent.py +325 -0
  37. autogen/agentchat/contrib/retrieve_assistant_agent.py +56 -0
  38. autogen/agentchat/contrib/retrieve_user_proxy_agent.py +701 -0
  39. autogen/agentchat/contrib/society_of_mind_agent.py +203 -0
  40. autogen/agentchat/contrib/text_analyzer_agent.py +76 -0
  41. autogen/agentchat/contrib/vectordb/__init__.py +0 -0
  42. autogen/agentchat/contrib/vectordb/base.py +243 -0
  43. autogen/agentchat/contrib/vectordb/chromadb.py +326 -0
  44. autogen/agentchat/contrib/vectordb/mongodb.py +559 -0
  45. autogen/agentchat/contrib/vectordb/pgvectordb.py +958 -0
  46. autogen/agentchat/contrib/vectordb/qdrant.py +334 -0
  47. autogen/agentchat/contrib/vectordb/utils.py +126 -0
  48. autogen/agentchat/contrib/web_surfer.py +305 -0
  49. autogen/agentchat/conversable_agent.py +2904 -0
  50. autogen/agentchat/groupchat.py +1666 -0
  51. autogen/agentchat/user_proxy_agent.py +109 -0
  52. autogen/agentchat/utils.py +207 -0
  53. autogen/browser_utils.py +291 -0
  54. autogen/cache/__init__.py +10 -0
  55. autogen/cache/abstract_cache_base.py +78 -0
  56. autogen/cache/cache.py +182 -0
  57. autogen/cache/cache_factory.py +85 -0
  58. autogen/cache/cosmos_db_cache.py +150 -0
  59. autogen/cache/disk_cache.py +109 -0
  60. autogen/cache/in_memory_cache.py +61 -0
  61. autogen/cache/redis_cache.py +128 -0
  62. autogen/code_utils.py +745 -0
  63. autogen/coding/__init__.py +22 -0
  64. autogen/coding/base.py +113 -0
  65. autogen/coding/docker_commandline_code_executor.py +262 -0
  66. autogen/coding/factory.py +45 -0
  67. autogen/coding/func_with_reqs.py +203 -0
  68. autogen/coding/jupyter/__init__.py +22 -0
  69. autogen/coding/jupyter/base.py +32 -0
  70. autogen/coding/jupyter/docker_jupyter_server.py +164 -0
  71. autogen/coding/jupyter/embedded_ipython_code_executor.py +182 -0
  72. autogen/coding/jupyter/jupyter_client.py +224 -0
  73. autogen/coding/jupyter/jupyter_code_executor.py +161 -0
  74. autogen/coding/jupyter/local_jupyter_server.py +168 -0
  75. autogen/coding/local_commandline_code_executor.py +410 -0
  76. autogen/coding/markdown_code_extractor.py +44 -0
  77. autogen/coding/utils.py +57 -0
  78. autogen/exception_utils.py +46 -0
  79. autogen/extensions/__init__.py +0 -0
  80. autogen/formatting_utils.py +76 -0
  81. autogen/function_utils.py +362 -0
  82. autogen/graph_utils.py +148 -0
  83. autogen/io/__init__.py +15 -0
  84. autogen/io/base.py +105 -0
  85. autogen/io/console.py +43 -0
  86. autogen/io/websockets.py +213 -0
  87. autogen/logger/__init__.py +11 -0
  88. autogen/logger/base_logger.py +140 -0
  89. autogen/logger/file_logger.py +287 -0
  90. autogen/logger/logger_factory.py +29 -0
  91. autogen/logger/logger_utils.py +42 -0
  92. autogen/logger/sqlite_logger.py +459 -0
  93. autogen/math_utils.py +356 -0
  94. autogen/oai/__init__.py +33 -0
  95. autogen/oai/anthropic.py +428 -0
  96. autogen/oai/bedrock.py +600 -0
  97. autogen/oai/cerebras.py +264 -0
  98. autogen/oai/client.py +1148 -0
  99. autogen/oai/client_utils.py +167 -0
  100. autogen/oai/cohere.py +453 -0
  101. autogen/oai/completion.py +1216 -0
  102. autogen/oai/gemini.py +469 -0
  103. autogen/oai/groq.py +281 -0
  104. autogen/oai/mistral.py +279 -0
  105. autogen/oai/ollama.py +576 -0
  106. autogen/oai/openai_utils.py +810 -0
  107. autogen/oai/together.py +343 -0
  108. autogen/retrieve_utils.py +487 -0
  109. autogen/runtime_logging.py +163 -0
  110. autogen/token_count_utils.py +257 -0
  111. autogen/types.py +20 -0
  112. autogen/version.py +7 -0
@@ -0,0 +1,2904 @@
1
+ # Copyright (c) 2023 - 2024, Owners of https://github.com/ag2ai
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ #
5
+ # Portions derived from https://github.com/microsoft/autogen are under the MIT License.
6
+ # SPDX-License-Identifier: MIT
7
+ import asyncio
8
+ import copy
9
+ import functools
10
+ import inspect
11
+ import json
12
+ import logging
13
+ import re
14
+ import warnings
15
+ from collections import defaultdict
16
+ from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Type, TypeVar, Union
17
+
18
+ from openai import BadRequestError
19
+
20
+ from autogen.agentchat.chat import _post_process_carryover_item
21
+ from autogen.exception_utils import InvalidCarryOverType, SenderRequired
22
+
23
+ from .._pydantic import model_dump
24
+ from ..cache.cache import AbstractCache
25
+ from ..code_utils import (
26
+ PYTHON_VARIANTS,
27
+ UNKNOWN,
28
+ check_can_use_docker_or_throw,
29
+ content_str,
30
+ decide_use_docker,
31
+ execute_code,
32
+ extract_code,
33
+ infer_lang,
34
+ )
35
+ from ..coding.base import CodeExecutor
36
+ from ..coding.factory import CodeExecutorFactory
37
+ from ..formatting_utils import colored
38
+ from ..function_utils import get_function_schema, load_basemodels_if_needed, serialize_to_str
39
+ from ..io.base import IOStream
40
+ from ..oai.client import ModelClient, OpenAIWrapper
41
+ from ..runtime_logging import log_event, log_function_use, log_new_agent, logging_enabled
42
+ from .agent import Agent, LLMAgent
43
+ from .chat import ChatResult, a_initiate_chats, initiate_chats
44
+ from .utils import consolidate_chat_info, gather_usage_summary
45
+
46
+ __all__ = ("ConversableAgent",)
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ F = TypeVar("F", bound=Callable[..., Any])
51
+
52
+
53
+ class ConversableAgent(LLMAgent):
54
+ """(In preview) A class for generic conversable agents which can be configured as assistant or user proxy.
55
+
56
+ After receiving each message, the agent will send a reply to the sender unless the msg is a termination msg.
57
+ For example, AssistantAgent and UserProxyAgent are subclasses of this class,
58
+ configured with different default settings.
59
+
60
+ To modify auto reply, override `generate_reply` method.
61
+ To disable/enable human response in every turn, set `human_input_mode` to "NEVER" or "ALWAYS".
62
+ To modify the way to get human input, override `get_human_input` method.
63
+ To modify the way to execute code blocks, single code block, or function call, override `execute_code_blocks`,
64
+ `run_code`, and `execute_function` methods respectively.
65
+ """
66
+
67
+ DEFAULT_CONFIG = False # False or dict, the default config for llm inference
68
+ MAX_CONSECUTIVE_AUTO_REPLY = 100 # maximum number of consecutive auto replies (subject to future change)
69
+
70
+ DEFAULT_SUMMARY_PROMPT = "Summarize the takeaway from the conversation. Do not add any introductory phrases."
71
+ DEFAULT_SUMMARY_METHOD = "last_msg"
72
+ llm_config: Union[Dict, Literal[False]]
73
+
74
+ def __init__(
75
+ self,
76
+ name: str,
77
+ system_message: Optional[Union[str, List]] = "You are a helpful AI Assistant.",
78
+ is_termination_msg: Optional[Callable[[Dict], bool]] = None,
79
+ max_consecutive_auto_reply: Optional[int] = None,
80
+ human_input_mode: Literal["ALWAYS", "NEVER", "TERMINATE"] = "TERMINATE",
81
+ function_map: Optional[Dict[str, Callable]] = None,
82
+ code_execution_config: Union[Dict, Literal[False]] = False,
83
+ llm_config: Optional[Union[Dict, Literal[False]]] = None,
84
+ default_auto_reply: Union[str, Dict] = "",
85
+ description: Optional[str] = None,
86
+ chat_messages: Optional[Dict[Agent, List[Dict]]] = None,
87
+ silent: Optional[bool] = None,
88
+ ):
89
+ """
90
+ Args:
91
+ name (str): name of the agent.
92
+ system_message (str or list): system message for the ChatCompletion inference.
93
+ is_termination_msg (function): a function that takes a message in the form of a dictionary
94
+ and returns a boolean value indicating if this received message is a termination message.
95
+ The dict can contain the following keys: "content", "role", "name", "function_call".
96
+ max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.
97
+ default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).
98
+ When set to 0, no auto reply will be generated.
99
+ human_input_mode (str): whether to ask for human inputs every time a message is received.
100
+ Possible values are "ALWAYS", "TERMINATE", "NEVER".
101
+ (1) When "ALWAYS", the agent prompts for human input every time a message is received.
102
+ Under this mode, the conversation stops when the human input is "exit",
103
+ or when is_termination_msg is True and there is no human input.
104
+ (2) When "TERMINATE", the agent only prompts for human input only when a termination message is received or
105
+ the number of auto reply reaches the max_consecutive_auto_reply.
106
+ (3) When "NEVER", the agent will never prompt for human input. Under this mode, the conversation stops
107
+ when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.
108
+ function_map (dict[str, callable]): Mapping function names (passed to openai) to callable functions, also used for tool calls.
109
+ code_execution_config (dict or False): config for the code execution.
110
+ To disable code execution, set to False. Otherwise, set to a dictionary with the following keys:
111
+ - work_dir (Optional, str): The working directory for the code execution.
112
+ If None, a default working directory will be used.
113
+ The default working directory is the "extensions" directory under
114
+ "path_to_autogen".
115
+ - use_docker (Optional, list, str or bool): The docker image to use for code execution.
116
+ Default is True, which means the code will be executed in a docker container. A default list of images will be used.
117
+ If a list or a str of image name(s) is provided, the code will be executed in a docker container
118
+ with the first image successfully pulled.
119
+ If False, the code will be executed in the current environment.
120
+ We strongly recommend using docker for code execution.
121
+ - timeout (Optional, int): The maximum execution time in seconds.
122
+ - last_n_messages (Experimental, int or str): The number of messages to look back for code execution.
123
+ If set to 'auto', it will scan backwards through all messages arriving since the agent last spoke, which is typically the last time execution was attempted. (Default: auto)
124
+ llm_config (dict or False or None): llm inference configuration.
125
+ Please refer to [OpenAIWrapper.create](/docs/reference/oai/client#create)
126
+ for available options.
127
+ When using OpenAI or Azure OpenAI endpoints, please specify a non-empty 'model' either in `llm_config` or in each config of 'config_list' in `llm_config`.
128
+ To disable llm-based auto reply, set to False.
129
+ When set to None, will use self.DEFAULT_CONFIG, which defaults to False.
130
+ default_auto_reply (str or dict): default auto reply when no code execution or llm-based reply is generated.
131
+ description (str): a short description of the agent. This description is used by other agents
132
+ (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message)
133
+ chat_messages (dict or None): the previous chat messages that this agent had in the past with other agents.
134
+ Can be used to give the agent a memory by providing the chat history. This will allow the agent to
135
+ resume previous had conversations. Defaults to an empty chat history.
136
+ silent (bool or None): (Experimental) whether to print the message sent. If None, will use the value of
137
+ silent in each function.
138
+ """
139
+ # we change code_execution_config below and we have to make sure we don't change the input
140
+ # in case of UserProxyAgent, without this we could even change the default value {}
141
+ code_execution_config = (
142
+ code_execution_config.copy() if hasattr(code_execution_config, "copy") else code_execution_config
143
+ )
144
+
145
+ self._name = name
146
+ # a dictionary of conversations, default value is list
147
+ if chat_messages is None:
148
+ self._oai_messages = defaultdict(list)
149
+ else:
150
+ self._oai_messages = chat_messages
151
+
152
+ self._oai_system_message = [{"content": system_message, "role": "system"}]
153
+ self._description = description if description is not None else system_message
154
+ self._is_termination_msg = (
155
+ is_termination_msg
156
+ if is_termination_msg is not None
157
+ else (lambda x: content_str(x.get("content")) == "TERMINATE")
158
+ )
159
+ self.silent = silent
160
+ # Take a copy to avoid modifying the given dict
161
+ if isinstance(llm_config, dict):
162
+ try:
163
+ llm_config = copy.deepcopy(llm_config)
164
+ except TypeError as e:
165
+ raise TypeError(
166
+ "Please implement __deepcopy__ method for each value class in llm_config to support deepcopy."
167
+ " Refer to the docs for more details: https://ag2ai.github.io/autogen/docs/topics/llm_configuration#adding-http-client-in-llm_config-for-proxy"
168
+ ) from e
169
+
170
+ self._validate_llm_config(llm_config)
171
+
172
+ if logging_enabled():
173
+ log_new_agent(self, locals())
174
+
175
+ # Initialize standalone client cache object.
176
+ self.client_cache = None
177
+
178
+ self.human_input_mode = human_input_mode
179
+ self._max_consecutive_auto_reply = (
180
+ max_consecutive_auto_reply if max_consecutive_auto_reply is not None else self.MAX_CONSECUTIVE_AUTO_REPLY
181
+ )
182
+ self._consecutive_auto_reply_counter = defaultdict(int)
183
+ self._max_consecutive_auto_reply_dict = defaultdict(self.max_consecutive_auto_reply)
184
+ self._function_map = (
185
+ {}
186
+ if function_map is None
187
+ else {name: callable for name, callable in function_map.items() if self._assert_valid_name(name)}
188
+ )
189
+ self._default_auto_reply = default_auto_reply
190
+ self._reply_func_list = []
191
+ self._human_input = []
192
+ self.reply_at_receive = defaultdict(bool)
193
+ self.register_reply([Agent, None], ConversableAgent.generate_oai_reply)
194
+ self.register_reply([Agent, None], ConversableAgent.a_generate_oai_reply, ignore_async_in_sync_chat=True)
195
+
196
+ # Setting up code execution.
197
+ # Do not register code execution reply if code execution is disabled.
198
+ if code_execution_config is not False:
199
+ # If code_execution_config is None, set it to an empty dict.
200
+ if code_execution_config is None:
201
+ warnings.warn(
202
+ "Using None to signal a default code_execution_config is deprecated. "
203
+ "Use {} to use default or False to disable code execution.",
204
+ stacklevel=2,
205
+ )
206
+ code_execution_config = {}
207
+ if not isinstance(code_execution_config, dict):
208
+ raise ValueError("code_execution_config must be a dict or False.")
209
+
210
+ # We have got a valid code_execution_config.
211
+ self._code_execution_config = code_execution_config
212
+
213
+ if self._code_execution_config.get("executor") is not None:
214
+ if "use_docker" in self._code_execution_config:
215
+ raise ValueError(
216
+ "'use_docker' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
217
+ )
218
+
219
+ if "work_dir" in self._code_execution_config:
220
+ raise ValueError(
221
+ "'work_dir' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
222
+ )
223
+
224
+ if "timeout" in self._code_execution_config:
225
+ raise ValueError(
226
+ "'timeout' in code_execution_config is not valid when 'executor' is set. Use the appropriate arg in the chosen executor instead."
227
+ )
228
+
229
+ # Use the new code executor.
230
+ self._code_executor = CodeExecutorFactory.create(self._code_execution_config)
231
+ self.register_reply([Agent, None], ConversableAgent._generate_code_execution_reply_using_executor)
232
+ else:
233
+ # Legacy code execution using code_utils.
234
+ use_docker = self._code_execution_config.get("use_docker", None)
235
+ use_docker = decide_use_docker(use_docker)
236
+ check_can_use_docker_or_throw(use_docker)
237
+ self._code_execution_config["use_docker"] = use_docker
238
+ self.register_reply([Agent, None], ConversableAgent.generate_code_execution_reply)
239
+ else:
240
+ # Code execution is disabled.
241
+ self._code_execution_config = False
242
+
243
+ self.register_reply([Agent, None], ConversableAgent.generate_tool_calls_reply)
244
+ self.register_reply([Agent, None], ConversableAgent.a_generate_tool_calls_reply, ignore_async_in_sync_chat=True)
245
+ self.register_reply([Agent, None], ConversableAgent.generate_function_call_reply)
246
+ self.register_reply(
247
+ [Agent, None], ConversableAgent.a_generate_function_call_reply, ignore_async_in_sync_chat=True
248
+ )
249
+ self.register_reply([Agent, None], ConversableAgent.check_termination_and_human_reply)
250
+ self.register_reply(
251
+ [Agent, None], ConversableAgent.a_check_termination_and_human_reply, ignore_async_in_sync_chat=True
252
+ )
253
+
254
+ # Registered hooks are kept in lists, indexed by hookable method, to be called in their order of registration.
255
+ # New hookable methods should be added to this list as required to support new agent capabilities.
256
+ self.hook_lists: Dict[str, List[Callable]] = {
257
+ "process_last_received_message": [],
258
+ "process_all_messages_before_reply": [],
259
+ "process_message_before_send": [],
260
+ }
261
+
262
+ def _validate_llm_config(self, llm_config):
263
+ assert llm_config in (None, False) or isinstance(
264
+ llm_config, dict
265
+ ), "llm_config must be a dict or False or None."
266
+ if llm_config is None:
267
+ llm_config = self.DEFAULT_CONFIG
268
+ self.llm_config = self.DEFAULT_CONFIG if llm_config is None else llm_config
269
+ # TODO: more complete validity check
270
+ if self.llm_config in [{}, {"config_list": []}, {"config_list": [{"model": ""}]}]:
271
+ raise ValueError(
272
+ "When using OpenAI or Azure OpenAI endpoints, specify a non-empty 'model' either in 'llm_config' or in each config of 'config_list'."
273
+ )
274
+ self.client = None if self.llm_config is False else OpenAIWrapper(**self.llm_config)
275
+
276
+ @staticmethod
277
+ def _is_silent(agent: Agent, silent: Optional[bool] = False) -> bool:
278
+ return agent.silent if agent.silent is not None else silent
279
+
280
+ @property
281
+ def name(self) -> str:
282
+ """Get the name of the agent."""
283
+ return self._name
284
+
285
+ @property
286
+ def description(self) -> str:
287
+ """Get the description of the agent."""
288
+ return self._description
289
+
290
+ @description.setter
291
+ def description(self, description: str):
292
+ """Set the description of the agent."""
293
+ self._description = description
294
+
295
+ @property
296
+ def code_executor(self) -> Optional[CodeExecutor]:
297
+ """The code executor used by this agent. Returns None if code execution is disabled."""
298
+ if not hasattr(self, "_code_executor"):
299
+ return None
300
+ return self._code_executor
301
+
302
+ def register_reply(
303
+ self,
304
+ trigger: Union[Type[Agent], str, Agent, Callable[[Agent], bool], List],
305
+ reply_func: Callable,
306
+ position: int = 0,
307
+ config: Optional[Any] = None,
308
+ reset_config: Optional[Callable] = None,
309
+ *,
310
+ ignore_async_in_sync_chat: bool = False,
311
+ remove_other_reply_funcs: bool = False,
312
+ ):
313
+ """Register a reply function.
314
+
315
+ The reply function will be called when the trigger matches the sender.
316
+ The function registered later will be checked earlier by default.
317
+ To change the order, set the position to a positive integer.
318
+
319
+ Both sync and async reply functions can be registered. The sync reply function will be triggered
320
+ from both sync and async chats. However, an async reply function will only be triggered from async
321
+ chats (initiated with `ConversableAgent.a_initiate_chat`). If an `async` reply function is registered
322
+ and a chat is initialized with a sync function, `ignore_async_in_sync_chat` determines the behaviour as follows:
323
+ if `ignore_async_in_sync_chat` is set to `False` (default value), an exception will be raised, and
324
+ if `ignore_async_in_sync_chat` is set to `True`, the reply function will be ignored.
325
+
326
+ Args:
327
+ trigger (Agent class, str, Agent instance, callable, or list): the trigger.
328
+ If a class is provided, the reply function will be called when the sender is an instance of the class.
329
+ If a string is provided, the reply function will be called when the sender's name matches the string.
330
+ If an agent instance is provided, the reply function will be called when the sender is the agent instance.
331
+ If a callable is provided, the reply function will be called when the callable returns True.
332
+ If a list is provided, the reply function will be called when any of the triggers in the list is activated.
333
+ If None is provided, the reply function will be called only when the sender is None.
334
+ Note: Be sure to register `None` as a trigger if you would like to trigger an auto-reply function with non-empty messages and `sender=None`.
335
+ reply_func (Callable): the reply function.
336
+ The function takes a recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.
337
+
338
+ ```python
339
+ def reply_func(
340
+ recipient: ConversableAgent,
341
+ messages: Optional[List[Dict]] = None,
342
+ sender: Optional[Agent] = None,
343
+ config: Optional[Any] = None,
344
+ ) -> Tuple[bool, Union[str, Dict, None]]:
345
+ ```
346
+ position (int): the position of the reply function in the reply function list.
347
+ The function registered later will be checked earlier by default.
348
+ To change the order, set the position to a positive integer.
349
+ config (Any): the config to be passed to the reply function.
350
+ When an agent is reset, the config will be reset to the original value.
351
+ reset_config (Callable): the function to reset the config.
352
+ The function returns None. Signature: ```def reset_config(config: Any)```
353
+ ignore_async_in_sync_chat (bool): whether to ignore the async reply function in sync chats. If `False`, an exception
354
+ will be raised if an async reply function is registered and a chat is initialized with a sync
355
+ function.
356
+ remove_other_reply_funcs (bool): whether to remove other reply functions when registering this reply function.
357
+ """
358
+ if not isinstance(trigger, (type, str, Agent, Callable, list)):
359
+ raise ValueError("trigger must be a class, a string, an agent, a callable or a list.")
360
+ if remove_other_reply_funcs:
361
+ self._reply_func_list.clear()
362
+ self._reply_func_list.insert(
363
+ position,
364
+ {
365
+ "trigger": trigger,
366
+ "reply_func": reply_func,
367
+ "config": copy.copy(config),
368
+ "init_config": config,
369
+ "reset_config": reset_config,
370
+ "ignore_async_in_sync_chat": ignore_async_in_sync_chat and inspect.iscoroutinefunction(reply_func),
371
+ },
372
+ )
373
+
374
+ def replace_reply_func(self, old_reply_func: Callable, new_reply_func: Callable):
375
+ """Replace a registered reply function with a new one.
376
+
377
+ Args:
378
+ old_reply_func (Callable): the old reply function to be replaced.
379
+ new_reply_func (Callable): the new reply function to replace the old one.
380
+ """
381
+ for f in self._reply_func_list:
382
+ if f["reply_func"] == old_reply_func:
383
+ f["reply_func"] = new_reply_func
384
+
385
+ @staticmethod
386
+ def _get_chats_to_run(
387
+ chat_queue: List[Dict[str, Any]], recipient: Agent, messages: Union[str, Callable], sender: Agent, config: Any
388
+ ) -> List[Dict[str, Any]]:
389
+ """A simple chat reply function.
390
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
391
+ chat_queue.
392
+
393
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
394
+
395
+ Returns:
396
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
397
+ """
398
+ last_msg = messages[-1].get("content")
399
+ chat_to_run = []
400
+ for i, c in enumerate(chat_queue):
401
+ current_c = c.copy()
402
+ if current_c.get("sender") is None:
403
+ current_c["sender"] = recipient
404
+ message = current_c.get("message")
405
+ # If message is not provided in chat_queue, we by default use the last message from the original chat history as the first message in this nested chat (for the first chat in the chat queue).
406
+ # NOTE: This setting is prone to change.
407
+ if message is None and i == 0:
408
+ message = last_msg
409
+ if callable(message):
410
+ message = message(recipient, messages, sender, config)
411
+ # We only run chat that has a valid message. NOTE: This is prone to change dependin on applications.
412
+ if message:
413
+ current_c["message"] = message
414
+ chat_to_run.append(current_c)
415
+ return chat_to_run
416
+
417
+ @staticmethod
418
+ def _summary_from_nested_chats(
419
+ chat_queue: List[Dict[str, Any]], recipient: Agent, messages: Union[str, Callable], sender: Agent, config: Any
420
+ ) -> Tuple[bool, Union[str, None]]:
421
+ """A simple chat reply function.
422
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
423
+ chat_queue.
424
+
425
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
426
+
427
+ Returns:
428
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
429
+ """
430
+ chat_to_run = ConversableAgent._get_chats_to_run(chat_queue, recipient, messages, sender, config)
431
+ if not chat_to_run:
432
+ return True, None
433
+ res = initiate_chats(chat_to_run)
434
+ return True, res[-1].summary
435
+
436
+ @staticmethod
437
+ async def _a_summary_from_nested_chats(
438
+ chat_queue: List[Dict[str, Any]], recipient: Agent, messages: Union[str, Callable], sender: Agent, config: Any
439
+ ) -> Tuple[bool, Union[str, None]]:
440
+ """A simple chat reply function.
441
+ This function initiate one or a sequence of chats between the "recipient" and the agents in the
442
+ chat_queue.
443
+
444
+ It extracts and returns a summary from the nested chat based on the "summary_method" in each chat in chat_queue.
445
+
446
+ Returns:
447
+ Tuple[bool, str]: A tuple where the first element indicates the completion of the chat, and the second element contains the summary of the last chat if any chats were initiated.
448
+ """
449
+ chat_to_run = ConversableAgent._get_chats_to_run(chat_queue, recipient, messages, sender, config)
450
+ if not chat_to_run:
451
+ return True, None
452
+ res = await a_initiate_chats(chat_to_run)
453
+ index_of_last_chat = chat_to_run[-1]["chat_id"]
454
+ return True, res[index_of_last_chat].summary
455
+
456
+ def register_nested_chats(
457
+ self,
458
+ chat_queue: List[Dict[str, Any]],
459
+ trigger: Union[Type[Agent], str, Agent, Callable[[Agent], bool], List],
460
+ reply_func_from_nested_chats: Union[str, Callable] = "summary_from_nested_chats",
461
+ position: int = 2,
462
+ use_async: Union[bool, None] = None,
463
+ **kwargs,
464
+ ) -> None:
465
+ """Register a nested chat reply function.
466
+ Args:
467
+ chat_queue (list): a list of chat objects to be initiated. If use_async is used, then all messages in chat_queue must have a chat-id associated with them.
468
+ trigger (Agent class, str, Agent instance, callable, or list): refer to `register_reply` for details.
469
+ reply_func_from_nested_chats (Callable, str): the reply function for the nested chat.
470
+ The function takes a chat_queue for nested chat, recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.
471
+ Default to "summary_from_nested_chats", which corresponds to a built-in reply function that get summary from the nested chat_queue.
472
+ ```python
473
+ def reply_func_from_nested_chats(
474
+ chat_queue: List[Dict],
475
+ recipient: ConversableAgent,
476
+ messages: Optional[List[Dict]] = None,
477
+ sender: Optional[Agent] = None,
478
+ config: Optional[Any] = None,
479
+ ) -> Tuple[bool, Union[str, Dict, None]]:
480
+ ```
481
+ position (int): Ref to `register_reply` for details. Default to 2. It means we first check the termination and human reply, then check the registered nested chat reply.
482
+ use_async: Uses a_initiate_chats internally to start nested chats. If the original chat is initiated with a_initiate_chats, you may set this to true so nested chats do not run in sync.
483
+ kwargs: Ref to `register_reply` for details.
484
+ """
485
+ if use_async:
486
+ for chat in chat_queue:
487
+ if chat.get("chat_id") is None:
488
+ raise ValueError("chat_id is required for async nested chats")
489
+
490
+ if use_async:
491
+ if reply_func_from_nested_chats == "summary_from_nested_chats":
492
+ reply_func_from_nested_chats = self._a_summary_from_nested_chats
493
+ if not callable(reply_func_from_nested_chats) or not inspect.iscoroutinefunction(
494
+ reply_func_from_nested_chats
495
+ ):
496
+ raise ValueError("reply_func_from_nested_chats must be a callable and a coroutine")
497
+
498
+ async def wrapped_reply_func(recipient, messages=None, sender=None, config=None):
499
+ return await reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)
500
+
501
+ else:
502
+ if reply_func_from_nested_chats == "summary_from_nested_chats":
503
+ reply_func_from_nested_chats = self._summary_from_nested_chats
504
+ if not callable(reply_func_from_nested_chats):
505
+ raise ValueError("reply_func_from_nested_chats must be a callable")
506
+
507
+ def wrapped_reply_func(recipient, messages=None, sender=None, config=None):
508
+ return reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)
509
+
510
+ functools.update_wrapper(wrapped_reply_func, reply_func_from_nested_chats)
511
+
512
+ self.register_reply(
513
+ trigger,
514
+ wrapped_reply_func,
515
+ position,
516
+ kwargs.get("config"),
517
+ kwargs.get("reset_config"),
518
+ ignore_async_in_sync_chat=(
519
+ not use_async if use_async is not None else kwargs.get("ignore_async_in_sync_chat")
520
+ ),
521
+ )
522
+
523
+ @property
524
+ def system_message(self) -> str:
525
+ """Return the system message."""
526
+ return self._oai_system_message[0]["content"]
527
+
528
+ def update_system_message(self, system_message: str) -> None:
529
+ """Update the system message.
530
+
531
+ Args:
532
+ system_message (str): system message for the ChatCompletion inference.
533
+ """
534
+ self._oai_system_message[0]["content"] = system_message
535
+
536
+ def update_max_consecutive_auto_reply(self, value: int, sender: Optional[Agent] = None):
537
+ """Update the maximum number of consecutive auto replies.
538
+
539
+ Args:
540
+ value (int): the maximum number of consecutive auto replies.
541
+ sender (Agent): when the sender is provided, only update the max_consecutive_auto_reply for that sender.
542
+ """
543
+ if sender is None:
544
+ self._max_consecutive_auto_reply = value
545
+ for k in self._max_consecutive_auto_reply_dict:
546
+ self._max_consecutive_auto_reply_dict[k] = value
547
+ else:
548
+ self._max_consecutive_auto_reply_dict[sender] = value
549
+
550
+ def max_consecutive_auto_reply(self, sender: Optional[Agent] = None) -> int:
551
+ """The maximum number of consecutive auto replies."""
552
+ return self._max_consecutive_auto_reply if sender is None else self._max_consecutive_auto_reply_dict[sender]
553
+
554
+ @property
555
+ def chat_messages(self) -> Dict[Agent, List[Dict]]:
556
+ """A dictionary of conversations from agent to list of messages."""
557
+ return self._oai_messages
558
+
559
+ def chat_messages_for_summary(self, agent: Agent) -> List[Dict]:
560
+ """A list of messages as a conversation to summarize."""
561
+ return self._oai_messages[agent]
562
+
563
+ def last_message(self, agent: Optional[Agent] = None) -> Optional[Dict]:
564
+ """The last message exchanged with the agent.
565
+
566
+ Args:
567
+ agent (Agent): The agent in the conversation.
568
+ If None and more than one agent's conversations are found, an error will be raised.
569
+ If None and only one conversation is found, the last message of the only conversation will be returned.
570
+
571
+ Returns:
572
+ The last message exchanged with the agent.
573
+ """
574
+ if agent is None:
575
+ n_conversations = len(self._oai_messages)
576
+ if n_conversations == 0:
577
+ return None
578
+ if n_conversations == 1:
579
+ for conversation in self._oai_messages.values():
580
+ return conversation[-1]
581
+ raise ValueError("More than one conversation is found. Please specify the sender to get the last message.")
582
+ if agent not in self._oai_messages.keys():
583
+ raise KeyError(
584
+ f"The agent '{agent.name}' is not present in any conversation. No history available for this agent."
585
+ )
586
+ return self._oai_messages[agent][-1]
587
+
588
+ @property
589
+ def use_docker(self) -> Union[bool, str, None]:
590
+ """Bool value of whether to use docker to execute the code,
591
+ or str value of the docker image name to use, or None when code execution is disabled.
592
+ """
593
+ return None if self._code_execution_config is False else self._code_execution_config.get("use_docker")
594
+
595
+ @staticmethod
596
+ def _message_to_dict(message: Union[Dict, str]) -> Dict:
597
+ """Convert a message to a dictionary.
598
+
599
+ The message can be a string or a dictionary. The string will be put in the "content" field of the new dictionary.
600
+ """
601
+ if isinstance(message, str):
602
+ return {"content": message}
603
+ elif isinstance(message, dict):
604
+ return message
605
+ else:
606
+ return dict(message)
607
+
608
+ @staticmethod
609
+ def _normalize_name(name):
610
+ """
611
+ LLMs sometimes ask functions while ignoring their own format requirements, this function should be used to replace invalid characters with "_".
612
+
613
+ Prefer _assert_valid_name for validating user configuration or input
614
+ """
615
+ return re.sub(r"[^a-zA-Z0-9_-]", "_", name)[:64]
616
+
617
+ @staticmethod
618
+ def _assert_valid_name(name):
619
+ """
620
+ Ensure that configured names are valid, raises ValueError if not.
621
+
622
+ For munging LLM responses use _normalize_name to ensure LLM specified names don't break the API.
623
+ """
624
+ if not re.match(r"^[a-zA-Z0-9_-]+$", name):
625
+ raise ValueError(f"Invalid name: {name}. Only letters, numbers, '_' and '-' are allowed.")
626
+ if len(name) > 64:
627
+ raise ValueError(f"Invalid name: {name}. Name must be less than 64 characters.")
628
+ return name
629
+
630
+ def _append_oai_message(self, message: Union[Dict, str], role, conversation_id: Agent, is_sending: bool) -> bool:
631
+ """Append a message to the ChatCompletion conversation.
632
+
633
+ If the message received is a string, it will be put in the "content" field of the new dictionary.
634
+ If the message received is a dictionary but does not have any of the three fields "content", "function_call", or "tool_calls",
635
+ this message is not a valid ChatCompletion message.
636
+ If only "function_call" or "tool_calls" is provided, "content" will be set to None if not provided, and the role of the message will be forced "assistant".
637
+
638
+ Args:
639
+ message (dict or str): message to be appended to the ChatCompletion conversation.
640
+ role (str): role of the message, can be "assistant" or "function".
641
+ conversation_id (Agent): id of the conversation, should be the recipient or sender.
642
+ is_sending (bool): If the agent (aka self) is sending to the conversation_id agent, otherwise receiving.
643
+
644
+ Returns:
645
+ bool: whether the message is appended to the ChatCompletion conversation.
646
+ """
647
+ message = self._message_to_dict(message)
648
+ # create oai message to be appended to the oai conversation that can be passed to oai directly.
649
+ oai_message = {
650
+ k: message[k]
651
+ for k in ("content", "function_call", "tool_calls", "tool_responses", "tool_call_id", "name", "context")
652
+ if k in message and message[k] is not None
653
+ }
654
+ if "content" not in oai_message:
655
+ if "function_call" in oai_message or "tool_calls" in oai_message:
656
+ oai_message["content"] = None # if only function_call is provided, content will be set to None.
657
+ else:
658
+ return False
659
+
660
+ if message.get("role") in ["function", "tool"]:
661
+ oai_message["role"] = message.get("role")
662
+ elif "override_role" in message:
663
+ # If we have a direction to override the role then set the
664
+ # role accordingly. Used to customise the role for the
665
+ # select speaker prompt.
666
+ oai_message["role"] = message.get("override_role")
667
+ else:
668
+ oai_message["role"] = role
669
+
670
+ if oai_message.get("function_call", False) or oai_message.get("tool_calls", False):
671
+ oai_message["role"] = "assistant" # only messages with role 'assistant' can have a function call.
672
+ elif "name" not in oai_message:
673
+ # If we don't have a name field, append it
674
+ if is_sending:
675
+ oai_message["name"] = self.name
676
+ else:
677
+ oai_message["name"] = conversation_id.name
678
+
679
+ self._oai_messages[conversation_id].append(oai_message)
680
+
681
+ return True
682
+
683
+ def _process_message_before_send(
684
+ self, message: Union[Dict, str], recipient: Agent, silent: bool
685
+ ) -> Union[Dict, str]:
686
+ """Process the message before sending it to the recipient."""
687
+ hook_list = self.hook_lists["process_message_before_send"]
688
+ for hook in hook_list:
689
+ message = hook(
690
+ sender=self, message=message, recipient=recipient, silent=ConversableAgent._is_silent(self, silent)
691
+ )
692
+ return message
693
+
694
+ def send(
695
+ self,
696
+ message: Union[Dict, str],
697
+ recipient: Agent,
698
+ request_reply: Optional[bool] = None,
699
+ silent: Optional[bool] = False,
700
+ ):
701
+ """Send a message to another agent.
702
+
703
+ Args:
704
+ message (dict or str): message to be sent.
705
+ The message could contain the following fields:
706
+ - content (str or List): Required, the content of the message. (Can be None)
707
+ - function_call (str): the name of the function to be called.
708
+ - name (str): the name of the function to be called.
709
+ - role (str): the role of the message, any role that is not "function"
710
+ will be modified to "assistant".
711
+ - context (dict): the context of the message, which will be passed to
712
+ [OpenAIWrapper.create](../oai/client#create).
713
+ For example, one agent can send a message A as:
714
+ ```python
715
+ {
716
+ "content": lambda context: context["use_tool_msg"],
717
+ "context": {
718
+ "use_tool_msg": "Use tool X if they are relevant."
719
+ }
720
+ }
721
+ ```
722
+ Next time, one agent can send a message B with a different "use_tool_msg".
723
+ Then the content of message A will be refreshed to the new "use_tool_msg".
724
+ So effectively, this provides a way for an agent to send a "link" and modify
725
+ the content of the "link" later.
726
+ recipient (Agent): the recipient of the message.
727
+ request_reply (bool or None): whether to request a reply from the recipient.
728
+ silent (bool or None): (Experimental) whether to print the message sent.
729
+
730
+ Raises:
731
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
732
+ """
733
+ message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))
734
+ # When the agent composes and sends the message, the role of the message is "assistant"
735
+ # unless it's "function".
736
+ valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)
737
+ if valid:
738
+ recipient.receive(message, self, request_reply, silent)
739
+ else:
740
+ raise ValueError(
741
+ "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
742
+ )
743
+
744
+ async def a_send(
745
+ self,
746
+ message: Union[Dict, str],
747
+ recipient: Agent,
748
+ request_reply: Optional[bool] = None,
749
+ silent: Optional[bool] = False,
750
+ ):
751
+ """(async) Send a message to another agent.
752
+
753
+ Args:
754
+ message (dict or str): message to be sent.
755
+ The message could contain the following fields:
756
+ - content (str or List): Required, the content of the message. (Can be None)
757
+ - function_call (str): the name of the function to be called.
758
+ - name (str): the name of the function to be called.
759
+ - role (str): the role of the message, any role that is not "function"
760
+ will be modified to "assistant".
761
+ - context (dict): the context of the message, which will be passed to
762
+ [OpenAIWrapper.create](../oai/client#create).
763
+ For example, one agent can send a message A as:
764
+ ```python
765
+ {
766
+ "content": lambda context: context["use_tool_msg"],
767
+ "context": {
768
+ "use_tool_msg": "Use tool X if they are relevant."
769
+ }
770
+ }
771
+ ```
772
+ Next time, one agent can send a message B with a different "use_tool_msg".
773
+ Then the content of message A will be refreshed to the new "use_tool_msg".
774
+ So effectively, this provides a way for an agent to send a "link" and modify
775
+ the content of the "link" later.
776
+ recipient (Agent): the recipient of the message.
777
+ request_reply (bool or None): whether to request a reply from the recipient.
778
+ silent (bool or None): (Experimental) whether to print the message sent.
779
+
780
+ Raises:
781
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
782
+ """
783
+ message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))
784
+ # When the agent composes and sends the message, the role of the message is "assistant"
785
+ # unless it's "function".
786
+ valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)
787
+ if valid:
788
+ await recipient.a_receive(message, self, request_reply, silent)
789
+ else:
790
+ raise ValueError(
791
+ "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
792
+ )
793
+
794
+ def _print_received_message(self, message: Union[Dict, str], sender: Agent):
795
+ iostream = IOStream.get_default()
796
+ # print the message received
797
+ iostream.print(colored(sender.name, "yellow"), "(to", f"{self.name}):\n", flush=True)
798
+ message = self._message_to_dict(message)
799
+
800
+ if message.get("tool_responses"): # Handle tool multi-call responses
801
+ for tool_response in message["tool_responses"]:
802
+ self._print_received_message(tool_response, sender)
803
+ if message.get("role") == "tool":
804
+ return # If role is tool, then content is just a concatenation of all tool_responses
805
+
806
+ if message.get("role") in ["function", "tool"]:
807
+ if message["role"] == "function":
808
+ id_key = "name"
809
+ else:
810
+ id_key = "tool_call_id"
811
+ id = message.get(id_key, "No id found")
812
+ func_print = f"***** Response from calling {message['role']} ({id}) *****"
813
+ iostream.print(colored(func_print, "green"), flush=True)
814
+ iostream.print(message["content"], flush=True)
815
+ iostream.print(colored("*" * len(func_print), "green"), flush=True)
816
+ else:
817
+ content = message.get("content")
818
+ if content is not None:
819
+ if "context" in message:
820
+ content = OpenAIWrapper.instantiate(
821
+ content,
822
+ message["context"],
823
+ self.llm_config and self.llm_config.get("allow_format_str_template", False),
824
+ )
825
+ iostream.print(content_str(content), flush=True)
826
+ if "function_call" in message and message["function_call"]:
827
+ function_call = dict(message["function_call"])
828
+ func_print = (
829
+ f"***** Suggested function call: {function_call.get('name', '(No function name found)')} *****"
830
+ )
831
+ iostream.print(colored(func_print, "green"), flush=True)
832
+ iostream.print(
833
+ "Arguments: \n",
834
+ function_call.get("arguments", "(No arguments found)"),
835
+ flush=True,
836
+ sep="",
837
+ )
838
+ iostream.print(colored("*" * len(func_print), "green"), flush=True)
839
+ if "tool_calls" in message and message["tool_calls"]:
840
+ for tool_call in message["tool_calls"]:
841
+ id = tool_call.get("id", "No tool call id found")
842
+ function_call = dict(tool_call.get("function", {}))
843
+ func_print = f"***** Suggested tool call ({id}): {function_call.get('name', '(No function name found)')} *****"
844
+ iostream.print(colored(func_print, "green"), flush=True)
845
+ iostream.print(
846
+ "Arguments: \n",
847
+ function_call.get("arguments", "(No arguments found)"),
848
+ flush=True,
849
+ sep="",
850
+ )
851
+ iostream.print(colored("*" * len(func_print), "green"), flush=True)
852
+
853
+ iostream.print("\n", "-" * 80, flush=True, sep="")
854
+
855
+ def _process_received_message(self, message: Union[Dict, str], sender: Agent, silent: bool):
856
+ # When the agent receives a message, the role of the message is "user". (If 'role' exists and is 'function', it will remain unchanged.)
857
+ valid = self._append_oai_message(message, "user", sender, is_sending=False)
858
+ if logging_enabled():
859
+ log_event(self, "received_message", message=message, sender=sender.name, valid=valid)
860
+
861
+ if not valid:
862
+ raise ValueError(
863
+ "Received message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."
864
+ )
865
+
866
+ if not ConversableAgent._is_silent(sender, silent):
867
+ self._print_received_message(message, sender)
868
+
869
+ def receive(
870
+ self,
871
+ message: Union[Dict, str],
872
+ sender: Agent,
873
+ request_reply: Optional[bool] = None,
874
+ silent: Optional[bool] = False,
875
+ ):
876
+ """Receive a message from another agent.
877
+
878
+ Once a message is received, this function sends a reply to the sender or stop.
879
+ The reply can be generated automatically or entered manually by a human.
880
+
881
+ Args:
882
+ message (dict or str): message from the sender. If the type is dict, it may contain the following reserved fields (either content or function_call need to be provided).
883
+ 1. "content": content of the message, can be None.
884
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
885
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
886
+ 4. "role": role of the message, can be "assistant", "user", "function", "tool".
887
+ This field is only needed to distinguish between "function" or "assistant"/"user".
888
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
889
+ 6. "context" (dict): the context of the message, which will be passed to
890
+ [OpenAIWrapper.create](../oai/client#create).
891
+ sender: sender of an Agent instance.
892
+ request_reply (bool or None): whether a reply is requested from the sender.
893
+ If None, the value is determined by `self.reply_at_receive[sender]`.
894
+ silent (bool or None): (Experimental) whether to print the message received.
895
+
896
+ Raises:
897
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
898
+ """
899
+ self._process_received_message(message, sender, silent)
900
+ if request_reply is False or request_reply is None and self.reply_at_receive[sender] is False:
901
+ return
902
+ reply = self.generate_reply(messages=self.chat_messages[sender], sender=sender)
903
+ if reply is not None:
904
+ self.send(reply, sender, silent=silent)
905
+
906
+ async def a_receive(
907
+ self,
908
+ message: Union[Dict, str],
909
+ sender: Agent,
910
+ request_reply: Optional[bool] = None,
911
+ silent: Optional[bool] = False,
912
+ ):
913
+ """(async) Receive a message from another agent.
914
+
915
+ Once a message is received, this function sends a reply to the sender or stop.
916
+ The reply can be generated automatically or entered manually by a human.
917
+
918
+ Args:
919
+ message (dict or str): message from the sender. If the type is dict, it may contain the following reserved fields (either content or function_call need to be provided).
920
+ 1. "content": content of the message, can be None.
921
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
922
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
923
+ 4. "role": role of the message, can be "assistant", "user", "function".
924
+ This field is only needed to distinguish between "function" or "assistant"/"user".
925
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
926
+ 6. "context" (dict): the context of the message, which will be passed to
927
+ [OpenAIWrapper.create](../oai/client#create).
928
+ sender: sender of an Agent instance.
929
+ request_reply (bool or None): whether a reply is requested from the sender.
930
+ If None, the value is determined by `self.reply_at_receive[sender]`.
931
+ silent (bool or None): (Experimental) whether to print the message received.
932
+
933
+ Raises:
934
+ ValueError: if the message can't be converted into a valid ChatCompletion message.
935
+ """
936
+ self._process_received_message(message, sender, silent)
937
+ if request_reply is False or request_reply is None and self.reply_at_receive[sender] is False:
938
+ return
939
+ reply = await self.a_generate_reply(sender=sender)
940
+ if reply is not None:
941
+ await self.a_send(reply, sender, silent=silent)
942
+
943
+ def _prepare_chat(
944
+ self,
945
+ recipient: "ConversableAgent",
946
+ clear_history: bool,
947
+ prepare_recipient: bool = True,
948
+ reply_at_receive: bool = True,
949
+ ) -> None:
950
+ self.reset_consecutive_auto_reply_counter(recipient)
951
+ self.reply_at_receive[recipient] = reply_at_receive
952
+ if clear_history:
953
+ self.clear_history(recipient)
954
+ self._human_input = []
955
+ if prepare_recipient:
956
+ recipient._prepare_chat(self, clear_history, False, reply_at_receive)
957
+
958
+ def _raise_exception_on_async_reply_functions(self) -> None:
959
+ """Raise an exception if any async reply functions are registered.
960
+
961
+ Raises:
962
+ RuntimeError: if any async reply functions are registered.
963
+ """
964
+ reply_functions = {
965
+ f["reply_func"] for f in self._reply_func_list if not f.get("ignore_async_in_sync_chat", False)
966
+ }
967
+
968
+ async_reply_functions = [f for f in reply_functions if inspect.iscoroutinefunction(f)]
969
+ if async_reply_functions:
970
+ msg = (
971
+ "Async reply functions can only be used with ConversableAgent.a_initiate_chat(). The following async reply functions are found: "
972
+ + ", ".join([f.__name__ for f in async_reply_functions])
973
+ )
974
+
975
+ raise RuntimeError(msg)
976
+
977
+ def initiate_chat(
978
+ self,
979
+ recipient: "ConversableAgent",
980
+ clear_history: bool = True,
981
+ silent: Optional[bool] = False,
982
+ cache: Optional[AbstractCache] = None,
983
+ max_turns: Optional[int] = None,
984
+ summary_method: Optional[Union[str, Callable]] = DEFAULT_SUMMARY_METHOD,
985
+ summary_args: Optional[dict] = {},
986
+ message: Optional[Union[Dict, str, Callable]] = None,
987
+ **kwargs,
988
+ ) -> ChatResult:
989
+ """Initiate a chat with the recipient agent.
990
+
991
+ Reset the consecutive auto reply counter.
992
+ If `clear_history` is True, the chat history with the recipient agent will be cleared.
993
+
994
+
995
+ Args:
996
+ recipient: the recipient agent.
997
+ clear_history (bool): whether to clear the chat history with the agent. Default is True.
998
+ silent (bool or None): (Experimental) whether to print the messages for this conversation. Default is False.
999
+ cache (AbstractCache or None): the cache client to be used for this conversation. Default is None.
1000
+ max_turns (int or None): the maximum number of turns for the chat between the two agents. One turn means one conversation round trip. Note that this is different from
1001
+ [max_consecutive_auto_reply](#max_consecutive_auto_reply) which is the maximum number of consecutive auto replies; and it is also different from [max_rounds in GroupChat](./groupchat#groupchat-objects) which is the maximum number of rounds in a group chat session.
1002
+ If max_turns is set to None, the chat will continue until a termination condition is met. Default is None.
1003
+ summary_method (str or callable): a method to get a summary from the chat. Default is DEFAULT_SUMMARY_METHOD, i.e., "last_msg".
1004
+
1005
+ Supported strings are "last_msg" and "reflection_with_llm":
1006
+ - when set to "last_msg", it returns the last message of the dialog as the summary.
1007
+ - when set to "reflection_with_llm", it returns a summary extracted using an llm client.
1008
+ `llm_config` must be set in either the recipient or sender.
1009
+
1010
+ A callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g.,
1011
+
1012
+ ```python
1013
+ def my_summary_method(
1014
+ sender: ConversableAgent,
1015
+ recipient: ConversableAgent,
1016
+ summary_args: dict,
1017
+ ):
1018
+ return recipient.last_message(sender)["content"]
1019
+ ```
1020
+ summary_args (dict): a dictionary of arguments to be passed to the summary_method.
1021
+ One example key is "summary_prompt", and value is a string of text used to prompt a LLM-based agent (the sender or receiver agent) to reflect
1022
+ on the conversation and extract a summary when summary_method is "reflection_with_llm".
1023
+ The default summary_prompt is DEFAULT_SUMMARY_PROMPT, i.e., "Summarize takeaway from the conversation. Do not add any introductory phrases. If the intended request is NOT properly addressed, please point it out."
1024
+ Another available key is "summary_role", which is the role of the message sent to the agent in charge of summarizing. Default is "system".
1025
+ message (str, dict or Callable): the initial message to be sent to the recipient. Needs to be provided. Otherwise, input() will be called to get the initial message.
1026
+ - If a string or a dict is provided, it will be used as the initial message. `generate_init_message` is called to generate the initial message for the agent based on this string and the context.
1027
+ If dict, it may contain the following reserved fields (either content or tool_calls need to be provided).
1028
+
1029
+ 1. "content": content of the message, can be None.
1030
+ 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")
1031
+ 3. "tool_calls": a list of dictionaries containing the function name and arguments.
1032
+ 4. "role": role of the message, can be "assistant", "user", "function".
1033
+ This field is only needed to distinguish between "function" or "assistant"/"user".
1034
+ 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.
1035
+ 6. "context" (dict): the context of the message, which will be passed to
1036
+ [OpenAIWrapper.create](../oai/client#create).
1037
+
1038
+ - If a callable is provided, it will be called to get the initial message in the form of a string or a dict.
1039
+ If the returned type is dict, it may contain the reserved fields mentioned above.
1040
+
1041
+ Example of a callable message (returning a string):
1042
+
1043
+ ```python
1044
+ def my_message(sender: ConversableAgent, recipient: ConversableAgent, context: dict) -> Union[str, Dict]:
1045
+ carryover = context.get("carryover", "")
1046
+ if isinstance(message, list):
1047
+ carryover = carryover[-1]
1048
+ final_msg = "Write a blogpost." + "\\nContext: \\n" + carryover
1049
+ return final_msg
1050
+ ```
1051
+
1052
+ Example of a callable message (returning a dict):
1053
+
1054
+ ```python
1055
+ def my_message(sender: ConversableAgent, recipient: ConversableAgent, context: dict) -> Union[str, Dict]:
1056
+ final_msg = {}
1057
+ carryover = context.get("carryover", "")
1058
+ if isinstance(message, list):
1059
+ carryover = carryover[-1]
1060
+ final_msg["content"] = "Write a blogpost." + "\\nContext: \\n" + carryover
1061
+ final_msg["context"] = {"prefix": "Today I feel"}
1062
+ return final_msg
1063
+ ```
1064
+ **kwargs: any additional information. It has the following reserved fields:
1065
+ - "carryover": a string or a list of string to specify the carryover information to be passed to this chat.
1066
+ If provided, we will combine this carryover (by attaching a "context: " string and the carryover content after the message content) with the "message" content when generating the initial chat
1067
+ message in `generate_init_message`.
1068
+ - "verbose": a boolean to specify whether to print the message and carryover in a chat. Default is False.
1069
+
1070
+ Raises:
1071
+ RuntimeError: if any async reply functions are registered and not ignored in sync chat.
1072
+
1073
+ Returns:
1074
+ ChatResult: an ChatResult object.
1075
+ """
1076
+ _chat_info = locals().copy()
1077
+ _chat_info["sender"] = self
1078
+ consolidate_chat_info(_chat_info, uniform_sender=self)
1079
+ for agent in [self, recipient]:
1080
+ agent._raise_exception_on_async_reply_functions()
1081
+ agent.previous_cache = agent.client_cache
1082
+ agent.client_cache = cache
1083
+ if isinstance(max_turns, int):
1084
+ self._prepare_chat(recipient, clear_history, reply_at_receive=False)
1085
+ for _ in range(max_turns):
1086
+ if _ == 0:
1087
+ if isinstance(message, Callable):
1088
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1089
+ else:
1090
+ msg2send = self.generate_init_message(message, **kwargs)
1091
+ else:
1092
+ msg2send = self.generate_reply(messages=self.chat_messages[recipient], sender=recipient)
1093
+ if msg2send is None:
1094
+ break
1095
+ self.send(msg2send, recipient, request_reply=True, silent=silent)
1096
+ else:
1097
+ self._prepare_chat(recipient, clear_history)
1098
+ if isinstance(message, Callable):
1099
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1100
+ else:
1101
+ msg2send = self.generate_init_message(message, **kwargs)
1102
+ self.send(msg2send, recipient, silent=silent)
1103
+ summary = self._summarize_chat(
1104
+ summary_method,
1105
+ summary_args,
1106
+ recipient,
1107
+ cache=cache,
1108
+ )
1109
+ for agent in [self, recipient]:
1110
+ agent.client_cache = agent.previous_cache
1111
+ agent.previous_cache = None
1112
+ chat_result = ChatResult(
1113
+ chat_history=self.chat_messages[recipient],
1114
+ summary=summary,
1115
+ cost=gather_usage_summary([self, recipient]),
1116
+ human_input=self._human_input,
1117
+ )
1118
+ return chat_result
1119
+
1120
+ async def a_initiate_chat(
1121
+ self,
1122
+ recipient: "ConversableAgent",
1123
+ clear_history: bool = True,
1124
+ silent: Optional[bool] = False,
1125
+ cache: Optional[AbstractCache] = None,
1126
+ max_turns: Optional[int] = None,
1127
+ summary_method: Optional[Union[str, Callable]] = DEFAULT_SUMMARY_METHOD,
1128
+ summary_args: Optional[dict] = {},
1129
+ message: Optional[Union[str, Callable]] = None,
1130
+ **kwargs,
1131
+ ) -> ChatResult:
1132
+ """(async) Initiate a chat with the recipient agent.
1133
+
1134
+ Reset the consecutive auto reply counter.
1135
+ If `clear_history` is True, the chat history with the recipient agent will be cleared.
1136
+ `a_generate_init_message` is called to generate the initial message for the agent.
1137
+
1138
+ Args: Please refer to `initiate_chat`.
1139
+
1140
+ Returns:
1141
+ ChatResult: an ChatResult object.
1142
+ """
1143
+ _chat_info = locals().copy()
1144
+ _chat_info["sender"] = self
1145
+ consolidate_chat_info(_chat_info, uniform_sender=self)
1146
+ for agent in [self, recipient]:
1147
+ agent.previous_cache = agent.client_cache
1148
+ agent.client_cache = cache
1149
+ if isinstance(max_turns, int):
1150
+ self._prepare_chat(recipient, clear_history, reply_at_receive=False)
1151
+ for _ in range(max_turns):
1152
+ if _ == 0:
1153
+ if isinstance(message, Callable):
1154
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1155
+ else:
1156
+ msg2send = await self.a_generate_init_message(message, **kwargs)
1157
+ else:
1158
+ msg2send = await self.a_generate_reply(messages=self.chat_messages[recipient], sender=recipient)
1159
+ if msg2send is None:
1160
+ break
1161
+ await self.a_send(msg2send, recipient, request_reply=True, silent=silent)
1162
+ else:
1163
+ self._prepare_chat(recipient, clear_history)
1164
+ if isinstance(message, Callable):
1165
+ msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)
1166
+ else:
1167
+ msg2send = await self.a_generate_init_message(message, **kwargs)
1168
+ await self.a_send(msg2send, recipient, silent=silent)
1169
+ summary = self._summarize_chat(
1170
+ summary_method,
1171
+ summary_args,
1172
+ recipient,
1173
+ cache=cache,
1174
+ )
1175
+ for agent in [self, recipient]:
1176
+ agent.client_cache = agent.previous_cache
1177
+ agent.previous_cache = None
1178
+ chat_result = ChatResult(
1179
+ chat_history=self.chat_messages[recipient],
1180
+ summary=summary,
1181
+ cost=gather_usage_summary([self, recipient]),
1182
+ human_input=self._human_input,
1183
+ )
1184
+ return chat_result
1185
+
1186
+ def _summarize_chat(
1187
+ self,
1188
+ summary_method,
1189
+ summary_args,
1190
+ recipient: Optional[Agent] = None,
1191
+ cache: Optional[AbstractCache] = None,
1192
+ ) -> str:
1193
+ """Get a chat summary from an agent participating in a chat.
1194
+
1195
+ Args:
1196
+ summary_method (str or callable): the summary_method to get the summary.
1197
+ The callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g,
1198
+ ```python
1199
+ def my_summary_method(
1200
+ sender: ConversableAgent,
1201
+ recipient: ConversableAgent,
1202
+ summary_args: dict,
1203
+ ):
1204
+ return recipient.last_message(sender)["content"]
1205
+ ```
1206
+ summary_args (dict): a dictionary of arguments to be passed to the summary_method.
1207
+ recipient: the recipient agent in a chat.
1208
+ prompt (str): the prompt used to get a summary when summary_method is "reflection_with_llm".
1209
+
1210
+ Returns:
1211
+ str: a chat summary from the agent.
1212
+ """
1213
+ summary = ""
1214
+ if summary_method is None:
1215
+ return summary
1216
+ if "cache" not in summary_args:
1217
+ summary_args["cache"] = cache
1218
+ if summary_method == "reflection_with_llm":
1219
+ summary_method = self._reflection_with_llm_as_summary
1220
+ elif summary_method == "last_msg":
1221
+ summary_method = self._last_msg_as_summary
1222
+
1223
+ if isinstance(summary_method, Callable):
1224
+ summary = summary_method(self, recipient, summary_args)
1225
+ else:
1226
+ raise ValueError(
1227
+ "If not None, the summary_method must be a string from [`reflection_with_llm`, `last_msg`] or a callable."
1228
+ )
1229
+ return summary
1230
+
1231
+ @staticmethod
1232
+ def _last_msg_as_summary(sender, recipient, summary_args) -> str:
1233
+ """Get a chat summary from the last message of the recipient."""
1234
+ summary = ""
1235
+ try:
1236
+ content = recipient.last_message(sender)["content"]
1237
+ if isinstance(content, str):
1238
+ summary = content.replace("TERMINATE", "")
1239
+ elif isinstance(content, list):
1240
+ # Remove the `TERMINATE` word in the content list.
1241
+ summary = "\n".join(
1242
+ x["text"].replace("TERMINATE", "") for x in content if isinstance(x, dict) and "text" in x
1243
+ )
1244
+ except (IndexError, AttributeError) as e:
1245
+ warnings.warn(f"Cannot extract summary using last_msg: {e}. Using an empty str as summary.", UserWarning)
1246
+ return summary
1247
+
1248
+ @staticmethod
1249
+ def _reflection_with_llm_as_summary(sender, recipient, summary_args):
1250
+ prompt = summary_args.get("summary_prompt")
1251
+ prompt = ConversableAgent.DEFAULT_SUMMARY_PROMPT if prompt is None else prompt
1252
+ if not isinstance(prompt, str):
1253
+ raise ValueError("The summary_prompt must be a string.")
1254
+ msg_list = recipient.chat_messages_for_summary(sender)
1255
+ agent = sender if recipient is None else recipient
1256
+ role = summary_args.get("summary_role", None)
1257
+ if role and not isinstance(role, str):
1258
+ raise ValueError("The summary_role in summary_arg must be a string.")
1259
+ try:
1260
+ summary = sender._reflection_with_llm(
1261
+ prompt, msg_list, llm_agent=agent, cache=summary_args.get("cache"), role=role
1262
+ )
1263
+ except BadRequestError as e:
1264
+ warnings.warn(
1265
+ f"Cannot extract summary using reflection_with_llm: {e}. Using an empty str as summary.", UserWarning
1266
+ )
1267
+ summary = ""
1268
+ return summary
1269
+
1270
+ def _reflection_with_llm(
1271
+ self,
1272
+ prompt,
1273
+ messages,
1274
+ llm_agent: Optional[Agent] = None,
1275
+ cache: Optional[AbstractCache] = None,
1276
+ role: Union[str, None] = None,
1277
+ ) -> str:
1278
+ """Get a chat summary using reflection with an llm client based on the conversation history.
1279
+
1280
+ Args:
1281
+ prompt (str): The prompt (in this method it is used as system prompt) used to get the summary.
1282
+ messages (list): The messages generated as part of a chat conversation.
1283
+ llm_agent: the agent with an llm client.
1284
+ cache (AbstractCache or None): the cache client to be used for this conversation.
1285
+ role (str): the role of the message, usually "system" or "user". Default is "system".
1286
+ """
1287
+ if not role:
1288
+ role = "system"
1289
+
1290
+ system_msg = [
1291
+ {
1292
+ "role": role,
1293
+ "content": prompt,
1294
+ }
1295
+ ]
1296
+
1297
+ messages = messages + system_msg
1298
+ if llm_agent and llm_agent.client is not None:
1299
+ llm_client = llm_agent.client
1300
+ elif self.client is not None:
1301
+ llm_client = self.client
1302
+ else:
1303
+ raise ValueError("No OpenAIWrapper client is found.")
1304
+ response = self._generate_oai_reply_from_client(llm_client=llm_client, messages=messages, cache=cache)
1305
+ return response
1306
+
1307
+ def _check_chat_queue_for_sender(self, chat_queue: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
1308
+ """
1309
+ Check the chat queue and add the "sender" key if it's missing.
1310
+
1311
+ Args:
1312
+ chat_queue (List[Dict[str, Any]]): A list of dictionaries containing chat information.
1313
+
1314
+ Returns:
1315
+ List[Dict[str, Any]]: A new list of dictionaries with the "sender" key added if it was missing.
1316
+ """
1317
+ chat_queue_with_sender = []
1318
+ for chat_info in chat_queue:
1319
+ if chat_info.get("sender") is None:
1320
+ chat_info["sender"] = self
1321
+ chat_queue_with_sender.append(chat_info)
1322
+ return chat_queue_with_sender
1323
+
1324
+ def initiate_chats(self, chat_queue: List[Dict[str, Any]]) -> List[ChatResult]:
1325
+ """(Experimental) Initiate chats with multiple agents.
1326
+
1327
+ Args:
1328
+ chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.
1329
+ Each dictionary should contain the input arguments for [`initiate_chat`](conversable_agent#initiate_chat)
1330
+
1331
+ Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.
1332
+ """
1333
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
1334
+ self._finished_chats = initiate_chats(_chat_queue)
1335
+ return self._finished_chats
1336
+
1337
+ async def a_initiate_chats(self, chat_queue: List[Dict[str, Any]]) -> Dict[int, ChatResult]:
1338
+ _chat_queue = self._check_chat_queue_for_sender(chat_queue)
1339
+ self._finished_chats = await a_initiate_chats(_chat_queue)
1340
+ return self._finished_chats
1341
+
1342
+ def get_chat_results(self, chat_index: Optional[int] = None) -> Union[List[ChatResult], ChatResult]:
1343
+ """A summary from the finished chats of particular agents."""
1344
+ if chat_index is not None:
1345
+ return self._finished_chats[chat_index]
1346
+ else:
1347
+ return self._finished_chats
1348
+
1349
+ def reset(self):
1350
+ """Reset the agent."""
1351
+ self.clear_history()
1352
+ self.reset_consecutive_auto_reply_counter()
1353
+ self.stop_reply_at_receive()
1354
+ if self.client is not None:
1355
+ self.client.clear_usage_summary()
1356
+ for reply_func_tuple in self._reply_func_list:
1357
+ if reply_func_tuple["reset_config"] is not None:
1358
+ reply_func_tuple["reset_config"](reply_func_tuple["config"])
1359
+ else:
1360
+ reply_func_tuple["config"] = copy.copy(reply_func_tuple["init_config"])
1361
+
1362
+ def stop_reply_at_receive(self, sender: Optional[Agent] = None):
1363
+ """Reset the reply_at_receive of the sender."""
1364
+ if sender is None:
1365
+ self.reply_at_receive.clear()
1366
+ else:
1367
+ self.reply_at_receive[sender] = False
1368
+
1369
+ def reset_consecutive_auto_reply_counter(self, sender: Optional[Agent] = None):
1370
+ """Reset the consecutive_auto_reply_counter of the sender."""
1371
+ if sender is None:
1372
+ self._consecutive_auto_reply_counter.clear()
1373
+ else:
1374
+ self._consecutive_auto_reply_counter[sender] = 0
1375
+
1376
+ def clear_history(self, recipient: Optional[Agent] = None, nr_messages_to_preserve: Optional[int] = None):
1377
+ """Clear the chat history of the agent.
1378
+
1379
+ Args:
1380
+ recipient: the agent with whom the chat history to clear. If None, clear the chat history with all agents.
1381
+ nr_messages_to_preserve: the number of newest messages to preserve in the chat history.
1382
+ """
1383
+ iostream = IOStream.get_default()
1384
+ if recipient is None:
1385
+ if nr_messages_to_preserve:
1386
+ for key in self._oai_messages:
1387
+ nr_messages_to_preserve_internal = nr_messages_to_preserve
1388
+ # if breaking history between function call and function response, save function call message
1389
+ # additionally, otherwise openai will return error
1390
+ first_msg_to_save = self._oai_messages[key][-nr_messages_to_preserve_internal]
1391
+ if "tool_responses" in first_msg_to_save:
1392
+ nr_messages_to_preserve_internal += 1
1393
+ iostream.print(
1394
+ f"Preserving one more message for {self.name} to not divide history between tool call and "
1395
+ f"tool response."
1396
+ )
1397
+ # Remove messages from history except last `nr_messages_to_preserve` messages.
1398
+ self._oai_messages[key] = self._oai_messages[key][-nr_messages_to_preserve_internal:]
1399
+ else:
1400
+ self._oai_messages.clear()
1401
+ else:
1402
+ self._oai_messages[recipient].clear()
1403
+ if nr_messages_to_preserve:
1404
+ iostream.print(
1405
+ colored(
1406
+ "WARNING: `nr_preserved_messages` is ignored when clearing chat history with a specific agent.",
1407
+ "yellow",
1408
+ ),
1409
+ flush=True,
1410
+ )
1411
+
1412
+ def generate_oai_reply(
1413
+ self,
1414
+ messages: Optional[List[Dict]] = None,
1415
+ sender: Optional[Agent] = None,
1416
+ config: Optional[OpenAIWrapper] = None,
1417
+ ) -> Tuple[bool, Union[str, Dict, None]]:
1418
+ """Generate a reply using autogen.oai."""
1419
+ client = self.client if config is None else config
1420
+ if client is None:
1421
+ return False, None
1422
+ if messages is None:
1423
+ messages = self._oai_messages[sender]
1424
+ extracted_response = self._generate_oai_reply_from_client(
1425
+ client, self._oai_system_message + messages, self.client_cache
1426
+ )
1427
+ return (False, None) if extracted_response is None else (True, extracted_response)
1428
+
1429
+ def _generate_oai_reply_from_client(self, llm_client, messages, cache) -> Union[str, Dict, None]:
1430
+ # unroll tool_responses
1431
+ all_messages = []
1432
+ for message in messages:
1433
+ tool_responses = message.get("tool_responses", [])
1434
+ if tool_responses:
1435
+ all_messages += tool_responses
1436
+ # tool role on the parent message means the content is just concatenation of all of the tool_responses
1437
+ if message.get("role") != "tool":
1438
+ all_messages.append({key: message[key] for key in message if key != "tool_responses"})
1439
+ else:
1440
+ all_messages.append(message)
1441
+
1442
+ # TODO: #1143 handle token limit exceeded error
1443
+ response = llm_client.create(
1444
+ context=messages[-1].pop("context", None), messages=all_messages, cache=cache, agent=self
1445
+ )
1446
+ extracted_response = llm_client.extract_text_or_completion_object(response)[0]
1447
+
1448
+ if extracted_response is None:
1449
+ warnings.warn(f"Extracted_response from {response} is None.", UserWarning)
1450
+ return None
1451
+ # ensure function and tool calls will be accepted when sent back to the LLM
1452
+ if not isinstance(extracted_response, str) and hasattr(extracted_response, "model_dump"):
1453
+ extracted_response = model_dump(extracted_response)
1454
+ if isinstance(extracted_response, dict):
1455
+ if extracted_response.get("function_call"):
1456
+ extracted_response["function_call"]["name"] = self._normalize_name(
1457
+ extracted_response["function_call"]["name"]
1458
+ )
1459
+ for tool_call in extracted_response.get("tool_calls") or []:
1460
+ tool_call["function"]["name"] = self._normalize_name(tool_call["function"]["name"])
1461
+ # Remove id and type if they are not present.
1462
+ # This is to make the tool call object compatible with Mistral API.
1463
+ if tool_call.get("id") is None:
1464
+ tool_call.pop("id")
1465
+ if tool_call.get("type") is None:
1466
+ tool_call.pop("type")
1467
+ return extracted_response
1468
+
1469
+ async def a_generate_oai_reply(
1470
+ self,
1471
+ messages: Optional[List[Dict]] = None,
1472
+ sender: Optional[Agent] = None,
1473
+ config: Optional[Any] = None,
1474
+ ) -> Tuple[bool, Union[str, Dict, None]]:
1475
+ """Generate a reply using autogen.oai asynchronously."""
1476
+ iostream = IOStream.get_default()
1477
+
1478
+ def _generate_oai_reply(
1479
+ self, iostream: IOStream, *args: Any, **kwargs: Any
1480
+ ) -> Tuple[bool, Union[str, Dict, None]]:
1481
+ with IOStream.set_default(iostream):
1482
+ return self.generate_oai_reply(*args, **kwargs)
1483
+
1484
+ return await asyncio.get_event_loop().run_in_executor(
1485
+ None,
1486
+ functools.partial(
1487
+ _generate_oai_reply, self=self, iostream=iostream, messages=messages, sender=sender, config=config
1488
+ ),
1489
+ )
1490
+
1491
+ def _generate_code_execution_reply_using_executor(
1492
+ self,
1493
+ messages: Optional[List[Dict]] = None,
1494
+ sender: Optional[Agent] = None,
1495
+ config: Optional[Union[Dict, Literal[False]]] = None,
1496
+ ):
1497
+ """Generate a reply using code executor."""
1498
+ iostream = IOStream.get_default()
1499
+
1500
+ if config is not None:
1501
+ raise ValueError("config is not supported for _generate_code_execution_reply_using_executor.")
1502
+ if self._code_execution_config is False:
1503
+ return False, None
1504
+ if messages is None:
1505
+ messages = self._oai_messages[sender]
1506
+ last_n_messages = self._code_execution_config.get("last_n_messages", "auto")
1507
+
1508
+ if not (isinstance(last_n_messages, (int, float)) and last_n_messages >= 0) and last_n_messages != "auto":
1509
+ raise ValueError("last_n_messages must be either a non-negative integer, or the string 'auto'.")
1510
+
1511
+ num_messages_to_scan = last_n_messages
1512
+ if last_n_messages == "auto":
1513
+ # Find when the agent last spoke
1514
+ num_messages_to_scan = 0
1515
+ for message in reversed(messages):
1516
+ if "role" not in message:
1517
+ break
1518
+ elif message["role"] != "user":
1519
+ break
1520
+ else:
1521
+ num_messages_to_scan += 1
1522
+ num_messages_to_scan = min(len(messages), num_messages_to_scan)
1523
+ messages_to_scan = messages[-num_messages_to_scan:]
1524
+
1525
+ # iterate through the last n messages in reverse
1526
+ # if code blocks are found, execute the code blocks and return the output
1527
+ # if no code blocks are found, continue
1528
+ for message in reversed(messages_to_scan):
1529
+ if not message["content"]:
1530
+ continue
1531
+ code_blocks = self._code_executor.code_extractor.extract_code_blocks(message["content"])
1532
+ if len(code_blocks) == 0:
1533
+ continue
1534
+
1535
+ num_code_blocks = len(code_blocks)
1536
+ if num_code_blocks == 1:
1537
+ iostream.print(
1538
+ colored(
1539
+ f"\n>>>>>>>> EXECUTING CODE BLOCK (inferred language is {code_blocks[0].language})...",
1540
+ "red",
1541
+ ),
1542
+ flush=True,
1543
+ )
1544
+ else:
1545
+ iostream.print(
1546
+ colored(
1547
+ f"\n>>>>>>>> EXECUTING {num_code_blocks} CODE BLOCKS (inferred languages are [{', '.join([x.language for x in code_blocks])}])...",
1548
+ "red",
1549
+ ),
1550
+ flush=True,
1551
+ )
1552
+
1553
+ # found code blocks, execute code.
1554
+ code_result = self._code_executor.execute_code_blocks(code_blocks)
1555
+ exitcode2str = "execution succeeded" if code_result.exit_code == 0 else "execution failed"
1556
+ return True, f"exitcode: {code_result.exit_code} ({exitcode2str})\nCode output: {code_result.output}"
1557
+
1558
+ return False, None
1559
+
1560
+ def generate_code_execution_reply(
1561
+ self,
1562
+ messages: Optional[List[Dict]] = None,
1563
+ sender: Optional[Agent] = None,
1564
+ config: Optional[Union[Dict, Literal[False]]] = None,
1565
+ ):
1566
+ """Generate a reply using code execution."""
1567
+ code_execution_config = config if config is not None else self._code_execution_config
1568
+ if code_execution_config is False:
1569
+ return False, None
1570
+ if messages is None:
1571
+ messages = self._oai_messages[sender]
1572
+ last_n_messages = code_execution_config.pop("last_n_messages", "auto")
1573
+
1574
+ if not (isinstance(last_n_messages, (int, float)) and last_n_messages >= 0) and last_n_messages != "auto":
1575
+ raise ValueError("last_n_messages must be either a non-negative integer, or the string 'auto'.")
1576
+
1577
+ messages_to_scan = last_n_messages
1578
+ if last_n_messages == "auto":
1579
+ # Find when the agent last spoke
1580
+ messages_to_scan = 0
1581
+ for i in range(len(messages)):
1582
+ message = messages[-(i + 1)]
1583
+ if "role" not in message:
1584
+ break
1585
+ elif message["role"] != "user":
1586
+ break
1587
+ else:
1588
+ messages_to_scan += 1
1589
+
1590
+ # iterate through the last n messages in reverse
1591
+ # if code blocks are found, execute the code blocks and return the output
1592
+ # if no code blocks are found, continue
1593
+ for i in range(min(len(messages), messages_to_scan)):
1594
+ message = messages[-(i + 1)]
1595
+ if not message["content"]:
1596
+ continue
1597
+ code_blocks = extract_code(message["content"])
1598
+ if len(code_blocks) == 1 and code_blocks[0][0] == UNKNOWN:
1599
+ continue
1600
+
1601
+ # found code blocks, execute code and push "last_n_messages" back
1602
+ exitcode, logs = self.execute_code_blocks(code_blocks)
1603
+ code_execution_config["last_n_messages"] = last_n_messages
1604
+ exitcode2str = "execution succeeded" if exitcode == 0 else "execution failed"
1605
+ return True, f"exitcode: {exitcode} ({exitcode2str})\nCode output: {logs}"
1606
+
1607
+ # no code blocks are found, push last_n_messages back and return.
1608
+ code_execution_config["last_n_messages"] = last_n_messages
1609
+
1610
+ return False, None
1611
+
1612
+ def generate_function_call_reply(
1613
+ self,
1614
+ messages: Optional[List[Dict]] = None,
1615
+ sender: Optional[Agent] = None,
1616
+ config: Optional[Any] = None,
1617
+ ) -> Tuple[bool, Union[Dict, None]]:
1618
+ """
1619
+ Generate a reply using function call.
1620
+
1621
+ "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
1622
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions
1623
+ """
1624
+ if config is None:
1625
+ config = self
1626
+ if messages is None:
1627
+ messages = self._oai_messages[sender]
1628
+ message = messages[-1]
1629
+ if "function_call" in message and message["function_call"]:
1630
+ func_call = message["function_call"]
1631
+ func = self._function_map.get(func_call.get("name", None), None)
1632
+ if inspect.iscoroutinefunction(func):
1633
+ try:
1634
+ # get the running loop if it was already created
1635
+ loop = asyncio.get_running_loop()
1636
+ close_loop = False
1637
+ except RuntimeError:
1638
+ # create a loop if there is no running loop
1639
+ loop = asyncio.new_event_loop()
1640
+ close_loop = True
1641
+
1642
+ _, func_return = loop.run_until_complete(self.a_execute_function(func_call))
1643
+ if close_loop:
1644
+ loop.close()
1645
+ else:
1646
+ _, func_return = self.execute_function(message["function_call"])
1647
+ return True, func_return
1648
+ return False, None
1649
+
1650
+ async def a_generate_function_call_reply(
1651
+ self,
1652
+ messages: Optional[List[Dict]] = None,
1653
+ sender: Optional[Agent] = None,
1654
+ config: Optional[Any] = None,
1655
+ ) -> Tuple[bool, Union[Dict, None]]:
1656
+ """
1657
+ Generate a reply using async function call.
1658
+
1659
+ "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
1660
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions
1661
+ """
1662
+ if config is None:
1663
+ config = self
1664
+ if messages is None:
1665
+ messages = self._oai_messages[sender]
1666
+ message = messages[-1]
1667
+ if "function_call" in message:
1668
+ func_call = message["function_call"]
1669
+ func_name = func_call.get("name", "")
1670
+ func = self._function_map.get(func_name, None)
1671
+ if func and inspect.iscoroutinefunction(func):
1672
+ _, func_return = await self.a_execute_function(func_call)
1673
+ else:
1674
+ _, func_return = self.execute_function(func_call)
1675
+ return True, func_return
1676
+
1677
+ return False, None
1678
+
1679
+ def _str_for_tool_response(self, tool_response):
1680
+ return str(tool_response.get("content", ""))
1681
+
1682
+ def generate_tool_calls_reply(
1683
+ self,
1684
+ messages: Optional[List[Dict]] = None,
1685
+ sender: Optional[Agent] = None,
1686
+ config: Optional[Any] = None,
1687
+ ) -> Tuple[bool, Union[Dict, None]]:
1688
+ """Generate a reply using tool call."""
1689
+ if config is None:
1690
+ config = self
1691
+ if messages is None:
1692
+ messages = self._oai_messages[sender]
1693
+ message = messages[-1]
1694
+ tool_returns = []
1695
+ for tool_call in message.get("tool_calls", []):
1696
+ function_call = tool_call.get("function", {})
1697
+ func = self._function_map.get(function_call.get("name", None), None)
1698
+ if inspect.iscoroutinefunction(func):
1699
+ try:
1700
+ # get the running loop if it was already created
1701
+ loop = asyncio.get_running_loop()
1702
+ close_loop = False
1703
+ except RuntimeError:
1704
+ # create a loop if there is no running loop
1705
+ loop = asyncio.new_event_loop()
1706
+ close_loop = True
1707
+
1708
+ _, func_return = loop.run_until_complete(self.a_execute_function(function_call))
1709
+ if close_loop:
1710
+ loop.close()
1711
+ else:
1712
+ _, func_return = self.execute_function(function_call)
1713
+ content = func_return.get("content", "")
1714
+ if content is None:
1715
+ content = ""
1716
+ tool_call_id = tool_call.get("id", None)
1717
+ if tool_call_id is not None:
1718
+ tool_call_response = {
1719
+ "tool_call_id": tool_call_id,
1720
+ "role": "tool",
1721
+ "content": content,
1722
+ }
1723
+ else:
1724
+ # Do not include tool_call_id if it is not present.
1725
+ # This is to make the tool call object compatible with Mistral API.
1726
+ tool_call_response = {
1727
+ "role": "tool",
1728
+ "content": content,
1729
+ }
1730
+ tool_returns.append(tool_call_response)
1731
+ if tool_returns:
1732
+ return True, {
1733
+ "role": "tool",
1734
+ "tool_responses": tool_returns,
1735
+ "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),
1736
+ }
1737
+ return False, None
1738
+
1739
+ async def _a_execute_tool_call(self, tool_call):
1740
+ id = tool_call["id"]
1741
+ function_call = tool_call.get("function", {})
1742
+ _, func_return = await self.a_execute_function(function_call)
1743
+ return {
1744
+ "tool_call_id": id,
1745
+ "role": "tool",
1746
+ "content": func_return.get("content", ""),
1747
+ }
1748
+
1749
+ async def a_generate_tool_calls_reply(
1750
+ self,
1751
+ messages: Optional[List[Dict]] = None,
1752
+ sender: Optional[Agent] = None,
1753
+ config: Optional[Any] = None,
1754
+ ) -> Tuple[bool, Union[Dict, None]]:
1755
+ """Generate a reply using async function call."""
1756
+ if config is None:
1757
+ config = self
1758
+ if messages is None:
1759
+ messages = self._oai_messages[sender]
1760
+ message = messages[-1]
1761
+ async_tool_calls = []
1762
+ for tool_call in message.get("tool_calls", []):
1763
+ async_tool_calls.append(self._a_execute_tool_call(tool_call))
1764
+ if async_tool_calls:
1765
+ tool_returns = await asyncio.gather(*async_tool_calls)
1766
+ return True, {
1767
+ "role": "tool",
1768
+ "tool_responses": tool_returns,
1769
+ "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),
1770
+ }
1771
+
1772
+ return False, None
1773
+
1774
+ def check_termination_and_human_reply(
1775
+ self,
1776
+ messages: Optional[List[Dict]] = None,
1777
+ sender: Optional[Agent] = None,
1778
+ config: Optional[Any] = None,
1779
+ ) -> Tuple[bool, Union[str, None]]:
1780
+ """Check if the conversation should be terminated, and if human reply is provided.
1781
+
1782
+ This method checks for conditions that require the conversation to be terminated, such as reaching
1783
+ a maximum number of consecutive auto-replies or encountering a termination message. Additionally,
1784
+ it prompts for and processes human input based on the configured human input mode, which can be
1785
+ 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter
1786
+ for the conversation and prints relevant messages based on the human input received.
1787
+
1788
+ Args:
1789
+ - messages (Optional[List[Dict]]): A list of message dictionaries, representing the conversation history.
1790
+ - sender (Optional[Agent]): The agent object representing the sender of the message.
1791
+ - config (Optional[Any]): Configuration object, defaults to the current instance if not provided.
1792
+
1793
+ Returns:
1794
+ - Tuple[bool, Union[str, Dict, None]]: A tuple containing a boolean indicating if the conversation
1795
+ should be terminated, and a human reply which can be a string, a dictionary, or None.
1796
+ """
1797
+ iostream = IOStream.get_default()
1798
+
1799
+ if config is None:
1800
+ config = self
1801
+ if messages is None:
1802
+ messages = self._oai_messages[sender] if sender else []
1803
+ message = messages[-1]
1804
+ reply = ""
1805
+ no_human_input_msg = ""
1806
+ sender_name = "the sender" if sender is None else sender.name
1807
+ if self.human_input_mode == "ALWAYS":
1808
+ reply = self.get_human_input(
1809
+ f"Replying as {self.name}. Provide feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: "
1810
+ )
1811
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1812
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1813
+ reply = reply if reply or not self._is_termination_msg(message) else "exit"
1814
+ else:
1815
+ if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:
1816
+ if self.human_input_mode == "NEVER":
1817
+ reply = "exit"
1818
+ else:
1819
+ # self.human_input_mode == "TERMINATE":
1820
+ terminate = self._is_termination_msg(message)
1821
+ reply = self.get_human_input(
1822
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
1823
+ if terminate
1824
+ else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "
1825
+ )
1826
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1827
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1828
+ reply = reply if reply or not terminate else "exit"
1829
+ elif self._is_termination_msg(message):
1830
+ if self.human_input_mode == "NEVER":
1831
+ reply = "exit"
1832
+ else:
1833
+ # self.human_input_mode == "TERMINATE":
1834
+ reply = self.get_human_input(
1835
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
1836
+ )
1837
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1838
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1839
+ reply = reply or "exit"
1840
+
1841
+ # print the no_human_input_msg
1842
+ if no_human_input_msg:
1843
+ iostream.print(colored(f"\n>>>>>>>> {no_human_input_msg}", "red"), flush=True)
1844
+
1845
+ # stop the conversation
1846
+ if reply == "exit":
1847
+ # reset the consecutive_auto_reply_counter
1848
+ self._consecutive_auto_reply_counter[sender] = 0
1849
+ return True, None
1850
+
1851
+ # send the human reply
1852
+ if reply or self._max_consecutive_auto_reply_dict[sender] == 0:
1853
+ # reset the consecutive_auto_reply_counter
1854
+ self._consecutive_auto_reply_counter[sender] = 0
1855
+ # User provided a custom response, return function and tool failures indicating user interruption
1856
+ tool_returns = []
1857
+ if message.get("function_call", False):
1858
+ tool_returns.append(
1859
+ {
1860
+ "role": "function",
1861
+ "name": message["function_call"].get("name", ""),
1862
+ "content": "USER INTERRUPTED",
1863
+ }
1864
+ )
1865
+
1866
+ if message.get("tool_calls", False):
1867
+ tool_returns.extend(
1868
+ [
1869
+ {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}
1870
+ for tool_call in message["tool_calls"]
1871
+ ]
1872
+ )
1873
+
1874
+ response = {"role": "user", "content": reply}
1875
+ if tool_returns:
1876
+ response["tool_responses"] = tool_returns
1877
+
1878
+ return True, response
1879
+
1880
+ # increment the consecutive_auto_reply_counter
1881
+ self._consecutive_auto_reply_counter[sender] += 1
1882
+ if self.human_input_mode != "NEVER":
1883
+ iostream.print(colored("\n>>>>>>>> USING AUTO REPLY...", "red"), flush=True)
1884
+
1885
+ return False, None
1886
+
1887
+ async def a_check_termination_and_human_reply(
1888
+ self,
1889
+ messages: Optional[List[Dict]] = None,
1890
+ sender: Optional[Agent] = None,
1891
+ config: Optional[Any] = None,
1892
+ ) -> Tuple[bool, Union[str, None]]:
1893
+ """(async) Check if the conversation should be terminated, and if human reply is provided.
1894
+
1895
+ This method checks for conditions that require the conversation to be terminated, such as reaching
1896
+ a maximum number of consecutive auto-replies or encountering a termination message. Additionally,
1897
+ it prompts for and processes human input based on the configured human input mode, which can be
1898
+ 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter
1899
+ for the conversation and prints relevant messages based on the human input received.
1900
+
1901
+ Args:
1902
+ - messages (Optional[List[Dict]]): A list of message dictionaries, representing the conversation history.
1903
+ - sender (Optional[Agent]): The agent object representing the sender of the message.
1904
+ - config (Optional[Any]): Configuration object, defaults to the current instance if not provided.
1905
+
1906
+ Returns:
1907
+ - Tuple[bool, Union[str, Dict, None]]: A tuple containing a boolean indicating if the conversation
1908
+ should be terminated, and a human reply which can be a string, a dictionary, or None.
1909
+ """
1910
+ iostream = IOStream.get_default()
1911
+
1912
+ if config is None:
1913
+ config = self
1914
+ if messages is None:
1915
+ messages = self._oai_messages[sender] if sender else []
1916
+ message = messages[-1] if messages else {}
1917
+ reply = ""
1918
+ no_human_input_msg = ""
1919
+ sender_name = "the sender" if sender is None else sender.name
1920
+ if self.human_input_mode == "ALWAYS":
1921
+ reply = await self.a_get_human_input(
1922
+ f"Replying as {self.name}. Provide feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to end the conversation: "
1923
+ )
1924
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1925
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1926
+ reply = reply if reply or not self._is_termination_msg(message) else "exit"
1927
+ else:
1928
+ if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:
1929
+ if self.human_input_mode == "NEVER":
1930
+ reply = "exit"
1931
+ else:
1932
+ # self.human_input_mode == "TERMINATE":
1933
+ terminate = self._is_termination_msg(message)
1934
+ reply = await self.a_get_human_input(
1935
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
1936
+ if terminate
1937
+ else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "
1938
+ )
1939
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1940
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1941
+ reply = reply if reply or not terminate else "exit"
1942
+ elif self._is_termination_msg(message):
1943
+ if self.human_input_mode == "NEVER":
1944
+ reply = "exit"
1945
+ else:
1946
+ # self.human_input_mode == "TERMINATE":
1947
+ reply = await self.a_get_human_input(
1948
+ f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "
1949
+ )
1950
+ no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""
1951
+ # if the human input is empty, and the message is a termination message, then we will terminate the conversation
1952
+ reply = reply or "exit"
1953
+
1954
+ # print the no_human_input_msg
1955
+ if no_human_input_msg:
1956
+ iostream.print(colored(f"\n>>>>>>>> {no_human_input_msg}", "red"), flush=True)
1957
+
1958
+ # stop the conversation
1959
+ if reply == "exit":
1960
+ # reset the consecutive_auto_reply_counter
1961
+ self._consecutive_auto_reply_counter[sender] = 0
1962
+ return True, None
1963
+
1964
+ # send the human reply
1965
+ if reply or self._max_consecutive_auto_reply_dict[sender] == 0:
1966
+ # User provided a custom response, return function and tool results indicating user interruption
1967
+ # reset the consecutive_auto_reply_counter
1968
+ self._consecutive_auto_reply_counter[sender] = 0
1969
+ tool_returns = []
1970
+ if message.get("function_call", False):
1971
+ tool_returns.append(
1972
+ {
1973
+ "role": "function",
1974
+ "name": message["function_call"].get("name", ""),
1975
+ "content": "USER INTERRUPTED",
1976
+ }
1977
+ )
1978
+
1979
+ if message.get("tool_calls", False):
1980
+ tool_returns.extend(
1981
+ [
1982
+ {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}
1983
+ for tool_call in message["tool_calls"]
1984
+ ]
1985
+ )
1986
+
1987
+ response = {"role": "user", "content": reply}
1988
+ if tool_returns:
1989
+ response["tool_responses"] = tool_returns
1990
+
1991
+ return True, response
1992
+
1993
+ # increment the consecutive_auto_reply_counter
1994
+ self._consecutive_auto_reply_counter[sender] += 1
1995
+ if self.human_input_mode != "NEVER":
1996
+ iostream.print(colored("\n>>>>>>>> USING AUTO REPLY...", "red"), flush=True)
1997
+
1998
+ return False, None
1999
+
2000
+ def generate_reply(
2001
+ self,
2002
+ messages: Optional[List[Dict[str, Any]]] = None,
2003
+ sender: Optional["Agent"] = None,
2004
+ **kwargs: Any,
2005
+ ) -> Union[str, Dict, None]:
2006
+ """Reply based on the conversation history and the sender.
2007
+
2008
+ Either messages or sender must be provided.
2009
+ Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.
2010
+ Use registered auto reply functions to generate replies.
2011
+ By default, the following functions are checked in order:
2012
+ 1. check_termination_and_human_reply
2013
+ 2. generate_function_call_reply (deprecated in favor of tool_calls)
2014
+ 3. generate_tool_calls_reply
2015
+ 4. generate_code_execution_reply
2016
+ 5. generate_oai_reply
2017
+ Every function returns a tuple (final, reply).
2018
+ When a function returns final=False, the next function will be checked.
2019
+ So by default, termination and human reply will be checked first.
2020
+ If not terminating and human reply is skipped, execute function or code and return the result.
2021
+ AI replies are generated only when no code execution is performed.
2022
+
2023
+ Args:
2024
+ messages: a list of messages in the conversation history.
2025
+ sender: sender of an Agent instance.
2026
+
2027
+ Additional keyword arguments:
2028
+ exclude (List[Callable]): a list of reply functions to be excluded.
2029
+
2030
+ Returns:
2031
+ str or dict or None: reply. None if no reply is generated.
2032
+ """
2033
+ if all((messages is None, sender is None)):
2034
+ error_msg = f"Either {messages=} or {sender=} must be provided."
2035
+ logger.error(error_msg)
2036
+ raise AssertionError(error_msg)
2037
+
2038
+ if messages is None:
2039
+ messages = self._oai_messages[sender]
2040
+
2041
+ # Call the hookable method that gives registered hooks a chance to process the last message.
2042
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2043
+ messages = self.process_last_received_message(messages)
2044
+
2045
+ # Call the hookable method that gives registered hooks a chance to process all messages.
2046
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2047
+ messages = self.process_all_messages_before_reply(messages)
2048
+
2049
+ for reply_func_tuple in self._reply_func_list:
2050
+ reply_func = reply_func_tuple["reply_func"]
2051
+ if "exclude" in kwargs and reply_func in kwargs["exclude"]:
2052
+ continue
2053
+ if inspect.iscoroutinefunction(reply_func):
2054
+ continue
2055
+ if self._match_trigger(reply_func_tuple["trigger"], sender):
2056
+ final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
2057
+ if logging_enabled():
2058
+ log_event(
2059
+ self,
2060
+ "reply_func_executed",
2061
+ reply_func_module=reply_func.__module__,
2062
+ reply_func_name=reply_func.__name__,
2063
+ final=final,
2064
+ reply=reply,
2065
+ )
2066
+ if final:
2067
+ return reply
2068
+ return self._default_auto_reply
2069
+
2070
+ async def a_generate_reply(
2071
+ self,
2072
+ messages: Optional[List[Dict[str, Any]]] = None,
2073
+ sender: Optional["Agent"] = None,
2074
+ **kwargs: Any,
2075
+ ) -> Union[str, Dict[str, Any], None]:
2076
+ """(async) Reply based on the conversation history and the sender.
2077
+
2078
+ Either messages or sender must be provided.
2079
+ Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.
2080
+ Use registered auto reply functions to generate replies.
2081
+ By default, the following functions are checked in order:
2082
+ 1. check_termination_and_human_reply
2083
+ 2. generate_function_call_reply
2084
+ 3. generate_tool_calls_reply
2085
+ 4. generate_code_execution_reply
2086
+ 5. generate_oai_reply
2087
+ Every function returns a tuple (final, reply).
2088
+ When a function returns final=False, the next function will be checked.
2089
+ So by default, termination and human reply will be checked first.
2090
+ If not terminating and human reply is skipped, execute function or code and return the result.
2091
+ AI replies are generated only when no code execution is performed.
2092
+
2093
+ Args:
2094
+ messages: a list of messages in the conversation history.
2095
+ sender: sender of an Agent instance.
2096
+
2097
+ Additional keyword arguments:
2098
+ exclude (List[Callable]): a list of reply functions to be excluded.
2099
+
2100
+ Returns:
2101
+ str or dict or None: reply. None if no reply is generated.
2102
+ """
2103
+ if all((messages is None, sender is None)):
2104
+ error_msg = f"Either {messages=} or {sender=} must be provided."
2105
+ logger.error(error_msg)
2106
+ raise AssertionError(error_msg)
2107
+
2108
+ if messages is None:
2109
+ messages = self._oai_messages[sender]
2110
+
2111
+ # Call the hookable method that gives registered hooks a chance to process all messages.
2112
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2113
+ messages = self.process_all_messages_before_reply(messages)
2114
+
2115
+ # Call the hookable method that gives registered hooks a chance to process the last message.
2116
+ # Message modifications do not affect the incoming messages or self._oai_messages.
2117
+ messages = self.process_last_received_message(messages)
2118
+
2119
+ for reply_func_tuple in self._reply_func_list:
2120
+ reply_func = reply_func_tuple["reply_func"]
2121
+ if "exclude" in kwargs and reply_func in kwargs["exclude"]:
2122
+ continue
2123
+
2124
+ if self._match_trigger(reply_func_tuple["trigger"], sender):
2125
+ if inspect.iscoroutinefunction(reply_func):
2126
+ final, reply = await reply_func(
2127
+ self, messages=messages, sender=sender, config=reply_func_tuple["config"]
2128
+ )
2129
+ else:
2130
+ final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])
2131
+ if final:
2132
+ return reply
2133
+ return self._default_auto_reply
2134
+
2135
+ def _match_trigger(self, trigger: Union[None, str, type, Agent, Callable, List], sender: Optional[Agent]) -> bool:
2136
+ """Check if the sender matches the trigger.
2137
+
2138
+ Args:
2139
+ - trigger (Union[None, str, type, Agent, Callable, List]): The condition to match against the sender.
2140
+ Can be `None`, string, type, `Agent` instance, callable, or a list of these.
2141
+ - sender (Agent): The sender object or type to be matched against the trigger.
2142
+
2143
+ Returns:
2144
+ - bool: Returns `True` if the sender matches the trigger, otherwise `False`.
2145
+
2146
+ Raises:
2147
+ - ValueError: If the trigger type is unsupported.
2148
+ """
2149
+ if trigger is None:
2150
+ return sender is None
2151
+ elif isinstance(trigger, str):
2152
+ if sender is None:
2153
+ raise SenderRequired()
2154
+ return trigger == sender.name
2155
+ elif isinstance(trigger, type):
2156
+ return isinstance(sender, trigger)
2157
+ elif isinstance(trigger, Agent):
2158
+ # return True if the sender is the same type (class) as the trigger
2159
+ return trigger == sender
2160
+ elif isinstance(trigger, Callable):
2161
+ rst = trigger(sender)
2162
+ assert isinstance(rst, bool), f"trigger {trigger} must return a boolean value."
2163
+ return rst
2164
+ elif isinstance(trigger, list):
2165
+ return any(self._match_trigger(t, sender) for t in trigger)
2166
+ else:
2167
+ raise ValueError(f"Unsupported trigger type: {type(trigger)}")
2168
+
2169
+ def get_human_input(self, prompt: str) -> str:
2170
+ """Get human input.
2171
+
2172
+ Override this method to customize the way to get human input.
2173
+
2174
+ Args:
2175
+ prompt (str): prompt for the human input.
2176
+
2177
+ Returns:
2178
+ str: human input.
2179
+ """
2180
+ iostream = IOStream.get_default()
2181
+
2182
+ reply = iostream.input(prompt)
2183
+ self._human_input.append(reply)
2184
+ return reply
2185
+
2186
+ async def a_get_human_input(self, prompt: str) -> str:
2187
+ """(Async) Get human input.
2188
+
2189
+ Override this method to customize the way to get human input.
2190
+
2191
+ Args:
2192
+ prompt (str): prompt for the human input.
2193
+
2194
+ Returns:
2195
+ str: human input.
2196
+ """
2197
+ loop = asyncio.get_running_loop()
2198
+ reply = await loop.run_in_executor(None, functools.partial(self.get_human_input, prompt))
2199
+ return reply
2200
+
2201
+ def run_code(self, code, **kwargs):
2202
+ """Run the code and return the result.
2203
+
2204
+ Override this function to modify the way to run the code.
2205
+ Args:
2206
+ code (str): the code to be executed.
2207
+ **kwargs: other keyword arguments.
2208
+
2209
+ Returns:
2210
+ A tuple of (exitcode, logs, image).
2211
+ exitcode (int): the exit code of the code execution.
2212
+ logs (str): the logs of the code execution.
2213
+ image (str or None): the docker image used for the code execution.
2214
+ """
2215
+ return execute_code(code, **kwargs)
2216
+
2217
+ def execute_code_blocks(self, code_blocks):
2218
+ """Execute the code blocks and return the result."""
2219
+ iostream = IOStream.get_default()
2220
+
2221
+ logs_all = ""
2222
+ for i, code_block in enumerate(code_blocks):
2223
+ lang, code = code_block
2224
+ if not lang:
2225
+ lang = infer_lang(code)
2226
+ iostream.print(
2227
+ colored(
2228
+ f"\n>>>>>>>> EXECUTING CODE BLOCK {i} (inferred language is {lang})...",
2229
+ "red",
2230
+ ),
2231
+ flush=True,
2232
+ )
2233
+ if lang in ["bash", "shell", "sh"]:
2234
+ exitcode, logs, image = self.run_code(code, lang=lang, **self._code_execution_config)
2235
+ elif lang in PYTHON_VARIANTS:
2236
+ if code.startswith("# filename: "):
2237
+ filename = code[11 : code.find("\n")].strip()
2238
+ else:
2239
+ filename = None
2240
+ exitcode, logs, image = self.run_code(
2241
+ code,
2242
+ lang="python",
2243
+ filename=filename,
2244
+ **self._code_execution_config,
2245
+ )
2246
+ else:
2247
+ # In case the language is not supported, we return an error message.
2248
+ exitcode, logs, image = (
2249
+ 1,
2250
+ f"unknown language {lang}",
2251
+ None,
2252
+ )
2253
+ # raise NotImplementedError
2254
+ if image is not None:
2255
+ self._code_execution_config["use_docker"] = image
2256
+ logs_all += "\n" + logs
2257
+ if exitcode != 0:
2258
+ return exitcode, logs_all
2259
+ return exitcode, logs_all
2260
+
2261
+ @staticmethod
2262
+ def _format_json_str(jstr):
2263
+ """Remove newlines outside of quotes, and handle JSON escape sequences.
2264
+
2265
+ 1. this function removes the newline in the query outside of quotes otherwise json.loads(s) will fail.
2266
+ Ex 1:
2267
+ "{\n"tool": "python",\n"query": "print('hello')\nprint('world')"\n}" -> "{"tool": "python","query": "print('hello')\nprint('world')"}"
2268
+ Ex 2:
2269
+ "{\n \"location\": \"Boston, MA\"\n}" -> "{"location": "Boston, MA"}"
2270
+
2271
+ 2. this function also handles JSON escape sequences inside quotes.
2272
+ Ex 1:
2273
+ '{"args": "a\na\na\ta"}' -> '{"args": "a\\na\\na\\ta"}'
2274
+ """
2275
+ result = []
2276
+ inside_quotes = False
2277
+ last_char = " "
2278
+ for char in jstr:
2279
+ if last_char != "\\" and char == '"':
2280
+ inside_quotes = not inside_quotes
2281
+ last_char = char
2282
+ if not inside_quotes and char == "\n":
2283
+ continue
2284
+ if inside_quotes and char == "\n":
2285
+ char = "\\n"
2286
+ if inside_quotes and char == "\t":
2287
+ char = "\\t"
2288
+ result.append(char)
2289
+ return "".join(result)
2290
+
2291
+ def execute_function(self, func_call, verbose: bool = False) -> Tuple[bool, Dict[str, str]]:
2292
+ """Execute a function call and return the result.
2293
+
2294
+ Override this function to modify the way to execute function and tool calls.
2295
+
2296
+ Args:
2297
+ func_call: a dictionary extracted from openai message at "function_call" or "tool_calls" with keys "name" and "arguments".
2298
+
2299
+ Returns:
2300
+ A tuple of (is_exec_success, result_dict).
2301
+ is_exec_success (boolean): whether the execution is successful.
2302
+ result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".
2303
+
2304
+ "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
2305
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
2306
+ """
2307
+ iostream = IOStream.get_default()
2308
+
2309
+ func_name = func_call.get("name", "")
2310
+ func = self._function_map.get(func_name, None)
2311
+
2312
+ is_exec_success = False
2313
+ if func is not None:
2314
+ # Extract arguments from a json-like string and put it into a dict.
2315
+ input_string = self._format_json_str(func_call.get("arguments", "{}"))
2316
+ try:
2317
+ arguments = json.loads(input_string)
2318
+ except json.JSONDecodeError as e:
2319
+ arguments = None
2320
+ content = f"Error: {e}\n The argument must be in JSON format."
2321
+
2322
+ # Try to execute the function
2323
+ if arguments is not None:
2324
+ iostream.print(
2325
+ colored(f"\n>>>>>>>> EXECUTING FUNCTION {func_name}...", "magenta"),
2326
+ flush=True,
2327
+ )
2328
+ try:
2329
+ content = func(**arguments)
2330
+ is_exec_success = True
2331
+ except Exception as e:
2332
+ content = f"Error: {e}"
2333
+ else:
2334
+ content = f"Error: Function {func_name} not found."
2335
+
2336
+ if verbose:
2337
+ iostream.print(
2338
+ colored(f"\nInput arguments: {arguments}\nOutput:\n{content}", "magenta"),
2339
+ flush=True,
2340
+ )
2341
+
2342
+ return is_exec_success, {
2343
+ "name": func_name,
2344
+ "role": "function",
2345
+ "content": str(content),
2346
+ }
2347
+
2348
+ async def a_execute_function(self, func_call):
2349
+ """Execute an async function call and return the result.
2350
+
2351
+ Override this function to modify the way async functions and tools are executed.
2352
+
2353
+ Args:
2354
+ func_call: a dictionary extracted from openai message at key "function_call" or "tool_calls" with keys "name" and "arguments".
2355
+
2356
+ Returns:
2357
+ A tuple of (is_exec_success, result_dict).
2358
+ is_exec_success (boolean): whether the execution is successful.
2359
+ result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".
2360
+
2361
+ "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
2362
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
2363
+ """
2364
+ iostream = IOStream.get_default()
2365
+
2366
+ func_name = func_call.get("name", "")
2367
+ func = self._function_map.get(func_name, None)
2368
+
2369
+ is_exec_success = False
2370
+ if func is not None:
2371
+ # Extract arguments from a json-like string and put it into a dict.
2372
+ input_string = self._format_json_str(func_call.get("arguments", "{}"))
2373
+ try:
2374
+ arguments = json.loads(input_string)
2375
+ except json.JSONDecodeError as e:
2376
+ arguments = None
2377
+ content = f"Error: {e}\n The argument must be in JSON format."
2378
+
2379
+ # Try to execute the function
2380
+ if arguments is not None:
2381
+ iostream.print(
2382
+ colored(f"\n>>>>>>>> EXECUTING ASYNC FUNCTION {func_name}...", "magenta"),
2383
+ flush=True,
2384
+ )
2385
+ try:
2386
+ if inspect.iscoroutinefunction(func):
2387
+ content = await func(**arguments)
2388
+ else:
2389
+ # Fallback to sync function if the function is not async
2390
+ content = func(**arguments)
2391
+ is_exec_success = True
2392
+ except Exception as e:
2393
+ content = f"Error: {e}"
2394
+ else:
2395
+ content = f"Error: Function {func_name} not found."
2396
+
2397
+ return is_exec_success, {
2398
+ "name": func_name,
2399
+ "role": "function",
2400
+ "content": str(content),
2401
+ }
2402
+
2403
+ def generate_init_message(self, message: Union[Dict, str, None], **kwargs) -> Union[str, Dict]:
2404
+ """Generate the initial message for the agent.
2405
+ If message is None, input() will be called to get the initial message.
2406
+
2407
+ Args:
2408
+ message (str or None): the message to be processed.
2409
+ **kwargs: any additional information. It has the following reserved fields:
2410
+ "carryover": a string or a list of string to specify the carryover information to be passed to this chat. It can be a string or a list of string.
2411
+ If provided, we will combine this carryover with the "message" content when generating the initial chat
2412
+ message.
2413
+ Returns:
2414
+ str or dict: the processed message.
2415
+ """
2416
+ if message is None:
2417
+ message = self.get_human_input(">")
2418
+
2419
+ return self._handle_carryover(message, kwargs)
2420
+
2421
+ def _handle_carryover(self, message: Union[str, Dict], kwargs: dict) -> Union[str, Dict]:
2422
+ if not kwargs.get("carryover"):
2423
+ return message
2424
+
2425
+ if isinstance(message, str):
2426
+ return self._process_carryover(message, kwargs)
2427
+
2428
+ elif isinstance(message, dict):
2429
+ if isinstance(message.get("content"), str):
2430
+ # Makes sure the original message is not mutated
2431
+ message = message.copy()
2432
+ message["content"] = self._process_carryover(message["content"], kwargs)
2433
+ elif isinstance(message.get("content"), list):
2434
+ # Makes sure the original message is not mutated
2435
+ message = message.copy()
2436
+ message["content"] = self._process_multimodal_carryover(message["content"], kwargs)
2437
+ else:
2438
+ raise InvalidCarryOverType("Carryover should be a string or a list of strings.")
2439
+
2440
+ return message
2441
+
2442
+ def _process_carryover(self, content: str, kwargs: dict) -> str:
2443
+ # Makes sure there's a carryover
2444
+ if not kwargs.get("carryover"):
2445
+ return content
2446
+
2447
+ # if carryover is string
2448
+ if isinstance(kwargs["carryover"], str):
2449
+ content += "\nContext: \n" + kwargs["carryover"]
2450
+ elif isinstance(kwargs["carryover"], list):
2451
+ content += "\nContext: \n" + ("\n").join([_post_process_carryover_item(t) for t in kwargs["carryover"]])
2452
+ else:
2453
+ raise InvalidCarryOverType(
2454
+ "Carryover should be a string or a list of strings. Not adding carryover to the message."
2455
+ )
2456
+ return content
2457
+
2458
+ def _process_multimodal_carryover(self, content: List[Dict], kwargs: dict) -> List[Dict]:
2459
+ """Prepends the context to a multimodal message."""
2460
+ # Makes sure there's a carryover
2461
+ if not kwargs.get("carryover"):
2462
+ return content
2463
+
2464
+ return [{"type": "text", "text": self._process_carryover("", kwargs)}] + content
2465
+
2466
+ async def a_generate_init_message(self, message: Union[Dict, str, None], **kwargs) -> Union[str, Dict]:
2467
+ """Generate the initial message for the agent.
2468
+ If message is None, input() will be called to get the initial message.
2469
+
2470
+ Args:
2471
+ Please refer to `generate_init_message` for the description of the arguments.
2472
+
2473
+ Returns:
2474
+ str or dict: the processed message.
2475
+ """
2476
+ if message is None:
2477
+ message = await self.a_get_human_input(">")
2478
+
2479
+ return self._handle_carryover(message, kwargs)
2480
+
2481
+ def register_function(self, function_map: Dict[str, Union[Callable, None]]):
2482
+ """Register functions to the agent.
2483
+
2484
+ Args:
2485
+ function_map: a dictionary mapping function names to functions. if function_map[name] is None, the function will be removed from the function_map.
2486
+ """
2487
+ for name, func in function_map.items():
2488
+ self._assert_valid_name(name)
2489
+ if func is None and name not in self._function_map.keys():
2490
+ warnings.warn(f"The function {name} to remove doesn't exist", name)
2491
+ if name in self._function_map:
2492
+ warnings.warn(f"Function '{name}' is being overridden.", UserWarning)
2493
+ self._function_map.update(function_map)
2494
+ self._function_map = {k: v for k, v in self._function_map.items() if v is not None}
2495
+
2496
+ def update_function_signature(self, func_sig: Union[str, Dict], is_remove: None):
2497
+ """update a function_signature in the LLM configuration for function_call.
2498
+
2499
+ Args:
2500
+ func_sig (str or dict): description/name of the function to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat/create-functions
2501
+ is_remove: whether removing the function from llm_config with name 'func_sig'
2502
+
2503
+ Deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)
2504
+ See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call
2505
+ """
2506
+
2507
+ if not isinstance(self.llm_config, dict):
2508
+ error_msg = "To update a function signature, agent must have an llm_config"
2509
+ logger.error(error_msg)
2510
+ raise AssertionError(error_msg)
2511
+
2512
+ if is_remove:
2513
+ if "functions" not in self.llm_config.keys():
2514
+ error_msg = "The agent config doesn't have function {name}.".format(name=func_sig)
2515
+ logger.error(error_msg)
2516
+ raise AssertionError(error_msg)
2517
+ else:
2518
+ self.llm_config["functions"] = [
2519
+ func for func in self.llm_config["functions"] if func["name"] != func_sig
2520
+ ]
2521
+ else:
2522
+ if not isinstance(func_sig, dict):
2523
+ raise ValueError(
2524
+ f"The function signature must be of the type dict. Received function signature type {type(func_sig)}"
2525
+ )
2526
+
2527
+ self._assert_valid_name(func_sig["name"])
2528
+ if "functions" in self.llm_config.keys():
2529
+ if any(func["name"] == func_sig["name"] for func in self.llm_config["functions"]):
2530
+ warnings.warn(f"Function '{func_sig['name']}' is being overridden.", UserWarning)
2531
+
2532
+ self.llm_config["functions"] = [
2533
+ func for func in self.llm_config["functions"] if func.get("name") != func_sig["name"]
2534
+ ] + [func_sig]
2535
+ else:
2536
+ self.llm_config["functions"] = [func_sig]
2537
+
2538
+ if len(self.llm_config["functions"]) == 0:
2539
+ del self.llm_config["functions"]
2540
+
2541
+ self.client = OpenAIWrapper(**self.llm_config)
2542
+
2543
+ def update_tool_signature(self, tool_sig: Union[str, Dict], is_remove: None):
2544
+ """update a tool_signature in the LLM configuration for tool_call.
2545
+
2546
+ Args:
2547
+ tool_sig (str or dict): description/name of the tool to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools
2548
+ is_remove: whether removing the tool from llm_config with name 'tool_sig'
2549
+ """
2550
+
2551
+ if not self.llm_config:
2552
+ error_msg = "To update a tool signature, agent must have an llm_config"
2553
+ logger.error(error_msg)
2554
+ raise AssertionError(error_msg)
2555
+
2556
+ if is_remove:
2557
+ if "tools" not in self.llm_config.keys():
2558
+ error_msg = "The agent config doesn't have tool {name}.".format(name=tool_sig)
2559
+ logger.error(error_msg)
2560
+ raise AssertionError(error_msg)
2561
+ else:
2562
+ self.llm_config["tools"] = [
2563
+ tool for tool in self.llm_config["tools"] if tool["function"]["name"] != tool_sig
2564
+ ]
2565
+ else:
2566
+ if not isinstance(tool_sig, dict):
2567
+ raise ValueError(
2568
+ f"The tool signature must be of the type dict. Received tool signature type {type(tool_sig)}"
2569
+ )
2570
+ self._assert_valid_name(tool_sig["function"]["name"])
2571
+ if "tools" in self.llm_config:
2572
+ if any(tool["function"]["name"] == tool_sig["function"]["name"] for tool in self.llm_config["tools"]):
2573
+ warnings.warn(f"Function '{tool_sig['function']['name']}' is being overridden.", UserWarning)
2574
+ self.llm_config["tools"] = [
2575
+ tool
2576
+ for tool in self.llm_config["tools"]
2577
+ if tool.get("function", {}).get("name") != tool_sig["function"]["name"]
2578
+ ] + [tool_sig]
2579
+ else:
2580
+ self.llm_config["tools"] = [tool_sig]
2581
+
2582
+ if len(self.llm_config["tools"]) == 0:
2583
+ del self.llm_config["tools"]
2584
+
2585
+ self.client = OpenAIWrapper(**self.llm_config)
2586
+
2587
+ def can_execute_function(self, name: Union[List[str], str]) -> bool:
2588
+ """Whether the agent can execute the function."""
2589
+ names = name if isinstance(name, list) else [name]
2590
+ return all([n in self._function_map for n in names])
2591
+
2592
+ @property
2593
+ def function_map(self) -> Dict[str, Callable]:
2594
+ """Return the function map."""
2595
+ return self._function_map
2596
+
2597
+ def _wrap_function(self, func: F) -> F:
2598
+ """Wrap the function to dump the return value to json.
2599
+
2600
+ Handles both sync and async functions.
2601
+
2602
+ Args:
2603
+ func: the function to be wrapped.
2604
+
2605
+ Returns:
2606
+ The wrapped function.
2607
+ """
2608
+
2609
+ @load_basemodels_if_needed
2610
+ @functools.wraps(func)
2611
+ def _wrapped_func(*args, **kwargs):
2612
+ retval = func(*args, **kwargs)
2613
+ if logging_enabled():
2614
+ log_function_use(self, func, kwargs, retval)
2615
+ return serialize_to_str(retval)
2616
+
2617
+ @load_basemodels_if_needed
2618
+ @functools.wraps(func)
2619
+ async def _a_wrapped_func(*args, **kwargs):
2620
+ retval = await func(*args, **kwargs)
2621
+ if logging_enabled():
2622
+ log_function_use(self, func, kwargs, retval)
2623
+ return serialize_to_str(retval)
2624
+
2625
+ wrapped_func = _a_wrapped_func if inspect.iscoroutinefunction(func) else _wrapped_func
2626
+
2627
+ # needed for testing
2628
+ wrapped_func._origin = func
2629
+
2630
+ return wrapped_func
2631
+
2632
+ def register_for_llm(
2633
+ self,
2634
+ *,
2635
+ name: Optional[str] = None,
2636
+ description: Optional[str] = None,
2637
+ api_style: Literal["function", "tool"] = "tool",
2638
+ ) -> Callable[[F], F]:
2639
+ """Decorator factory for registering a function to be used by an agent.
2640
+
2641
+ It's return value is used to decorate a function to be registered to the agent. The function uses type hints to
2642
+ specify the arguments and return type. The function name is used as the default name for the function,
2643
+ but a custom name can be provided. The function description is used to describe the function in the
2644
+ agent's configuration.
2645
+
2646
+ Args:
2647
+ name (optional(str)): name of the function. If None, the function name will be used (default: None).
2648
+ description (optional(str)): description of the function (default: None). It is mandatory
2649
+ for the initial decorator, but the following ones can omit it.
2650
+ api_style: (literal): the API style for function call.
2651
+ For Azure OpenAI API, use version 2023-12-01-preview or later.
2652
+ `"function"` style will be deprecated. For earlier version use
2653
+ `"function"` if `"tool"` doesn't work.
2654
+ See [Azure OpenAI documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/function-calling?tabs=python) for details.
2655
+
2656
+ Returns:
2657
+ The decorator for registering a function to be used by an agent.
2658
+
2659
+ Examples:
2660
+ ```
2661
+ @user_proxy.register_for_execution()
2662
+ @agent2.register_for_llm()
2663
+ @agent1.register_for_llm(description="This is a very useful function")
2664
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
2665
+ return a + str(b * c)
2666
+ ```
2667
+
2668
+ For Azure OpenAI versions prior to 2023-12-01-preview, set `api_style`
2669
+ to `"function"` if `"tool"` doesn't work:
2670
+ ```
2671
+ @agent2.register_for_llm(api_style="function")
2672
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
2673
+ return a + str(b * c)
2674
+ ```
2675
+
2676
+ """
2677
+
2678
+ def _decorator(func: F) -> F:
2679
+ """Decorator for registering a function to be used by an agent.
2680
+
2681
+ Args:
2682
+ func: the function to be registered.
2683
+
2684
+ Returns:
2685
+ The function to be registered, with the _description attribute set to the function description.
2686
+
2687
+ Raises:
2688
+ ValueError: if the function description is not provided and not propagated by a previous decorator.
2689
+ RuntimeError: if the LLM config is not set up before registering a function.
2690
+
2691
+ """
2692
+ # name can be overwritten by the parameter, by default it is the same as function name
2693
+ if name:
2694
+ func._name = name
2695
+ elif not hasattr(func, "_name"):
2696
+ func._name = func.__name__
2697
+
2698
+ # description is propagated from the previous decorator, but it is mandatory for the first one
2699
+ if description:
2700
+ func._description = description
2701
+ else:
2702
+ if not hasattr(func, "_description"):
2703
+ raise ValueError("Function description is required, none found.")
2704
+
2705
+ # get JSON schema for the function
2706
+ f = get_function_schema(func, name=func._name, description=func._description)
2707
+
2708
+ # register the function to the agent if there is LLM config, raise an exception otherwise
2709
+ if self.llm_config is None:
2710
+ raise RuntimeError("LLM config must be setup before registering a function for LLM.")
2711
+
2712
+ if api_style == "function":
2713
+ f = f["function"]
2714
+ self.update_function_signature(f, is_remove=False)
2715
+ elif api_style == "tool":
2716
+ self.update_tool_signature(f, is_remove=False)
2717
+ else:
2718
+ raise ValueError(f"Unsupported API style: {api_style}")
2719
+
2720
+ return func
2721
+
2722
+ return _decorator
2723
+
2724
+ def register_for_execution(
2725
+ self,
2726
+ name: Optional[str] = None,
2727
+ ) -> Callable[[F], F]:
2728
+ """Decorator factory for registering a function to be executed by an agent.
2729
+
2730
+ It's return value is used to decorate a function to be registered to the agent.
2731
+
2732
+ Args:
2733
+ name (optional(str)): name of the function. If None, the function name will be used (default: None).
2734
+
2735
+ Returns:
2736
+ The decorator for registering a function to be used by an agent.
2737
+
2738
+ Examples:
2739
+ ```
2740
+ @user_proxy.register_for_execution()
2741
+ @agent2.register_for_llm()
2742
+ @agent1.register_for_llm(description="This is a very useful function")
2743
+ def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14):
2744
+ return a + str(b * c)
2745
+ ```
2746
+
2747
+ """
2748
+
2749
+ def _decorator(func: F) -> F:
2750
+ """Decorator for registering a function to be used by an agent.
2751
+
2752
+ Args:
2753
+ func: the function to be registered.
2754
+
2755
+ Returns:
2756
+ The function to be registered, with the _description attribute set to the function description.
2757
+
2758
+ Raises:
2759
+ ValueError: if the function description is not provided and not propagated by a previous decorator.
2760
+
2761
+ """
2762
+ # name can be overwritten by the parameter, by default it is the same as function name
2763
+ if name:
2764
+ func._name = name
2765
+ elif not hasattr(func, "_name"):
2766
+ func._name = func.__name__
2767
+
2768
+ self.register_function({func._name: self._wrap_function(func)})
2769
+
2770
+ return func
2771
+
2772
+ return _decorator
2773
+
2774
+ def register_model_client(self, model_client_cls: ModelClient, **kwargs):
2775
+ """Register a model client.
2776
+
2777
+ Args:
2778
+ model_client_cls: A custom client class that follows the Client interface
2779
+ **kwargs: The kwargs for the custom client class to be initialized with
2780
+ """
2781
+ self.client.register_model_client(model_client_cls, **kwargs)
2782
+
2783
+ def register_hook(self, hookable_method: str, hook: Callable):
2784
+ """
2785
+ Registers a hook to be called by a hookable method, in order to add a capability to the agent.
2786
+ Registered hooks are kept in lists (one per hookable method), and are called in their order of registration.
2787
+
2788
+ Args:
2789
+ hookable_method: A hookable method name implemented by ConversableAgent.
2790
+ hook: A method implemented by a subclass of AgentCapability.
2791
+ """
2792
+ assert hookable_method in self.hook_lists, f"{hookable_method} is not a hookable method."
2793
+ hook_list = self.hook_lists[hookable_method]
2794
+ assert hook not in hook_list, f"{hook} is already registered as a hook."
2795
+ hook_list.append(hook)
2796
+
2797
+ def process_all_messages_before_reply(self, messages: List[Dict]) -> List[Dict]:
2798
+ """
2799
+ Calls any registered capability hooks to process all messages, potentially modifying the messages.
2800
+ """
2801
+ hook_list = self.hook_lists["process_all_messages_before_reply"]
2802
+ # If no hooks are registered, or if there are no messages to process, return the original message list.
2803
+ if len(hook_list) == 0 or messages is None:
2804
+ return messages
2805
+
2806
+ # Call each hook (in order of registration) to process the messages.
2807
+ processed_messages = messages
2808
+ for hook in hook_list:
2809
+ processed_messages = hook(processed_messages)
2810
+ return processed_messages
2811
+
2812
+ def process_last_received_message(self, messages: List[Dict]) -> List[Dict]:
2813
+ """
2814
+ Calls any registered capability hooks to use and potentially modify the text of the last message,
2815
+ as long as the last message is not a function call or exit command.
2816
+ """
2817
+
2818
+ # If any required condition is not met, return the original message list.
2819
+ hook_list = self.hook_lists["process_last_received_message"]
2820
+ if len(hook_list) == 0:
2821
+ return messages # No hooks registered.
2822
+ if messages is None:
2823
+ return None # No message to process.
2824
+ if len(messages) == 0:
2825
+ return messages # No message to process.
2826
+ last_message = messages[-1]
2827
+ if "function_call" in last_message:
2828
+ return messages # Last message is a function call.
2829
+ if "context" in last_message:
2830
+ return messages # Last message contains a context key.
2831
+ if "content" not in last_message:
2832
+ return messages # Last message has no content.
2833
+
2834
+ user_content = last_message["content"]
2835
+ if not isinstance(user_content, str) and not isinstance(user_content, list):
2836
+ # if the user_content is a string, it is for regular LLM
2837
+ # if the user_content is a list, it should follow the multimodal LMM format.
2838
+ return messages
2839
+ if user_content == "exit":
2840
+ return messages # Last message is an exit command.
2841
+
2842
+ # Call each hook (in order of registration) to process the user's message.
2843
+ processed_user_content = user_content
2844
+ for hook in hook_list:
2845
+ processed_user_content = hook(processed_user_content)
2846
+
2847
+ if processed_user_content == user_content:
2848
+ return messages # No hooks actually modified the user's message.
2849
+
2850
+ # Replace the last user message with the expanded one.
2851
+ messages = messages.copy()
2852
+ messages[-1]["content"] = processed_user_content
2853
+ return messages
2854
+
2855
+ def print_usage_summary(self, mode: Union[str, List[str]] = ["actual", "total"]) -> None:
2856
+ """Print the usage summary."""
2857
+ iostream = IOStream.get_default()
2858
+
2859
+ if self.client is None:
2860
+ iostream.print(f"No cost incurred from agent '{self.name}'.")
2861
+ else:
2862
+ iostream.print(f"Agent '{self.name}':")
2863
+ self.client.print_usage_summary(mode)
2864
+
2865
+ def get_actual_usage(self) -> Union[None, Dict[str, int]]:
2866
+ """Get the actual usage summary."""
2867
+ if self.client is None:
2868
+ return None
2869
+ else:
2870
+ return self.client.actual_usage_summary
2871
+
2872
+ def get_total_usage(self) -> Union[None, Dict[str, int]]:
2873
+ """Get the total usage summary."""
2874
+ if self.client is None:
2875
+ return None
2876
+ else:
2877
+ return self.client.total_usage_summary
2878
+
2879
+
2880
+ def register_function(
2881
+ f: Callable[..., Any],
2882
+ *,
2883
+ caller: ConversableAgent,
2884
+ executor: ConversableAgent,
2885
+ name: Optional[str] = None,
2886
+ description: str,
2887
+ ) -> None:
2888
+ """Register a function to be proposed by an agent and executed for an executor.
2889
+
2890
+ This function can be used instead of function decorators `@ConversationAgent.register_for_llm` and
2891
+ `@ConversationAgent.register_for_execution`.
2892
+
2893
+ Args:
2894
+ f: the function to be registered.
2895
+ caller: the agent calling the function, typically an instance of ConversableAgent.
2896
+ executor: the agent executing the function, typically an instance of UserProxy.
2897
+ name: name of the function. If None, the function name will be used (default: None).
2898
+ description: description of the function. The description is used by LLM to decode whether the function
2899
+ is called. Make sure the description is properly describing what the function does or it might not be
2900
+ called by LLM when needed.
2901
+
2902
+ """
2903
+ f = caller.register_for_llm(name=name, description=description)(f)
2904
+ executor.register_for_execution(name=name)(f)