UserProxyAgent - AG2

UserProxyAgent

``autogen.UserProxyAgent #

UserProxyAgent(name, is_termination_msg=None, max_consecutive_auto_reply=None, human_input_mode='ALWAYS', function_map=None, code_execution_config={}, default_auto_reply='', llm_config=False, system_message='', description=None, **kwargs)

Bases: ConversableAgent

(In preview) A proxy agent for the user, that can execute code and provide feedback to the other agents.

UserProxyAgent is a subclass of ConversableAgent configured with human_input_mode to ALWAYS and llm_config to False. By default, the agent will prompt for human input every time a message is received. Code execution is enabled by default. LLM-based auto reply is disabled by default. To modify auto reply, register a method with register_reply. To modify the way to get human input, override get_human_input method. To modify the way to execute code blocks, single code block, or function call, override execute_code_blocks, run_code, and execute_function methods respectively.

Args: name (str): name of the agent. is_termination_msg (function): a function that takes a message in the form of a dictionary and returns a boolean value indicating if this received message is a termination message. The dict can contain the following keys: "content", "role", "name", "function_call". max_consecutive_auto_reply (int): the maximum number of consecutive auto replies. default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case). The limit only plays a role when human_input_mode is not "ALWAYS". human_input_mode (str): whether to ask for human inputs every time a message is received. Possible values are "ALWAYS", "TERMINATE", "NEVER". (1) When "ALWAYS", the agent prompts for human input every time a message is received. Under this mode, the conversation stops when the human input is "exit", or when is_termination_msg is True and there is no human input. (2) When "TERMINATE", the agent only prompts for human input only when a termination message is received or the number of auto reply reaches the max_consecutive_auto_reply. (3) When "NEVER", the agent will never prompt for human input. Under this mode, the conversation stops when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True. function_map (dict[str, callable]): Mapping function names (passed to openai) to callable functions. code_execution_config (dict or False): config for the code execution. To disable code execution, set to False. Otherwise, set to a dictionary with the following keys: - work_dir (Optional, str): The working directory for the code execution. If None, a default working directory will be used. The default working directory is the "extensions" directory under "path_to_autogen". - use_docker (Optional, list, str or bool): The docker image to use for code execution. Default is True, which means the code will be executed in a docker container. A default list of images will be used. If a list or a str of image name(s) is provided, the code will be executed in a docker container with the first image successfully pulled. If False, the code will be executed in the current environment. We strongly recommend using docker for code execution. - timeout (Optional, int): The maximum execution time in seconds. - last_n_messages (Experimental, Optional, int): The number of messages to look back for code execution. Default to 1. default_auto_reply (str or dict or None): the default auto reply message when no code execution or llm based reply is generated. llm_config (LLMConfig or dict or False or None): llm inference configuration. Please refer to OpenAIWrapper.create for available options. Default to False, which disables llm-based auto reply. When set to None, will use self.DEFAULT_CONFIG, which defaults to False. system_message (str or List): system message for ChatCompletion inference. Only used when llm_config is not False. Use it to reprogram the agent. description (str): a short description of the agent. This description is used by other agents (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message) **kwargs (dict): Please refer to other kwargs in ConversableAgent.

Source code in autogen/agentchat/user_proxy_agent.py

<br> 35<br> 36<br> 37<br> 38<br> 39<br> 40<br> 41<br> 42<br> 43<br> 44<br> 45<br> 46<br> 47<br> 48<br> 49<br> 50<br> 51<br> 52<br> 53<br> 54<br> 55<br> 56<br> 57<br> 58<br> 59<br> 60<br> 61<br> 62<br> 63<br> 64<br> 65<br> 66<br> 67<br> 68<br> 69<br> 70<br> 71<br> 72<br> 73<br> 74<br> 75<br> 76<br> 77<br> 78<br> 79<br> 80<br> 81<br> 82<br> 83<br> 84<br> 85<br> 86<br> 87<br> 88<br> 89<br> 90<br> 91<br> 92<br> 93<br> 94<br> 95<br> 96<br> 97<br> 98<br> 99<br>100<br>101<br>102<br>103<br>104<br>105<br>106<br>107<br>108<br>109<br>110<br>111<br> <br>def __init__(<br> self,<br> name: str,<br> is_termination_msg: Optional[Callable[[dict[str, Any]], bool]] = None,<br> max_consecutive_auto_reply: Optional[int] = None,<br> human_input_mode: Literal["ALWAYS", "TERMINATE", "NEVER"] = "ALWAYS",<br> function_map: Optional[dict[str, Callable[..., Any]]] = None,<br> code_execution_config: Union[dict[str, Any], Literal[False]] = {},<br> default_auto_reply: Optional[Union[str, dict[str, Any]]] = "",<br> llm_config: Optional[Union[LLMConfig, dict[str, Any], Literal[False]]] = False,<br> system_message: Optional[Union[str, list[str]]] = "",<br> description: Optional[str] = None,<br> **kwargs: Any,<br>):<br> """Args:<br> name (str): name of the agent.<br> is_termination_msg (function): a function that takes a message in the form of a dictionary<br> and returns a boolean value indicating if this received message is a termination message.<br> The dict can contain the following keys: "content", "role", "name", "function_call".<br> max_consecutive_auto_reply (int): the maximum number of consecutive auto replies.<br> default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).<br> The limit only plays a role when human_input_mode is not "ALWAYS".<br> human_input_mode (str): whether to ask for human inputs every time a message is received.<br> Possible values are "ALWAYS", "TERMINATE", "NEVER".<br> (1) When "ALWAYS", the agent prompts for human input every time a message is received.<br> Under this mode, the conversation stops when the human input is "exit",<br> or when is_termination_msg is True and there is no human input.<br> (2) When "TERMINATE", the agent only prompts for human input only when a termination message is received or<br> the number of auto reply reaches the max_consecutive_auto_reply.<br> (3) When "NEVER", the agent will never prompt for human input. Under this mode, the conversation stops<br> when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.<br> function_map (dict[str, callable]): Mapping function names (passed to openai) to callable functions.<br> code_execution_config (dict or False): config for the code execution.<br> To disable code execution, set to False. Otherwise, set to a dictionary with the following keys:<br> - work_dir (Optional, str): The working directory for the code execution.<br> If None, a default working directory will be used.<br> The default working directory is the "extensions" directory under<br> "path_to_autogen".<br> - use_docker (Optional, list, str or bool): The docker image to use for code execution.<br> Default is True, which means the code will be executed in a docker container. A default list of images will be used.<br> If a list or a str of image name(s) is provided, the code will be executed in a docker container<br> with the first image successfully pulled.<br> If False, the code will be executed in the current environment.<br> We strongly recommend using docker for code execution.<br> - timeout (Optional, int): The maximum execution time in seconds.<br> - last_n_messages (Experimental, Optional, int): The number of messages to look back for code execution. Default to 1.<br> default_auto_reply (str or dict or None): the default auto reply message when no code execution or llm based reply is generated.<br> llm_config (LLMConfig or dict or False or None): llm inference configuration.<br> Please refer to [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create)<br> for available options.<br> Default to False, which disables llm-based auto reply.<br> When set to None, will use self.DEFAULT_CONFIG, which defaults to False.<br> system_message (str or List): system message for ChatCompletion inference.<br> Only used when llm_config is not False. Use it to reprogram the agent.<br> description (str): a short description of the agent. This description is used by other agents<br> (e.g. the GroupChatManager) to decide when to call upon this agent. (Default: system_message)<br> **kwargs (dict): Please refer to other kwargs in<br> [ConversableAgent](https://docs.ag2.ai/latest/docs/api-reference/autogen/ConversableAgent).<br> """<br> super().__init__(<br> name=name,<br> system_message=system_message,<br> is_termination_msg=is_termination_msg,<br> max_consecutive_auto_reply=max_consecutive_auto_reply,<br> human_input_mode=human_input_mode,<br> function_map=function_map,<br> code_execution_config=code_execution_config,<br> llm_config=llm_config,<br> default_auto_reply=default_auto_reply,<br> description=(<br> description if description is not None else self.DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS[human_input_mode]<br> ),<br> **kwargs,<br> )<br> if logging_enabled():<br> log_new_agent(self, locals())<br>

``nameproperty#

name

Get the name of the agent.

description`propertywritable`#

description

Get the description of the agent.

``system_messageproperty#

system_message

Return the system message.

DEFAULT\_CONFIG`class-attributeinstance-attribute`#

DEFAULT_CONFIG = False

MAX\_CONSECUTIVE\_AUTO\_REPLY`class-attributeinstance-attribute`#

MAX_CONSECUTIVE_AUTO_REPLY = 100

DEFAULT\_SUMMARY\_PROMPT`class-attributeinstance-attribute`#

DEFAULT_SUMMARY_PROMPT = 'Summarize the takeaway from the conversation. Do not add any introductory phrases.'

DEFAULT\_SUMMARY\_METHOD`class-attributeinstance-attribute`#

DEFAULT_SUMMARY_METHOD = 'last_msg'

``llm_configinstance-attribute#

llm_config = _validate_llm_config(llm_config)

``handoffsinstance-attribute#

handoffs = handoffs if handoffs is not None else Handoffs()

``silentinstance-attribute#

silent = silent

``run_executorinstance-attribute#

run_executor = None

``clientinstance-attribute#

client = _create_client(llm_config)

``client_cacheinstance-attribute#

client_cache = None

``human_input_modeinstance-attribute#

human_input_mode = human_input_mode

``reply_at_receiveinstance-attribute#

reply_at_receive = defaultdict(bool)

``context_variablesinstance-attribute#

context_variables = context_variables if context_variables is not None else ContextVariables()

``hook_listsinstance-attribute#

hook_lists = {'process_last_received_message': [], 'process_all_messages_before_reply': [], 'process_message_before_send': [], 'update_agent_state': []}

``code_executorproperty#

code_executor

The code executor used by this agent. Returns None if code execution is disabled.

``chat_messagesproperty#

chat_messages

A dictionary of conversations from agent to list of messages.

``use_dockerproperty#

use_docker

Bool value of whether to use docker to execute the code, or str value of the docker image name to use, or None when code execution is disabled.

``toolsproperty#

tools

Get the agent's tools (registered for LLM)

Note this is a copy of the tools list, use add_tool and remove_tool to modify the tools list.

``function_mapproperty#

function_map

Return the function map.

DEFAULT\_USER\_PROXY\_AGENT\_DESCRIPTIONS`class-attributeinstance-attribute`#

DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS = {'ALWAYS': 'An attentive HUMAN user who can answer questions about the task, and can perform tasks such as running Python code or inputting command line commands at a Linux terminal and reporting back the execution results.', 'TERMINATE': 'A user that can run Python code or input command line commands at a Linux terminal and report back the execution results.', 'NEVER': 'A computer terminal that performs no other action than running Python scripts (provided to it quoted in ```python code blocks), or sh shell scripts (provided to it quoted in ```sh code blocks).'}

``send #

send(message, recipient, request_reply=None, silent=False)

Send a message to another agent.

PARAMETER DESCRIPTION
message message to be sent. The message could contain the following fields: - content (str or List): Required, the content of the message. (Can be None) - function_call (str): the name of the function to be called. - name (str): the name of the function to be called. - role (str): the role of the message, any role that is not "function" will be modified to "assistant". - context (dict): the context of the message, which will be passed to OpenAIWrapper.create. For example, one agent can send a message A as:
TYPE:dict or str
{
    "content": lambda context: context["use_tool_msg"],
    "context": {"use_tool_msg": "Use tool X if they are relevant."},
}

Next time, one agent can send a message B with a different "use_tool_msg". Then the content of message A will be refreshed to the new "use_tool_msg". So effectively, this provides a way for an agent to send a "link" and modify the content of the "link" later. recipient (Agent): the recipient of the message. request_reply (bool or None): whether to request a reply from the recipient. silent (bool or None): (Experimental) whether to print the message sent.

RAISES DESCRIPTION
ValueError if the message can't be converted into a valid ChatCompletion message.

Source code in autogen/agentchat/conversable_agent.py

<br>1119<br>1120<br>1121<br>1122<br>1123<br>1124<br>1125<br>1126<br>1127<br>1128<br>1129<br>1130<br>1131<br>1132<br>1133<br>1134<br>1135<br>1136<br>1137<br>1138<br>1139<br>1140<br>1141<br>1142<br>1143<br>1144<br>1145<br>1146<br>1147<br>1148<br>1149<br>1150<br>1151<br>1152<br>1153<br>1154<br>1155<br>1156<br>1157<br>1158<br>1159<br>1160<br>1161<br>1162<br>1163<br>1164<br>1165<br> <br>def send(<br> self,<br> message: Union[dict[str, Any], str],<br> recipient: Agent,<br> request_reply: Optional[bool] = None,<br> silent: Optional[bool] = False,<br>):<br> """Send a message to another agent.<br> Args:<br> message (dict or str): message to be sent.<br> The message could contain the following fields:<br> - content (str or List): Required, the content of the message. (Can be None)<br> - function_call (str): the name of the function to be called.<br> - name (str): the name of the function to be called.<br> - role (str): the role of the message, any role that is not "function"<br> will be modified to "assistant".<br> - context (dict): the context of the message, which will be passed to<br> [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).<br> For example, one agent can send a message A as:<br> ```python<br> {<br> "content": lambda context: context["use_tool_msg"],<br> "context": {"use_tool_msg": "Use tool X if they are relevant."},<br> }<br> ```<br> Next time, one agent can send a message B with a different "use_tool_msg".<br> Then the content of message A will be refreshed to the new "use_tool_msg".<br> So effectively, this provides a way for an agent to send a "link" and modify<br> the content of the "link" later.<br> recipient (Agent): the recipient of the message.<br> request_reply (bool or None): whether to request a reply from the recipient.<br> silent (bool or None): (Experimental) whether to print the message sent.<br> Raises:<br> ValueError: if the message can't be converted into a valid ChatCompletion message.<br> """<br> message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))<br> # When the agent composes and sends the message, the role of the message is "assistant"<br> # unless it's "function".<br> valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)<br> if valid:<br> recipient.receive(message, self, request_reply, silent)<br> else:<br> raise ValueError(<br> "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."<br> )<br>

``a_sendasync#

a_send(message, recipient, request_reply=None, silent=False)

(async) Send a message to another agent.

{
    "content": lambda context: context["use_tool_msg"],
    "context": {"use_tool_msg": "Use tool X if they are relevant."},
}
RAISES DESCRIPTION
ValueError if the message can't be converted into a valid ChatCompletion message.

Source code in autogen/agentchat/conversable_agent.py

<br>1167<br>1168<br>1169<br>1170<br>1171<br>1172<br>1173<br>1174<br>1175<br>1176<br>1177<br>1178<br>1179<br>1180<br>1181<br>1182<br>1183<br>1184<br>1185<br>1186<br>1187<br>1188<br>1189<br>1190<br>1191<br>1192<br>1193<br>1194<br>1195<br>1196<br>1197<br>1198<br>1199<br>1200<br>1201<br>1202<br>1203<br>1204<br>1205<br>1206<br>1207<br>1208<br>1209<br>1210<br>1211<br>1212<br>1213<br> <br>async def a_send(<br> self,<br> message: Union[dict[str, Any], str],<br> recipient: Agent,<br> request_reply: Optional[bool] = None,<br> silent: Optional[bool] = False,<br>):<br> """(async) Send a message to another agent.<br> Args:<br> message (dict or str): message to be sent.<br> The message could contain the following fields:<br> - content (str or List): Required, the content of the message. (Can be None)<br> - function_call (str): the name of the function to be called.<br> - name (str): the name of the function to be called.<br> - role (str): the role of the message, any role that is not "function"<br> will be modified to "assistant".<br> - context (dict): the context of the message, which will be passed to<br> [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).<br> For example, one agent can send a message A as:<br> ```python<br> {<br> "content": lambda context: context["use_tool_msg"],<br> "context": {"use_tool_msg": "Use tool X if they are relevant."},<br> }<br> ```<br> Next time, one agent can send a message B with a different "use_tool_msg".<br> Then the content of message A will be refreshed to the new "use_tool_msg".<br> So effectively, this provides a way for an agent to send a "link" and modify<br> the content of the "link" later.<br> recipient (Agent): the recipient of the message.<br> request_reply (bool or None): whether to request a reply from the recipient.<br> silent (bool or None): (Experimental) whether to print the message sent.<br> Raises:<br> ValueError: if the message can't be converted into a valid ChatCompletion message.<br> """<br> message = self._process_message_before_send(message, recipient, ConversableAgent._is_silent(self, silent))<br> # When the agent composes and sends the message, the role of the message is "assistant"<br> # unless it's "function".<br> valid = self._append_oai_message(message, "assistant", recipient, is_sending=True)<br> if valid:<br> await recipient.a_receive(message, self, request_reply, silent)<br> else:<br> raise ValueError(<br> "Message can't be converted into a valid ChatCompletion message. Either content or function_call must be provided."<br> )<br>

``receive #

receive(message, sender, request_reply=None, silent=False)

Receive a message from another agent.

Once a message is received, this function sends a reply to the sender or stop. The reply can be generated automatically or entered manually by a human.

PARAMETER DESCRIPTION
message 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). 1. "content": content of the message, can be None. 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls") 3. "tool_calls": a list of dictionaries containing the function name and arguments. 4. "role": role of the message, can be "assistant", "user", "function", "tool". This field is only needed to distinguish between "function" or "assistant"/"user". 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name. 6. "context" (dict): the context of the message, which will be passed to OpenAIWrapper.create.
TYPE:dict or str
sender sender of an Agent instance.
TYPE:Agent
request_reply whether a reply is requested from the sender. If None, the value is determined by self.reply_at_receive[sender].
TYPE:bool or NoneDEFAULT:None
silent (Experimental) whether to print the message received.
TYPE:bool or NoneDEFAULT:False
RAISES DESCRIPTION
ValueError if the message can't be converted into a valid ChatCompletion message.

Source code in autogen/agentchat/conversable_agent.py

<br>1236<br>1237<br>1238<br>1239<br>1240<br>1241<br>1242<br>1243<br>1244<br>1245<br>1246<br>1247<br>1248<br>1249<br>1250<br>1251<br>1252<br>1253<br>1254<br>1255<br>1256<br>1257<br>1258<br>1259<br>1260<br>1261<br>1262<br>1263<br>1264<br>1265<br>1266<br>1267<br>1268<br>1269<br>1270<br>1271<br> <br>def receive(<br> self,<br> message: Union[dict[str, Any], str],<br> sender: Agent,<br> request_reply: Optional[bool] = None,<br> silent: Optional[bool] = False,<br>):<br> """Receive a message from another agent.<br> Once a message is received, this function sends a reply to the sender or stop.<br> The reply can be generated automatically or entered manually by a human.<br> Args:<br> 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).<br> 1. "content": content of the message, can be None.<br> 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")<br> 3. "tool_calls": a list of dictionaries containing the function name and arguments.<br> 4. "role": role of the message, can be "assistant", "user", "function", "tool".<br> This field is only needed to distinguish between "function" or "assistant"/"user".<br> 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.<br> 6. "context" (dict): the context of the message, which will be passed to<br> [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).<br> sender: sender of an Agent instance.<br> request_reply (bool or None): whether a reply is requested from the sender.<br> If None, the value is determined by `self.reply_at_receive[sender]`.<br> silent (bool or None): (Experimental) whether to print the message received.<br> Raises:<br> ValueError: if the message can't be converted into a valid ChatCompletion message.<br> """<br> self._process_received_message(message, sender, silent)<br> if request_reply is False or (request_reply is None and self.reply_at_receive[sender] is False):<br> return<br> reply = self.generate_reply(messages=self.chat_messages[sender], sender=sender)<br> if reply is not None:<br> self.send(reply, sender, silent=silent)<br>

``a_receiveasync#

a_receive(message, sender, request_reply=None, silent=False)

(async) Receive a message from another agent.

Once a message is received, this function sends a reply to the sender or stop. The reply can be generated automatically or entered manually by a human.

RAISES DESCRIPTION
ValueError if the message can't be converted into a valid ChatCompletion message.

Source code in autogen/agentchat/conversable_agent.py

<br>1273<br>1274<br>1275<br>1276<br>1277<br>1278<br>1279<br>1280<br>1281<br>1282<br>1283<br>1284<br>1285<br>1286<br>1287<br>1288<br>1289<br>1290<br>1291<br>1292<br>1293<br>1294<br>1295<br>1296<br>1297<br>1298<br>1299<br>1300<br>1301<br>1302<br>1303<br>1304<br>1305<br>1306<br>1307<br>1308<br> <br>async def a_receive(<br> self,<br> message: Union[dict[str, Any], str],<br> sender: Agent,<br> request_reply: Optional[bool] = None,<br> silent: Optional[bool] = False,<br>):<br> """(async) Receive a message from another agent.<br> Once a message is received, this function sends a reply to the sender or stop.<br> The reply can be generated automatically or entered manually by a human.<br> Args:<br> 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).<br> 1. "content": content of the message, can be None.<br> 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")<br> 3. "tool_calls": a list of dictionaries containing the function name and arguments.<br> 4. "role": role of the message, can be "assistant", "user", "function".<br> This field is only needed to distinguish between "function" or "assistant"/"user".<br> 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.<br> 6. "context" (dict): the context of the message, which will be passed to<br> [OpenAIWrapper.create](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).<br> sender: sender of an Agent instance.<br> request_reply (bool or None): whether a reply is requested from the sender.<br> If None, the value is determined by `self.reply_at_receive[sender]`.<br> silent (bool or None): (Experimental) whether to print the message received.<br> Raises:<br> ValueError: if the message can't be converted into a valid ChatCompletion message.<br> """<br> self._process_received_message(message, sender, silent)<br> if request_reply is False or (request_reply is None and self.reply_at_receive[sender] is False):<br> return<br> reply = await self.a_generate_reply(messages=self.chat_messages[sender], sender=sender)<br> if reply is not None:<br> await self.a_send(reply, sender, silent=silent)<br>

``generate_reply #

generate_reply(messages=None, sender=None, **kwargs)

Reply based on the conversation history and the sender.

Either messages or sender must be provided. Register a reply_func with None as one trigger for it to be activated when messages is non-empty and sender is None. Use registered auto reply functions to generate replies. By default, the following functions are checked in order: 1. check_termination_and_human_reply 2. generate_function_call_reply (deprecated in favor of tool_calls) 3. generate_tool_calls_reply 4. generate_code_execution_reply 5. generate_oai_reply Every function returns a tuple (final, reply). When a function returns final=False, the next function will be checked. So by default, termination and human reply will be checked first. If not terminating and human reply is skipped, execute function or code and return the result. AI replies are generated only when no code execution is performed.

PARAMETER DESCRIPTION
messages a list of messages in the conversation history.
TYPE:Optional[list[dict[str, Any]]]DEFAULT:None
sender sender of an Agent instance.
TYPE:Optional[Agent]DEFAULT:None
**kwargs Additional arguments to customize reply generation. Supported kwargs: - exclude (List[Callable[..., Any]]): A list of reply functions to exclude from the reply generation process. Functions in this list will be skipped even if they would normally be triggered.
TYPE:AnyDEFAULT:{}
RETURNS DESCRIPTION
Optional[Union[str, dict[str, Any]]] str or dict or None: reply. None if no reply is generated.

Source code in autogen/agentchat/conversable_agent.py

<br>2766<br>2767<br>2768<br>2769<br>2770<br>2771<br>2772<br>2773<br>2774<br>2775<br>2776<br>2777<br>2778<br>2779<br>2780<br>2781<br>2782<br>2783<br>2784<br>2785<br>2786<br>2787<br>2788<br>2789<br>2790<br>2791<br>2792<br>2793<br>2794<br>2795<br>2796<br>2797<br>2798<br>2799<br>2800<br>2801<br>2802<br>2803<br>2804<br>2805<br>2806<br>2807<br>2808<br>2809<br>2810<br>2811<br>2812<br>2813<br>2814<br>2815<br>2816<br>2817<br>2818<br>2819<br>2820<br>2821<br>2822<br>2823<br>2824<br>2825<br>2826<br>2827<br>2828<br>2829<br>2830<br>2831<br>2832<br>2833<br>2834<br>2835<br>2836<br>2837<br>2838<br> <br>def generate_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional["Agent"] = None,<br> **kwargs: Any,<br>) -> Optional[Union[str, dict[str, Any]]]:<br> """Reply based on the conversation history and the sender.<br> Either messages or sender must be provided.<br> Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.<br> Use registered auto reply functions to generate replies.<br> By default, the following functions are checked in order:<br> 1. check_termination_and_human_reply<br> 2. generate_function_call_reply (deprecated in favor of tool_calls)<br> 3. generate_tool_calls_reply<br> 4. generate_code_execution_reply<br> 5. generate_oai_reply<br> Every function returns a tuple (final, reply).<br> When a function returns final=False, the next function will be checked.<br> So by default, termination and human reply will be checked first.<br> If not terminating and human reply is skipped, execute function or code and return the result.<br> AI replies are generated only when no code execution is performed.<br> Args:<br> messages: a list of messages in the conversation history.<br> sender: sender of an Agent instance.<br> **kwargs (Any): Additional arguments to customize reply generation. Supported kwargs:<br> - exclude (List[Callable[..., Any]]): A list of reply functions to exclude from<br> the reply generation process. Functions in this list will be skipped even if<br> they would normally be triggered.<br> Returns:<br> str or dict or None: reply. None if no reply is generated.<br> """<br> if all((messages is None, sender is None)):<br> error_msg = f"Either {messages=} or {sender=} must be provided."<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> if messages is None:<br> messages = self._oai_messages[sender]<br> # Call the hookable method that gives registered hooks a chance to update agent state, used for their context variables.<br> self.update_agent_state_before_reply(messages)<br> # Call the hookable method that gives registered hooks a chance to process the last message.<br> # Message modifications do not affect the incoming messages or self._oai_messages.<br> messages = self.process_last_received_message(messages)<br> # Call the hookable method that gives registered hooks a chance to process all messages.<br> # Message modifications do not affect the incoming messages or self._oai_messages.<br> messages = self.process_all_messages_before_reply(messages)<br> for reply_func_tuple in self._reply_func_list:<br> reply_func = reply_func_tuple["reply_func"]<br> if "exclude" in kwargs and reply_func in kwargs["exclude"]:<br> continue<br> if inspect.iscoroutinefunction(reply_func):<br> continue<br> if self._match_trigger(reply_func_tuple["trigger"], sender):<br> final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])<br> if logging_enabled():<br> log_event(<br> self,<br> "reply_func_executed",<br> reply_func_module=reply_func.__module__,<br> reply_func_name=reply_func.__name__,<br> final=final,<br> reply=reply,<br> )<br> if final:<br> return reply<br> return self._default_auto_reply<br>

``a_generate_replyasync#

a_generate_reply(messages=None, sender=None, **kwargs)

(async) Reply based on the conversation history and the sender.

Either messages or sender must be provided. Register a reply_func with None as one trigger for it to be activated when messages is non-empty and sender is None. Use registered auto reply functions to generate replies. By default, the following functions are checked in order: 1. check_termination_and_human_reply 2. generate_function_call_reply 3. generate_tool_calls_reply 4. generate_code_execution_reply 5. generate_oai_reply Every function returns a tuple (final, reply). When a function returns final=False, the next function will be checked. So by default, termination and human reply will be checked first. If not terminating and human reply is skipped, execute function or code and return the result. AI replies are generated only when no code execution is performed.

RETURNS DESCRIPTION
Union[str, dict[str, Any], None] str or dict or None: reply. None if no reply is generated.

Source code in autogen/agentchat/conversable_agent.py

<br>2840<br>2841<br>2842<br>2843<br>2844<br>2845<br>2846<br>2847<br>2848<br>2849<br>2850<br>2851<br>2852<br>2853<br>2854<br>2855<br>2856<br>2857<br>2858<br>2859<br>2860<br>2861<br>2862<br>2863<br>2864<br>2865<br>2866<br>2867<br>2868<br>2869<br>2870<br>2871<br>2872<br>2873<br>2874<br>2875<br>2876<br>2877<br>2878<br>2879<br>2880<br>2881<br>2882<br>2883<br>2884<br>2885<br>2886<br>2887<br>2888<br>2889<br>2890<br>2891<br>2892<br>2893<br>2894<br>2895<br>2896<br>2897<br>2898<br>2899<br>2900<br>2901<br>2902<br>2903<br>2904<br>2905<br>2906<br>2907<br> <br>async def a_generate_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional["Agent"] = None,<br> **kwargs: Any,<br>) -> Union[str, dict[str, Any], None]:<br> """(async) Reply based on the conversation history and the sender.<br> Either messages or sender must be provided.<br> Register a reply_func with `None` as one trigger for it to be activated when `messages` is non-empty and `sender` is `None`.<br> Use registered auto reply functions to generate replies.<br> By default, the following functions are checked in order:<br> 1. check_termination_and_human_reply<br> 2. generate_function_call_reply<br> 3. generate_tool_calls_reply<br> 4. generate_code_execution_reply<br> 5. generate_oai_reply<br> Every function returns a tuple (final, reply).<br> When a function returns final=False, the next function will be checked.<br> So by default, termination and human reply will be checked first.<br> If not terminating and human reply is skipped, execute function or code and return the result.<br> AI replies are generated only when no code execution is performed.<br> Args:<br> messages: a list of messages in the conversation history.<br> sender: sender of an Agent instance.<br> **kwargs (Any): Additional arguments to customize reply generation. Supported kwargs:<br> - exclude (List[Callable[..., Any]]): A list of reply functions to exclude from<br> the reply generation process. Functions in this list will be skipped even if<br> they would normally be triggered.<br> Returns:<br> str or dict or None: reply. None if no reply is generated.<br> """<br> if all((messages is None, sender is None)):<br> error_msg = f"Either {messages=} or {sender=} must be provided."<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> if messages is None:<br> messages = self._oai_messages[sender]<br> # Call the hookable method that gives registered hooks a chance to update agent state, used for their context variables.<br> self.update_agent_state_before_reply(messages)<br> # Call the hookable method that gives registered hooks a chance to process the last message.<br> # Message modifications do not affect the incoming messages or self._oai_messages.<br> messages = self.process_last_received_message(messages)<br> # Call the hookable method that gives registered hooks a chance to process all messages.<br> # Message modifications do not affect the incoming messages or self._oai_messages.<br> messages = self.process_all_messages_before_reply(messages)<br> for reply_func_tuple in self._reply_func_list:<br> reply_func = reply_func_tuple["reply_func"]<br> if "exclude" in kwargs and reply_func in kwargs["exclude"]:<br> continue<br> if self._match_trigger(reply_func_tuple["trigger"], sender):<br> if inspect.iscoroutinefunction(reply_func):<br> final, reply = await reply_func(<br> self, messages=messages, sender=sender, config=reply_func_tuple["config"]<br> )<br> else:<br> final, reply = reply_func(self, messages=messages, sender=sender, config=reply_func_tuple["config"])<br> if final:<br> return reply<br> return self._default_auto_reply<br>

``set_ui_tools #

set_ui_tools(tools)

Set the UI tools for the agent.

PARAMETER DESCRIPTION
tools a list of tools to be set.
TYPE:list[Tool]

Source code in autogen/agentchat/conversable_agent.py

<br>3616<br>3617<br>3618<br>3619<br>3620<br>3621<br>3622<br>3623<br>3624<br>3625<br>3626<br>3627<br>3628<br>3629<br>3630<br>3631<br>3632<br>3633<br>3634<br>3635<br>3636<br> <br>def set_ui_tools(self, tools: list[Tool]) -> None:<br> """Set the UI tools for the agent.<br> Args:<br> tools: a list of tools to be set.<br> """<br> # Unset the previous UI tools<br> self._unset_previous_ui_tools()<br> # Set the new UI tools<br> for tool in tools:<br> # Register the tool for LLM<br> self._register_for_llm(tool, api_style="tool", silent_override=True)<br> if tool not in self._tools:<br> self._tools.append(tool)<br> # Register for execution<br> self.register_for_execution(serialize=False, silent_override=True)(tool)<br> # Set the current UI tools<br> self._ui_tools = tools<br>

``unset_ui_tools #

unset_ui_tools(tools)

Unset the UI tools for the agent.

PARAMETER DESCRIPTION
tools a list of tools to be unset.
TYPE:list[Tool]

Source code in autogen/agentchat/conversable_agent.py

<br>3638<br>3639<br>3640<br>3641<br>3642<br>3643<br>3644<br>3645<br> <br>def unset_ui_tools(self, tools: list[Tool]) -> None:<br> """Unset the UI tools for the agent.<br> Args:<br> tools: a list of tools to be unset.<br> """<br> for tool in tools:<br> self.remove_tool_for_llm(tool)<br>

``update_system_message #

update_system_message(system_message)

Update the system message.

PARAMETER DESCRIPTION
system_message system message for the ChatCompletion inference.
TYPE:str

Source code in autogen/agentchat/conversable_agent.py

<br>950<br>951<br>952<br>953<br>954<br>955<br>956<br> <br>def update_system_message(self, system_message: str) -> None:<br> """Update the system message.<br> Args:<br> system_message (str): system message for the ChatCompletion inference.<br> """<br> self._oai_system_message[0]["content"] = system_message<br>

``register_reply #

register_reply(trigger, reply_func, position=0, config=None, reset_config=None, *, ignore_async_in_sync_chat=False, remove_other_reply_funcs=False)

Register a reply function.

The reply function will be called when the trigger matches the sender. The function registered later will be checked earlier by default. To change the order, set the position to a positive integer.

Both sync and async reply functions can be registered. The sync reply function will be triggered from both sync and async chats. However, an async reply function will only be triggered from async chats (initiated with ConversableAgent.a_initiate_chat). If an async reply function is registered and a chat is initialized with a sync function, ignore_async_in_sync_chat determines the behaviour as follows: if ignore_async_in_sync_chat is set to False (default value), an exception will be raised, and if ignore_async_in_sync_chat is set to True, the reply function will be ignored.

PARAMETER DESCRIPTION
trigger the trigger. If a class is provided, the reply function will be called when the sender is an instance of the class. If a string is provided, the reply function will be called when the sender's name matches the string. If an agent instance is provided, the reply function will be called when the sender is the agent instance. If a callable is provided, the reply function will be called when the callable returns True. If a list is provided, the reply function will be called when any of the triggers in the list is activated. If None is provided, the reply function will be called only when the sender is None. 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.
TYPE:Agent class, str, Agent instance, callable, or list
reply_func the reply function. The function takes a recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.
<br>def reply_func(<br> recipient: ConversableAgent,<br> messages: Optional[List[Dict]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> Tuple[bool, Union[str, Dict, None]]:<br>
TYPE:Callable
position the position of the reply function in the reply function list. The function registered later will be checked earlier by default. To change the order, set the position to a positive integer.
TYPE:intDEFAULT:0
config the config to be passed to the reply function. When an agent is reset, the config will be reset to the original value.
TYPE:AnyDEFAULT:None
reset_config the function to reset the config. The function returns None. Signature: def reset_config(config: Any)
TYPE:CallableDEFAULT:None
ignore_async_in_sync_chat whether to ignore the async reply function in sync chats. If False, an exception will be raised if an async reply function is registered and a chat is initialized with a sync function.
TYPE:boolDEFAULT:False
remove_other_reply_funcs whether to remove other reply functions when registering this reply function.
TYPE:boolDEFAULT:False

Source code in autogen/agentchat/conversable_agent.py

<br>536<br>537<br>538<br>539<br>540<br>541<br>542<br>543<br>544<br>545<br>546<br>547<br>548<br>549<br>550<br>551<br>552<br>553<br>554<br>555<br>556<br>557<br>558<br>559<br>560<br>561<br>562<br>563<br>564<br>565<br>566<br>567<br>568<br>569<br>570<br>571<br>572<br>573<br>574<br>575<br>576<br>577<br>578<br>579<br>580<br>581<br>582<br>583<br>584<br>585<br>586<br>587<br>588<br>589<br>590<br>591<br>592<br>593<br>594<br>595<br>596<br>597<br>598<br>599<br>600<br>601<br>602<br>603<br>604<br>605<br>606<br> <br>def register_reply(<br> self,<br> trigger: Union[type[Agent], str, Agent, Callable[[Agent], bool], list],<br> reply_func: Callable,<br> position: int = 0,<br> config: Optional[Any] = None,<br> reset_config: Optional[Callable[..., Any]] = None,<br> *,<br> ignore_async_in_sync_chat: bool = False,<br> remove_other_reply_funcs: bool = False,<br>):<br> """Register a reply function.<br> The reply function will be called when the trigger matches the sender.<br> The function registered later will be checked earlier by default.<br> To change the order, set the position to a positive integer.<br> Both sync and async reply functions can be registered. The sync reply function will be triggered<br> from both sync and async chats. However, an async reply function will only be triggered from async<br> chats (initiated with `ConversableAgent.a_initiate_chat`). If an `async` reply function is registered<br> and a chat is initialized with a sync function, `ignore_async_in_sync_chat` determines the behaviour as follows:<br> if `ignore_async_in_sync_chat` is set to `False` (default value), an exception will be raised, and<br> if `ignore_async_in_sync_chat` is set to `True`, the reply function will be ignored.<br> Args:<br> trigger (Agent class, str, Agent instance, callable, or list): the trigger.<br> If a class is provided, the reply function will be called when the sender is an instance of the class.<br> If a string is provided, the reply function will be called when the sender's name matches the string.<br> If an agent instance is provided, the reply function will be called when the sender is the agent instance.<br> If a callable is provided, the reply function will be called when the callable returns True.<br> If a list is provided, the reply function will be called when any of the triggers in the list is activated.<br> If None is provided, the reply function will be called only when the sender is None.<br> 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`.<br> reply_func (Callable): the reply function.<br> The function takes a recipient agent, a list of messages, a sender agent and a config as input and returns a reply message.<br> ```python<br> def reply_func(<br> recipient: ConversableAgent,<br> messages: Optional[List[Dict]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br> ) -> Tuple[bool, Union[str, Dict, None]]:<br> ```<br> position (int): the position of the reply function in the reply function list.<br> The function registered later will be checked earlier by default.<br> To change the order, set the position to a positive integer.<br> config (Any): the config to be passed to the reply function.<br> When an agent is reset, the config will be reset to the original value.<br> reset_config (Callable): the function to reset the config.<br> The function returns None. Signature: ```def reset_config(config: Any)```<br> ignore_async_in_sync_chat (bool): whether to ignore the async reply function in sync chats. If `False`, an exception<br> will be raised if an async reply function is registered and a chat is initialized with a sync<br> function.<br> remove_other_reply_funcs (bool): whether to remove other reply functions when registering this reply function.<br> """<br> if not isinstance(trigger, (type, str, Agent, Callable, list)):<br> raise ValueError("trigger must be a class, a string, an agent, a callable or a list.")<br> if remove_other_reply_funcs:<br> self._reply_func_list.clear()<br> self._reply_func_list.insert(<br> position,<br> {<br> "trigger": trigger,<br> "reply_func": reply_func,<br> "config": copy.copy(config),<br> "init_config": config,<br> "reset_config": reset_config,<br> "ignore_async_in_sync_chat": ignore_async_in_sync_chat and inspect.iscoroutinefunction(reply_func),<br> },<br> )<br>

``replace_reply_func #

replace_reply_func(old_reply_func, new_reply_func)

Replace a registered reply function with a new one.

PARAMETER DESCRIPTION
old_reply_func the old reply function to be replaced.
TYPE:Callable
new_reply_func the new reply function to replace the old one.
TYPE:Callable

Source code in autogen/agentchat/conversable_agent.py

<br>608<br>609<br>610<br>611<br>612<br>613<br>614<br>615<br>616<br>617<br> <br>def replace_reply_func(self, old_reply_func: Callable, new_reply_func: Callable):<br> """Replace a registered reply function with a new one.<br> Args:<br> old_reply_func (Callable): the old reply function to be replaced.<br> new_reply_func (Callable): the new reply function to replace the old one.<br> """<br> for f in self._reply_func_list:<br> if f["reply_func"] == old_reply_func:<br> f["reply_func"] = new_reply_func<br>

``register_nested_chats #

register_nested_chats(chat_queue, trigger, reply_func_from_nested_chats='summary_from_nested_chats', position=2, use_async=None, **kwargs)

Register a nested chat reply function.

PARAMETER DESCRIPTION
chat_queue 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.
TYPE:list
trigger refer to register_reply for details.
TYPE:Agent class, str, Agent instance, callable, or list
reply_func_from_nested_chats the reply function for the nested chat. 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. Default to "summary_from_nested_chats", which corresponds to a built-in reply function that get summary from the nested chat_queue.
<br>def reply_func_from_nested_chats(<br> chat_queue: List[Dict],<br> recipient: ConversableAgent,<br> messages: Optional[List[Dict]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> Tuple[bool, Union[str, Dict, None]]:<br>
TYPE:(Callable, str)DEFAULT:'summary_from_nested_chats'
position 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.
TYPE:intDEFAULT:2
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.
TYPE:Union[bool, None]DEFAULT:None
kwargs Ref to register_reply for details.
TYPE:AnyDEFAULT:{}

Source code in autogen/agentchat/conversable_agent.py

<br>877<br>878<br>879<br>880<br>881<br>882<br>883<br>884<br>885<br>886<br>887<br>888<br>889<br>890<br>891<br>892<br>893<br>894<br>895<br>896<br>897<br>898<br>899<br>900<br>901<br>902<br>903<br>904<br>905<br>906<br>907<br>908<br>909<br>910<br>911<br>912<br>913<br>914<br>915<br>916<br>917<br>918<br>919<br>920<br>921<br>922<br>923<br>924<br>925<br>926<br>927<br>928<br>929<br>930<br>931<br>932<br>933<br>934<br>935<br>936<br>937<br>938<br>939<br>940<br>941<br>942<br>943<br> <br>def register_nested_chats(<br> self,<br> chat_queue: list[dict[str, Any]],<br> trigger: Union[type[Agent], str, Agent, Callable[[Agent], bool], list],<br> reply_func_from_nested_chats: Union[str, Callable[..., Any]] = "summary_from_nested_chats",<br> position: int = 2,<br> use_async: Union[bool, None] = None,<br> **kwargs: Any,<br>) -> None:<br> """Register a nested chat reply function.<br> Args:<br> 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.<br> trigger (Agent class, str, Agent instance, callable, or list): refer to `register_reply` for details.<br> reply_func_from_nested_chats (Callable, str): the reply function for the nested chat.<br> 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.<br> Default to "summary_from_nested_chats", which corresponds to a built-in reply function that get summary from the nested chat_queue.<br> ```python<br> def reply_func_from_nested_chats(<br> chat_queue: List[Dict],<br> recipient: ConversableAgent,<br> messages: Optional[List[Dict]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br> ) -> Tuple[bool, Union[str, Dict, None]]:<br> ```<br> 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.<br> 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.<br> kwargs: Ref to `register_reply` for details.<br> """<br> if use_async:<br> for chat in chat_queue:<br> if chat.get("chat_id") is None:<br> raise ValueError("chat_id is required for async nested chats")<br> if use_async:<br> if reply_func_from_nested_chats == "summary_from_nested_chats":<br> reply_func_from_nested_chats = self._a_summary_from_nested_chats<br> if not callable(reply_func_from_nested_chats) or not inspect.iscoroutinefunction(<br> reply_func_from_nested_chats<br> ):<br> raise ValueError("reply_func_from_nested_chats must be a callable and a coroutine")<br> async def wrapped_reply_func(recipient, messages=None, sender=None, config=None):<br> return await reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)<br> else:<br> if reply_func_from_nested_chats == "summary_from_nested_chats":<br> reply_func_from_nested_chats = self._summary_from_nested_chats<br> if not callable(reply_func_from_nested_chats):<br> raise ValueError("reply_func_from_nested_chats must be a callable")<br> def wrapped_reply_func(recipient, messages=None, sender=None, config=None):<br> return reply_func_from_nested_chats(chat_queue, recipient, messages, sender, config)<br> functools.update_wrapper(wrapped_reply_func, reply_func_from_nested_chats)<br> self.register_reply(<br> trigger,<br> wrapped_reply_func,<br> position,<br> kwargs.get("config"),<br> kwargs.get("reset_config"),<br> ignore_async_in_sync_chat=(<br> not use_async if use_async is not None else kwargs.get("ignore_async_in_sync_chat")<br> ),<br> )<br>

``update_max_consecutive_auto_reply #

update_max_consecutive_auto_reply(value, sender=None)

Update the maximum number of consecutive auto replies.

PARAMETER DESCRIPTION
value the maximum number of consecutive auto replies.
TYPE:int
sender when the sender is provided, only update the max_consecutive_auto_reply for that sender.
TYPE:AgentDEFAULT:None

Source code in autogen/agentchat/conversable_agent.py

<br>958<br>959<br>960<br>961<br>962<br>963<br>964<br>965<br>966<br>967<br>968<br>969<br>970<br> <br>def update_max_consecutive_auto_reply(self, value: int, sender: Optional[Agent] = None):<br> """Update the maximum number of consecutive auto replies.<br> Args:<br> value (int): the maximum number of consecutive auto replies.<br> sender (Agent): when the sender is provided, only update the max_consecutive_auto_reply for that sender.<br> """<br> if sender is None:<br> self._max_consecutive_auto_reply = value<br> for k in self._max_consecutive_auto_reply_dict:<br> self._max_consecutive_auto_reply_dict[k] = value<br> else:<br> self._max_consecutive_auto_reply_dict[sender] = value<br>

``max_consecutive_auto_reply #

max_consecutive_auto_reply(sender=None)

The maximum number of consecutive auto replies.

Source code in autogen/agentchat/conversable_agent.py

<br>972<br>973<br>974<br> <br>def max_consecutive_auto_reply(self, sender: Optional[Agent] = None) -> int:<br> """The maximum number of consecutive auto replies."""<br> return self._max_consecutive_auto_reply if sender is None else self._max_consecutive_auto_reply_dict[sender]<br>

``chat_messages_for_summary #

chat_messages_for_summary(agent)

A list of messages as a conversation to summarize.

Source code in autogen/agentchat/conversable_agent.py

<br>981<br>982<br>983<br> <br>def chat_messages_for_summary(self, agent: Agent) -> list[dict[str, Any]]:<br> """A list of messages as a conversation to summarize."""<br> return self._oai_messages[agent]<br>

``last_message #

last_message(agent=None)

The last message exchanged with the agent.

PARAMETER DESCRIPTION
agent The agent in the conversation. If None and more than one agent's conversations are found, an error will be raised. If None and only one conversation is found, the last message of the only conversation will be returned.
TYPE:AgentDEFAULT:None
RETURNS DESCRIPTION
Optional[dict[str, Any]] The last message exchanged with the agent.

Source code in autogen/agentchat/conversable_agent.py

<br> 985<br> 986<br> 987<br> 988<br> 989<br> 990<br> 991<br> 992<br> 993<br> 994<br> 995<br> 996<br> 997<br> 998<br> 999<br>1000<br>1001<br>1002<br>1003<br>1004<br>1005<br>1006<br>1007<br>1008<br> <br>def last_message(self, agent: Optional[Agent] = None) -> Optional[dict[str, Any]]:<br> """The last message exchanged with the agent.<br> Args:<br> agent (Agent): The agent in the conversation.<br> If None and more than one agent's conversations are found, an error will be raised.<br> If None and only one conversation is found, the last message of the only conversation will be returned.<br> Returns:<br> The last message exchanged with the agent.<br> """<br> if agent is None:<br> n_conversations = len(self._oai_messages)<br> if n_conversations == 0:<br> return None<br> if n_conversations == 1:<br> for conversation in self._oai_messages.values():<br> return conversation[-1]<br> raise ValueError("More than one conversation is found. Please specify the sender to get the last message.")<br> if agent not in self._oai_messages:<br> raise KeyError(<br> f"The agent '{agent.name}' is not present in any conversation. No history available for this agent."<br> )<br> return self._oai_messages[agent][-1]<br>

``initiate_chat #

initiate_chat(recipient, clear_history=True, silent=False, cache=None, max_turns=None, summary_method=DEFAULT_SUMMARY_METHOD, summary_args={}, message=None, **kwargs)

Initiate a chat with the recipient agent.

Reset the consecutive auto reply counter. If clear_history is True, the chat history with the recipient agent will be cleared.

PARAMETER DESCRIPTION
recipient the recipient agent.
TYPE:ConversableAgent
clear_history whether to clear the chat history with the agent. Default is True.
TYPE:boolDEFAULT:True
silent (Experimental) whether to print the messages for this conversation. Default is False.
TYPE:bool or NoneDEFAULT:False
cache the cache client to be used for this conversation. Default is None.
TYPE:AbstractCache or NoneDEFAULT:None
max_turns 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 max_consecutive_auto_reply which is the maximum number of consecutive auto replies; and it is also different from max_rounds in GroupChat which is the maximum number of rounds in a group chat session. If max_turns is set to None, the chat will continue until a termination condition is met. Default is None.
TYPE:int or NoneDEFAULT:None
summary_method a method to get a summary from the chat. Default is DEFAULT_SUMMARY_METHOD, i.e., "last_msg". Supported strings are "last_msg" and "reflection_with_llm": - when set to "last_msg", it returns the last message of the dialog as the summary. - when set to "reflection_with_llm", it returns a summary extracted using an llm client. llm_config must be set in either the recipient or sender.
A callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g.,
<br>def my_summary_method(<br> sender: ConversableAgent,<br> recipient: ConversableAgent,<br> summary_args: dict,<br>):<br> return recipient.last_message(sender)["content"]<br>
TYPE:str or callableDEFAULT:DEFAULT_SUMMARY_METHOD
summary_args a dictionary of arguments to be passed to the summary_method. One example key is "summary_prompt", and value is a string of text used to prompt a LLM-based agent (the sender or recipient agent) to reflect on the conversation and extract a summary when summary_method is "reflection_with_llm". 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." Another available key is "summary_role", which is the role of the message sent to the agent in charge of summarizing. Default is "system".
TYPE:dictDEFAULT:{}
message the initial message to be sent to the recipient. Needs to be provided. Otherwise, input() will be called to get the initial message. - 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. If dict, it may contain the following reserved fields (either content or tool_calls need to be provided).
<br> 1. "content": content of the message, can be None.<br> 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")<br> 3. "tool_calls": a list of dictionaries containing the function name and arguments.<br> 4. "role": role of the message, can be "assistant", "user", "function".<br> This field is only needed to distinguish between "function" or "assistant"/"user".<br> 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.<br> 6. "context" (dict): the context of the message, which will be passed to<br> `OpenAIWrapper.create`.<br>
- If a callable is provided, it will be called to get the initial message in the form of a string or a dict. If the returned type is dict, it may contain the reserved fields mentioned above.

Example of a callable message (returning a string):



<br>def my_message(<br> sender: ConversableAgent, recipient: ConversableAgent, context: dict<br>) -> Union[str, Dict]:<br> carryover = context.get("carryover", "")<br> if isinstance(message, list):<br> carryover = carryover[-1]<br> final_msg = "Write a blogpost." + "\nContext: \n" + carryover<br> return final_msg<br>



Example of a callable message (returning a dict):



<br>def my_message(<br> sender: ConversableAgent, recipient: ConversableAgent, context: dict<br>) -> Union[str, Dict]:<br> final_msg = {}<br> carryover = context.get("carryover", "")<br> if isinstance(message, list):<br> carryover = carryover[-1]<br> final_msg["content"] = "Write a blogpost." + "\nContext: \n" + carryover<br> final_msg["context"] = {"prefix": "Today I feel"}<br> return final_msg<br>

TYPE:(str, dict or Callable)DEFAULT:None
**kwargs any additional information. It has the following reserved fields: - "carryover": a string or a list of string to specify the carryover information to be passed to this chat. 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 message in generate_init_message. - "verbose": a boolean to specify whether to print the message and carryover in a chat. Default is False.
TYPE:AnyDEFAULT:{}
RAISES DESCRIPTION
RuntimeError if any async reply functions are registered and not ignored in sync chat.
RETURNS DESCRIPTION
ChatResult an ChatResult object.
TYPE:ChatResult

Source code in autogen/agentchat/conversable_agent.py

<br>1344<br>1345<br>1346<br>1347<br>1348<br>1349<br>1350<br>1351<br>1352<br>1353<br>1354<br>1355<br>1356<br>1357<br>1358<br>1359<br>1360<br>1361<br>1362<br>1363<br>1364<br>1365<br>1366<br>1367<br>1368<br>1369<br>1370<br>1371<br>1372<br>1373<br>1374<br>1375<br>1376<br>1377<br>1378<br>1379<br>1380<br>1381<br>1382<br>1383<br>1384<br>1385<br>1386<br>1387<br>1388<br>1389<br>1390<br>1391<br>1392<br>1393<br>1394<br>1395<br>1396<br>1397<br>1398<br>1399<br>1400<br>1401<br>1402<br>1403<br>1404<br>1405<br>1406<br>1407<br>1408<br>1409<br>1410<br>1411<br>1412<br>1413<br>1414<br>1415<br>1416<br>1417<br>1418<br>1419<br>1420<br>1421<br>1422<br>1423<br>1424<br>1425<br>1426<br>1427<br>1428<br>1429<br>1430<br>1431<br>1432<br>1433<br>1434<br>1435<br>1436<br>1437<br>1438<br>1439<br>1440<br>1441<br>1442<br>1443<br>1444<br>1445<br>1446<br>1447<br>1448<br>1449<br>1450<br>1451<br>1452<br>1453<br>1454<br>1455<br>1456<br>1457<br>1458<br>1459<br>1460<br>1461<br>1462<br>1463<br>1464<br>1465<br>1466<br>1467<br>1468<br>1469<br>1470<br>1471<br>1472<br>1473<br>1474<br>1475<br>1476<br>1477<br>1478<br>1479<br>1480<br>1481<br>1482<br>1483<br>1484<br>1485<br>1486<br>1487<br>1488<br>1489<br>1490<br>1491<br>1492<br>1493<br>1494<br>1495<br>1496<br>1497<br> <br>def initiate_chat(<br> self,<br> recipient: "ConversableAgent",<br> clear_history: bool = True,<br> silent: Optional[bool] = False,<br> cache: Optional[AbstractCache] = None,<br> max_turns: Optional[int] = None,<br> summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,<br> summary_args: Optional[dict[str, Any]] = {},<br> message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,<br> **kwargs: Any,<br>) -> ChatResult:<br> """Initiate a chat with the recipient agent.<br> Reset the consecutive auto reply counter.<br> If `clear_history` is True, the chat history with the recipient agent will be cleared.<br> Args:<br> recipient: the recipient agent.<br> clear_history (bool): whether to clear the chat history with the agent. Default is True.<br> silent (bool or None): (Experimental) whether to print the messages for this conversation. Default is False.<br> cache (AbstractCache or None): the cache client to be used for this conversation. Default is None.<br> 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<br> `max_consecutive_auto_reply` which is the maximum number of consecutive auto replies; and it is also different from `max_rounds` in GroupChat which is the maximum number of rounds in a group chat session.<br> If max_turns is set to None, the chat will continue until a termination condition is met. Default is None.<br> summary_method (str or callable): a method to get a summary from the chat. Default is DEFAULT_SUMMARY_METHOD, i.e., "last_msg".<br> Supported strings are "last_msg" and "reflection_with_llm":<br> - when set to "last_msg", it returns the last message of the dialog as the summary.<br> - when set to "reflection_with_llm", it returns a summary extracted using an llm client.<br> `llm_config` must be set in either the recipient or sender.<br> A callable summary_method should take the recipient and sender agent in a chat as input and return a string of summary. E.g.,<br> ```python<br> def my_summary_method(<br> sender: ConversableAgent,<br> recipient: ConversableAgent,<br> summary_args: dict,<br> ):<br> return recipient.last_message(sender)["content"]<br> ```<br> summary_args (dict): a dictionary of arguments to be passed to the summary_method.<br> One example key is "summary_prompt", and value is a string of text used to prompt a LLM-based agent (the sender or recipient agent) to reflect<br> on the conversation and extract a summary when summary_method is "reflection_with_llm".<br> 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."<br> Another available key is "summary_role", which is the role of the message sent to the agent in charge of summarizing. Default is "system".<br> 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.<br> - 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.<br> If dict, it may contain the following reserved fields (either content or tool_calls need to be provided).<br> 1. "content": content of the message, can be None.<br> 2. "function_call": a dictionary containing the function name and arguments. (deprecated in favor of "tool_calls")<br> 3. "tool_calls": a list of dictionaries containing the function name and arguments.<br> 4. "role": role of the message, can be "assistant", "user", "function".<br> This field is only needed to distinguish between "function" or "assistant"/"user".<br> 5. "name": In most cases, this field is not needed. When the role is "function", this field is needed to indicate the function name.<br> 6. "context" (dict): the context of the message, which will be passed to<br> `OpenAIWrapper.create`.<br> - If a callable is provided, it will be called to get the initial message in the form of a string or a dict.<br> If the returned type is dict, it may contain the reserved fields mentioned above.<br> Example of a callable message (returning a string):<br> ```python<br> def my_message(<br> sender: ConversableAgent, recipient: ConversableAgent, context: dict<br> ) -> Union[str, Dict]:<br> carryover = context.get("carryover", "")<br> if isinstance(message, list):<br> carryover = carryover[-1]<br> final_msg = "Write a blogpost." + "\\nContext: \\n" + carryover<br> return final_msg<br> ```<br> Example of a callable message (returning a dict):<br> ```python<br> def my_message(<br> sender: ConversableAgent, recipient: ConversableAgent, context: dict<br> ) -> Union[str, Dict]:<br> final_msg = {}<br> carryover = context.get("carryover", "")<br> if isinstance(message, list):<br> carryover = carryover[-1]<br> final_msg["content"] = "Write a blogpost." + "\\nContext: \\n" + carryover<br> final_msg["context"] = {"prefix": "Today I feel"}<br> return final_msg<br> ```<br> **kwargs: any additional information. It has the following reserved fields:<br> - "carryover": a string or a list of string to specify the carryover information to be passed to this chat.<br> 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<br> message in `generate_init_message`.<br> - "verbose": a boolean to specify whether to print the message and carryover in a chat. Default is False.<br> Raises:<br> RuntimeError: if any async reply functions are registered and not ignored in sync chat.<br> Returns:<br> ChatResult: an ChatResult object.<br> """<br> iostream = IOStream.get_default()<br> cache = Cache.get_current_cache(cache)<br> _chat_info = locals().copy()<br> _chat_info["sender"] = self<br> consolidate_chat_info(_chat_info, uniform_sender=self)<br> for agent in [self, recipient]:<br> agent._raise_exception_on_async_reply_functions()<br> agent.previous_cache = agent.client_cache<br> agent.client_cache = cache<br> if isinstance(max_turns, int):<br> self._prepare_chat(recipient, clear_history, reply_at_receive=False)<br> for i in range(max_turns):<br> # check recipient max consecutive auto reply limit<br> if self._consecutive_auto_reply_counter[recipient] >= recipient._max_consecutive_auto_reply:<br> break<br> if i == 0:<br> if isinstance(message, Callable):<br> msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)<br> else:<br> msg2send = self.generate_init_message(message, **kwargs)<br> else:<br> msg2send = self.generate_reply(messages=self.chat_messages[recipient], sender=recipient)<br> if msg2send is None:<br> break<br> self.send(msg2send, recipient, request_reply=True, silent=silent)<br> else: # No breaks in the for loop, so we have reached max turns<br> iostream.send(TerminationEvent(termination_reason=f"Maximum turns ({max_turns}) reached"))<br> else:<br> self._prepare_chat(recipient, clear_history)<br> if isinstance(message, Callable):<br> msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)<br> else:<br> msg2send = self.generate_init_message(message, **kwargs)<br> self.send(msg2send, recipient, silent=silent)<br> summary = self._summarize_chat(<br> summary_method,<br> summary_args,<br> recipient,<br> cache=cache,<br> )<br> for agent in [self, recipient]:<br> agent.client_cache = agent.previous_cache<br> agent.previous_cache = None<br> chat_result = ChatResult(<br> chat_history=self.chat_messages[recipient],<br> summary=summary,<br> cost=gather_usage_summary([self, recipient]),<br> human_input=self._human_input,<br> )<br> return chat_result<br>

``run #

run(recipient=None, clear_history=True, silent=False, cache=None, max_turns=None, summary_method=DEFAULT_SUMMARY_METHOD, summary_args={}, message=None, executor_kwargs=None, tools=None, user_input=False, msg_to='agent', **kwargs)

Source code in autogen/agentchat/conversable_agent.py

<br>1499<br>1500<br>1501<br>1502<br>1503<br>1504<br>1505<br>1506<br>1507<br>1508<br>1509<br>1510<br>1511<br>1512<br>1513<br>1514<br>1515<br>1516<br>1517<br>1518<br>1519<br>1520<br>1521<br>1522<br>1523<br>1524<br>1525<br>1526<br>1527<br>1528<br>1529<br>1530<br>1531<br>1532<br>1533<br>1534<br>1535<br>1536<br>1537<br>1538<br>1539<br>1540<br>1541<br>1542<br>1543<br>1544<br>1545<br>1546<br>1547<br>1548<br>1549<br>1550<br>1551<br>1552<br>1553<br>1554<br>1555<br>1556<br>1557<br>1558<br>1559<br>1560<br>1561<br>1562<br>1563<br>1564<br>1565<br>1566<br>1567<br>1568<br>1569<br>1570<br>1571<br>1572<br>1573<br>1574<br>1575<br>1576<br>1577<br>1578<br>1579<br>1580<br>1581<br>1582<br>1583<br>1584<br>1585<br>1586<br>1587<br>1588<br>1589<br>1590<br>1591<br>1592<br>1593<br>1594<br>1595<br>1596<br>1597<br>1598<br>1599<br>1600<br>1601<br>1602<br>1603<br>1604<br>1605<br>1606<br>1607<br> <br>def run(<br> self,<br> recipient: Optional["ConversableAgent"] = None,<br> clear_history: bool = True,<br> silent: Optional[bool] = False,<br> cache: Optional[AbstractCache] = None,<br> max_turns: Optional[int] = None,<br> summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,<br> summary_args: Optional[dict[str, Any]] = {},<br> message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,<br> executor_kwargs: Optional[dict[str, Any]] = None,<br> tools: Optional[Union[Tool, Iterable[Tool]]] = None,<br> user_input: Optional[bool] = False,<br> msg_to: Optional[str] = "agent",<br> **kwargs: Any,<br>) -> RunResponseProtocol:<br> iostream = ThreadIOStream()<br> agents = [self, recipient] if recipient else [self]<br> response = RunResponse(iostream, agents=agents)<br> if recipient is None:<br> def initiate_chat(<br> self=self,<br> iostream: ThreadIOStream = iostream,<br> response: RunResponse = response,<br> ) -> None:<br> with (<br> IOStream.set_default(iostream),<br> self._create_or_get_executor(<br> executor_kwargs=executor_kwargs,<br> tools=tools,<br> agent_name="user",<br> agent_human_input_mode="ALWAYS" if user_input else "NEVER",<br> ) as executor,<br> ):<br> try:<br> if msg_to == "agent":<br> chat_result = executor.initiate_chat(<br> self,<br> message=message,<br> clear_history=clear_history,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> )<br> else:<br> chat_result = self.initiate_chat(<br> executor,<br> message=message,<br> clear_history=clear_history,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> )<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_result.chat_history,<br> summary=chat_result.summary,<br> cost=chat_result.cost,<br> last_speaker=self.name,<br> )<br> )<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> else:<br> def initiate_chat(<br> self=self,<br> iostream: ThreadIOStream = iostream,<br> response: RunResponse = response,<br> ) -> None:<br> with IOStream.set_default(iostream): # type: ignore[arg-type]<br> try:<br> chat_result = self.initiate_chat(<br> recipient,<br> clear_history=clear_history,<br> silent=silent,<br> cache=cache,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> summary_args=summary_args,<br> message=message,<br> **kwargs,<br> )<br> response._summary = chat_result.summary<br> response._messages = chat_result.chat_history<br> _last_speaker = recipient if chat_result.chat_history[-1]["name"] == recipient.name else self<br> if hasattr(recipient, "last_speaker"):<br> _last_speaker = recipient.last_speaker<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_result.chat_history,<br> summary=chat_result.summary,<br> cost=chat_result.cost,<br> last_speaker=_last_speaker.name,<br> )<br> )<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> threading.Thread(<br> target=initiate_chat,<br> ).start()<br> return response<br>

``a_initiate_chatasync#

a_initiate_chat(recipient, clear_history=True, silent=False, cache=None, max_turns=None, summary_method=DEFAULT_SUMMARY_METHOD, summary_args={}, message=None, **kwargs)

(async) Initiate a chat with the recipient agent.

Reset the consecutive auto reply counter. If clear_history is True, the chat history with the recipient agent will be cleared. a_generate_init_message is called to generate the initial message for the agent.

Args: Please refer to initiate_chat.

RETURNS DESCRIPTION
ChatResult an ChatResult object.
TYPE:ChatResult

Source code in autogen/agentchat/conversable_agent.py

<br>1609<br>1610<br>1611<br>1612<br>1613<br>1614<br>1615<br>1616<br>1617<br>1618<br>1619<br>1620<br>1621<br>1622<br>1623<br>1624<br>1625<br>1626<br>1627<br>1628<br>1629<br>1630<br>1631<br>1632<br>1633<br>1634<br>1635<br>1636<br>1637<br>1638<br>1639<br>1640<br>1641<br>1642<br>1643<br>1644<br>1645<br>1646<br>1647<br>1648<br>1649<br>1650<br>1651<br>1652<br>1653<br>1654<br>1655<br>1656<br>1657<br>1658<br>1659<br>1660<br>1661<br>1662<br>1663<br>1664<br>1665<br>1666<br>1667<br>1668<br>1669<br>1670<br>1671<br>1672<br>1673<br>1674<br>1675<br>1676<br>1677<br> <br>async def a_initiate_chat(<br> self,<br> recipient: "ConversableAgent",<br> clear_history: bool = True,<br> silent: Optional[bool] = False,<br> cache: Optional[AbstractCache] = None,<br> max_turns: Optional[int] = None,<br> summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,<br> summary_args: Optional[dict[str, Any]] = {},<br> message: Optional[Union[str, Callable[..., Any]]] = None,<br> **kwargs: Any,<br>) -> ChatResult:<br> """(async) Initiate a chat with the recipient agent.<br> Reset the consecutive auto reply counter.<br> If `clear_history` is True, the chat history with the recipient agent will be cleared.<br> `a_generate_init_message` is called to generate the initial message for the agent.<br> Args: Please refer to `initiate_chat`.<br> Returns:<br> ChatResult: an ChatResult object.<br> """<br> iostream = IOStream.get_default()<br> _chat_info = locals().copy()<br> _chat_info["sender"] = self<br> consolidate_chat_info(_chat_info, uniform_sender=self)<br> for agent in [self, recipient]:<br> agent.previous_cache = agent.client_cache<br> agent.client_cache = cache<br> if isinstance(max_turns, int):<br> self._prepare_chat(recipient, clear_history, reply_at_receive=False)<br> for _ in range(max_turns):<br> if _ == 0:<br> if isinstance(message, Callable):<br> msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)<br> else:<br> msg2send = await self.a_generate_init_message(message, **kwargs)<br> else:<br> msg2send = await self.a_generate_reply(messages=self.chat_messages[recipient], sender=recipient)<br> if msg2send is None:<br> break<br> await self.a_send(msg2send, recipient, request_reply=True, silent=silent)<br> else: # No breaks in the for loop, so we have reached max turns<br> iostream.send(TerminationEvent(termination_reason=f"Maximum turns ({max_turns}) reached"))<br> else:<br> self._prepare_chat(recipient, clear_history)<br> if isinstance(message, Callable):<br> msg2send = message(_chat_info["sender"], _chat_info["recipient"], kwargs)<br> else:<br> msg2send = await self.a_generate_init_message(message, **kwargs)<br> await self.a_send(msg2send, recipient, silent=silent)<br> summary = self._summarize_chat(<br> summary_method,<br> summary_args,<br> recipient,<br> cache=cache,<br> )<br> for agent in [self, recipient]:<br> agent.client_cache = agent.previous_cache<br> agent.previous_cache = None<br> chat_result = ChatResult(<br> chat_history=self.chat_messages[recipient],<br> summary=summary,<br> cost=gather_usage_summary([self, recipient]),<br> human_input=self._human_input,<br> )<br> return chat_result<br>

``a_runasync#

a_run(recipient=None, clear_history=True, silent=False, cache=None, max_turns=None, summary_method=DEFAULT_SUMMARY_METHOD, summary_args={}, message=None, executor_kwargs=None, tools=None, user_input=False, msg_to='agent', **kwargs)

Source code in autogen/agentchat/conversable_agent.py

<br>1679<br>1680<br>1681<br>1682<br>1683<br>1684<br>1685<br>1686<br>1687<br>1688<br>1689<br>1690<br>1691<br>1692<br>1693<br>1694<br>1695<br>1696<br>1697<br>1698<br>1699<br>1700<br>1701<br>1702<br>1703<br>1704<br>1705<br>1706<br>1707<br>1708<br>1709<br>1710<br>1711<br>1712<br>1713<br>1714<br>1715<br>1716<br>1717<br>1718<br>1719<br>1720<br>1721<br>1722<br>1723<br>1724<br>1725<br>1726<br>1727<br>1728<br>1729<br>1730<br>1731<br>1732<br>1733<br>1734<br>1735<br>1736<br>1737<br>1738<br>1739<br>1740<br>1741<br>1742<br>1743<br>1744<br>1745<br>1746<br>1747<br>1748<br>1749<br>1750<br>1751<br>1752<br>1753<br>1754<br>1755<br>1756<br>1757<br>1758<br>1759<br>1760<br>1761<br>1762<br>1763<br>1764<br>1765<br>1766<br>1767<br>1768<br>1769<br>1770<br>1771<br>1772<br>1773<br>1774<br>1775<br>1776<br>1777<br>1778<br>1779<br>1780<br>1781<br>1782<br>1783<br> <br>async def a_run(<br> self,<br> recipient: Optional["ConversableAgent"] = None,<br> clear_history: bool = True,<br> silent: Optional[bool] = False,<br> cache: Optional[AbstractCache] = None,<br> max_turns: Optional[int] = None,<br> summary_method: Optional[Union[str, Callable[..., Any]]] = DEFAULT_SUMMARY_METHOD,<br> summary_args: Optional[dict[str, Any]] = {},<br> message: Optional[Union[dict[str, Any], str, Callable[..., Any]]] = None,<br> executor_kwargs: Optional[dict[str, Any]] = None,<br> tools: Optional[Union[Tool, Iterable[Tool]]] = None,<br> user_input: Optional[bool] = False,<br> msg_to: Optional[str] = "agent",<br> **kwargs: Any,<br>) -> AsyncRunResponseProtocol:<br> iostream = AsyncThreadIOStream()<br> agents = [self, recipient] if recipient else [self]<br> response = AsyncRunResponse(iostream, agents=agents)<br> if recipient is None:<br> async def initiate_chat(<br> self=self,<br> iostream: AsyncThreadIOStream = iostream,<br> response: AsyncRunResponse = response,<br> ) -> None:<br> with (<br> IOStream.set_default(iostream),<br> self._create_or_get_executor(<br> executor_kwargs=executor_kwargs,<br> tools=tools,<br> agent_name="user",<br> agent_human_input_mode="ALWAYS" if user_input else "NEVER",<br> ) as executor,<br> ):<br> try:<br> if msg_to == "agent":<br> chat_result = await executor.a_initiate_chat(<br> self,<br> message=message,<br> clear_history=clear_history,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> )<br> else:<br> chat_result = await self.a_initiate_chat(<br> executor,<br> message=message,<br> clear_history=clear_history,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> )<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_result.chat_history,<br> summary=chat_result.summary,<br> cost=chat_result.cost,<br> last_speaker=self.name,<br> )<br> )<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> else:<br> async def initiate_chat(<br> self=self,<br> iostream: AsyncThreadIOStream = iostream,<br> response: AsyncRunResponse = response,<br> ) -> None:<br> with IOStream.set_default(iostream): # type: ignore[arg-type]<br> try:<br> chat_result = await self.a_initiate_chat(<br> recipient,<br> clear_history=clear_history,<br> silent=silent,<br> cache=cache,<br> max_turns=max_turns,<br> summary_method=summary_method,<br> summary_args=summary_args,<br> message=message,<br> **kwargs,<br> )<br> last_speaker = recipient if chat_result.chat_history[-1]["name"] == recipient.name else self<br> if hasattr(recipient, "last_speaker"):<br> last_speaker = recipient.last_speaker<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_result.chat_history,<br> summary=chat_result.summary,<br> cost=chat_result.cost,<br> last_speaker=last_speaker.name,<br> )<br> )<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> asyncio.create_task(initiate_chat())<br> return response<br>

``initiate_chats #

initiate_chats(chat_queue)

(Experimental) Initiate chats with multiple agents.

PARAMETER DESCRIPTION
chat_queue a list of dictionaries containing the information of the chats. Each dictionary should contain the input arguments for initiate_chat
TYPE:List[Dict]

Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.

Source code in autogen/agentchat/conversable_agent.py

<br>1926<br>1927<br>1928<br>1929<br>1930<br>1931<br>1932<br>1933<br>1934<br>1935<br>1936<br>1937<br>1938<br> <br>def initiate_chats(self, chat_queue: list[dict[str, Any]]) -> list[ChatResult]:<br> """(Experimental) Initiate chats with multiple agents.<br> Args:<br> chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.<br> Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)<br> Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.<br> """<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> self._finished_chats = initiate_chats(_chat_queue)<br> return self._finished_chats<br>

``sequential_run #

sequential_run(chat_queue)

(Experimental) Initiate chats with multiple agents sequentially.

PARAMETER DESCRIPTION
chat_queue a list of dictionaries containing the information of the chats. Each dictionary should contain the input arguments for initiate_chat
TYPE:List[Dict]

Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.

Source code in autogen/agentchat/conversable_agent.py

<br>1940<br>1941<br>1942<br>1943<br>1944<br>1945<br>1946<br>1947<br>1948<br>1949<br>1950<br>1951<br>1952<br>1953<br>1954<br>1955<br>1956<br>1957<br>1958<br>1959<br>1960<br>1961<br>1962<br>1963<br>1964<br>1965<br>1966<br>1967<br>1968<br>1969<br>1970<br>1971<br>1972<br>1973<br>1974<br>1975<br>1976<br>1977<br>1978<br>1979<br>1980<br>1981<br>1982<br>1983<br>1984<br>1985<br>1986<br>1987<br>1988<br>1989<br>1990<br>1991<br>1992<br>1993<br>1994<br>1995<br>1996<br>1997<br>1998<br>1999<br>2000<br>2001<br>2002<br>2003<br> <br>def sequential_run(<br> self,<br> chat_queue: list[dict[str, Any]],<br>) -> list[RunResponseProtocol]:<br> """(Experimental) Initiate chats with multiple agents sequentially.<br> Args:<br> chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.<br> Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)<br> Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.<br> """<br> iostreams = [ThreadIOStream() for _ in range(len(chat_queue))]<br> # todo: add agents<br> responses = [RunResponse(iostream, agents=[]) for iostream in iostreams]<br> def _initiate_chats(<br> iostreams: list[ThreadIOStream] = iostreams,<br> responses: list[RunResponseProtocol] = responses,<br> ) -> None:<br> response = responses[0]<br> try:<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> consolidate_chat_info(_chat_queue)<br> _validate_recipients(_chat_queue)<br> finished_chats = []<br> for chat_info, response, iostream in zip(_chat_queue, responses, iostreams):<br> with IOStream.set_default(iostream):<br> _chat_carryover = chat_info.get("carryover", [])<br> finished_chat_indexes_to_exclude_from_carryover = chat_info.get(<br> "finished_chat_indexes_to_exclude_from_carryover", []<br> )<br> if isinstance(_chat_carryover, str):<br> _chat_carryover = [_chat_carryover]<br> chat_info["carryover"] = _chat_carryover + [<br> r.summary<br> for i, r in enumerate(finished_chats)<br> if i not in finished_chat_indexes_to_exclude_from_carryover<br> ]<br> if not chat_info.get("silent", False):<br> IOStream.get_default().send(PostCarryoverProcessingEvent(chat_info=chat_info))<br> sender = chat_info["sender"]<br> chat_res = sender.initiate_chat(**chat_info)<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_res.chat_history,<br> summary=chat_res.summary,<br> cost=chat_res.cost,<br> last_speaker=(self if chat_res.chat_history[-1]["name"] == self.name else sender).name,<br> )<br> )<br> finished_chats.append(chat_res)<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> threading.Thread(target=_initiate_chats).start()<br> return responses<br>

``a_initiate_chatsasync#

a_initiate_chats(chat_queue)

Source code in autogen/agentchat/conversable_agent.py

<br>2005<br>2006<br>2007<br>2008<br> <br>async def a_initiate_chats(self, chat_queue: list[dict[str, Any]]) -> dict[int, ChatResult]:<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> self._finished_chats = await a_initiate_chats(_chat_queue)<br> return self._finished_chats<br>

``a_sequential_runasync#

a_sequential_run(chat_queue)

(Experimental) Initiate chats with multiple agents sequentially.

PARAMETER DESCRIPTION
chat_queue a list of dictionaries containing the information of the chats. Each dictionary should contain the input arguments for initiate_chat
TYPE:List[Dict]

Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.

Source code in autogen/agentchat/conversable_agent.py

<br>2010<br>2011<br>2012<br>2013<br>2014<br>2015<br>2016<br>2017<br>2018<br>2019<br>2020<br>2021<br>2022<br>2023<br>2024<br>2025<br>2026<br>2027<br>2028<br>2029<br>2030<br>2031<br>2032<br>2033<br>2034<br>2035<br>2036<br>2037<br>2038<br>2039<br>2040<br>2041<br>2042<br>2043<br>2044<br>2045<br>2046<br>2047<br>2048<br>2049<br>2050<br>2051<br>2052<br>2053<br>2054<br>2055<br>2056<br>2057<br>2058<br>2059<br>2060<br>2061<br>2062<br>2063<br>2064<br>2065<br>2066<br>2067<br>2068<br>2069<br>2070<br>2071<br>2072<br>2073<br>2074<br> <br>async def a_sequential_run(<br> self,<br> chat_queue: list[dict[str, Any]],<br>) -> list[AsyncRunResponseProtocol]:<br> """(Experimental) Initiate chats with multiple agents sequentially.<br> Args:<br> chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.<br> Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)<br> Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.<br> """<br> iostreams = [AsyncThreadIOStream() for _ in range(len(chat_queue))]<br> # todo: add agents<br> responses = [AsyncRunResponse(iostream, agents=[]) for iostream in iostreams]<br> async def _a_initiate_chats(<br> iostreams: list[AsyncThreadIOStream] = iostreams,<br> responses: list[AsyncRunResponseProtocol] = responses,<br> ) -> None:<br> response = responses[0]<br> try:<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> consolidate_chat_info(_chat_queue)<br> _validate_recipients(_chat_queue)<br> finished_chats = []<br> for chat_info, response, iostream in zip(_chat_queue, responses, iostreams):<br> with IOStream.set_default(iostream):<br> _chat_carryover = chat_info.get("carryover", [])<br> finished_chat_indexes_to_exclude_from_carryover = chat_info.get(<br> "finished_chat_indexes_to_exclude_from_carryover", []<br> )<br> if isinstance(_chat_carryover, str):<br> _chat_carryover = [_chat_carryover]<br> chat_info["carryover"] = _chat_carryover + [<br> r.summary<br> for i, r in enumerate(finished_chats)<br> if i not in finished_chat_indexes_to_exclude_from_carryover<br> ]<br> if not chat_info.get("silent", False):<br> IOStream.get_default().send(PostCarryoverProcessingEvent(chat_info=chat_info))<br> sender = chat_info["sender"]<br> chat_res = await sender.a_initiate_chat(**chat_info)<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_res.chat_history,<br> summary=chat_res.summary,<br> cost=chat_res.cost,<br> last_speaker=(self if chat_res.chat_history[-1]["name"] == self.name else sender).name,<br> )<br> )<br> finished_chats.append(chat_res)<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> asyncio.create_task(_a_initiate_chats())<br> return responses<br>

``get_chat_results #

get_chat_results(chat_index=None)

A summary from the finished chats of particular agents.

Source code in autogen/agentchat/conversable_agent.py

<br>2076<br>2077<br>2078<br>2079<br>2080<br>2081<br> <br>def get_chat_results(self, chat_index: Optional[int] = None) -> Union[list[ChatResult], ChatResult]:<br> """A summary from the finished chats of particular agents."""<br> if chat_index is not None:<br> return self._finished_chats[chat_index]<br> else:<br> return self._finished_chats<br>

``reset #

reset()

Reset the agent.

Source code in autogen/agentchat/conversable_agent.py

<br>2083<br>2084<br>2085<br>2086<br>2087<br>2088<br>2089<br>2090<br>2091<br>2092<br>2093<br>2094<br> <br>def reset(self) -> None:<br> """Reset the agent."""<br> self.clear_history()<br> self.reset_consecutive_auto_reply_counter()<br> self.stop_reply_at_receive()<br> if self.client is not None:<br> self.client.clear_usage_summary()<br> for reply_func_tuple in self._reply_func_list:<br> if reply_func_tuple["reset_config"] is not None:<br> reply_func_tuple["reset_config"](reply_func_tuple["config"])<br> else:<br> reply_func_tuple["config"] = copy.copy(reply_func_tuple["init_config"])<br>

``stop_reply_at_receive #

stop_reply_at_receive(sender=None)

Reset the reply_at_receive of the sender.

Source code in autogen/agentchat/conversable_agent.py

<br>2096<br>2097<br>2098<br>2099<br>2100<br>2101<br> <br>def stop_reply_at_receive(self, sender: Optional[Agent] = None):<br> """Reset the reply_at_receive of the sender."""<br> if sender is None:<br> self.reply_at_receive.clear()<br> else:<br> self.reply_at_receive[sender] = False<br>

``reset_consecutive_auto_reply_counter #

reset_consecutive_auto_reply_counter(sender=None)

Reset the consecutive_auto_reply_counter of the sender.

Source code in autogen/agentchat/conversable_agent.py

<br>2103<br>2104<br>2105<br>2106<br>2107<br>2108<br> <br>def reset_consecutive_auto_reply_counter(self, sender: Optional[Agent] = None):<br> """Reset the consecutive_auto_reply_counter of the sender."""<br> if sender is None:<br> self._consecutive_auto_reply_counter.clear()<br> else:<br> self._consecutive_auto_reply_counter[sender] = 0<br>

``clear_history #

clear_history(recipient=None, nr_messages_to_preserve=None)

Clear the chat history of the agent.

PARAMETER DESCRIPTION
recipient the agent with whom the chat history to clear. If None, clear the chat history with all agents.
TYPE:Optional[Agent]DEFAULT:None
nr_messages_to_preserve the number of newest messages to preserve in the chat history.
TYPE:Optional[int]DEFAULT:None

Source code in autogen/agentchat/conversable_agent.py

<br>2110<br>2111<br>2112<br>2113<br>2114<br>2115<br>2116<br>2117<br>2118<br>2119<br>2120<br>2121<br>2122<br>2123<br>2124<br>2125<br>2126<br>2127<br>2128<br>2129<br>2130<br>2131<br>2132<br>2133<br>2134<br>2135<br>2136<br>2137<br>2138<br>2139<br> <br>def clear_history(self, recipient: Optional[Agent] = None, nr_messages_to_preserve: Optional[int] = None):<br> """Clear the chat history of the agent.<br> Args:<br> recipient: the agent with whom the chat history to clear. If None, clear the chat history with all agents.<br> nr_messages_to_preserve: the number of newest messages to preserve in the chat history.<br> """<br> iostream = IOStream.get_default()<br> if recipient is None:<br> no_messages_preserved = 0<br> if nr_messages_to_preserve:<br> for key in self._oai_messages:<br> nr_messages_to_preserve_internal = nr_messages_to_preserve<br> # if breaking history between function call and function response, save function call message<br> # additionally, otherwise openai will return error<br> first_msg_to_save = self._oai_messages[key][-nr_messages_to_preserve_internal]<br> if "tool_responses" in first_msg_to_save:<br> nr_messages_to_preserve_internal += 1<br> # clear_conversable_agent_history.print_preserving_message(iostream.print)<br> no_messages_preserved += 1<br> # Remove messages from history except last `nr_messages_to_preserve` messages.<br> self._oai_messages[key] = self._oai_messages[key][-nr_messages_to_preserve_internal:]<br> iostream.send(ClearConversableAgentHistoryEvent(agent=self, no_events_preserved=no_messages_preserved))<br> else:<br> self._oai_messages.clear()<br> else:<br> self._oai_messages[recipient].clear()<br> # clear_conversable_agent_history.print_warning(iostream.print)<br> if nr_messages_to_preserve:<br> iostream.send(ClearConversableAgentHistoryWarningEvent(recipient=self))<br>

``generate_oai_reply #

generate_oai_reply(messages=None, sender=None, config=None)

Generate a reply using autogen.oai.

Source code in autogen/agentchat/conversable_agent.py

<br>2141<br>2142<br>2143<br>2144<br>2145<br>2146<br>2147<br>2148<br>2149<br>2150<br>2151<br>2152<br>2153<br>2154<br>2155<br>2156<br> <br>def generate_oai_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[OpenAIWrapper] = None,<br>) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:<br> """Generate a reply using autogen.oai."""<br> client = self.client if config is None else config<br> if client is None:<br> return False, None<br> if messages is None:<br> messages = self._oai_messages[sender]<br> extracted_response = self._generate_oai_reply_from_client(<br> client, self._oai_system_message + messages, self.client_cache<br> )<br> return (False, None) if extracted_response is None else (True, extracted_response)<br>

``a_generate_oai_replyasync#

a_generate_oai_reply(messages=None, sender=None, config=None)

Generate a reply using autogen.oai asynchronously.

Source code in autogen/agentchat/conversable_agent.py

<br>2201<br>2202<br>2203<br>2204<br>2205<br>2206<br>2207<br>2208<br>2209<br>2210<br>2211<br>2212<br>2213<br>2214<br>2215<br>2216<br>2217<br>2218<br>2219<br>2220<br>2221<br> <br>async def a_generate_oai_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:<br> """Generate a reply using autogen.oai asynchronously."""<br> iostream = IOStream.get_default()<br> def _generate_oai_reply(<br> self, iostream: IOStream, *args: Any, **kwargs: Any<br> ) -> tuple[bool, Optional[Union[str, dict[str, Any]]]]:<br> with IOStream.set_default(iostream):<br> return self.generate_oai_reply(*args, **kwargs)<br> return await asyncio.get_event_loop().run_in_executor(<br> None,<br> functools.partial(<br> _generate_oai_reply, self=self, iostream=iostream, messages=messages, sender=sender, config=config<br> ),<br> )<br>

``generate_code_execution_reply #

generate_code_execution_reply(messages=None, sender=None, config=None)

Generate a reply using code execution.

Source code in autogen/agentchat/conversable_agent.py

<br>2274<br>2275<br>2276<br>2277<br>2278<br>2279<br>2280<br>2281<br>2282<br>2283<br>2284<br>2285<br>2286<br>2287<br>2288<br>2289<br>2290<br>2291<br>2292<br>2293<br>2294<br>2295<br>2296<br>2297<br>2298<br>2299<br>2300<br>2301<br>2302<br>2303<br>2304<br>2305<br>2306<br>2307<br>2308<br>2309<br>2310<br>2311<br>2312<br>2313<br>2314<br>2315<br>2316<br>2317<br>2318<br>2319<br>2320<br>2321<br>2322<br> <br>def generate_code_execution_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Union[dict[str, Any], Literal[False]]] = None,<br>):<br> """Generate a reply using code execution."""<br> code_execution_config = config if config is not None else self._code_execution_config<br> if code_execution_config is False:<br> return False, None<br> if messages is None:<br> messages = self._oai_messages[sender]<br> last_n_messages = code_execution_config.pop("last_n_messages", "auto")<br> if not (isinstance(last_n_messages, (int, float)) and last_n_messages >= 0) and last_n_messages != "auto":<br> raise ValueError("last_n_messages must be either a non-negative integer, or the string 'auto'.")<br> messages_to_scan = last_n_messages<br> if last_n_messages == "auto":<br> # Find when the agent last spoke<br> messages_to_scan = 0<br> for i in range(len(messages)):<br> message = messages[-(i + 1)]<br> if "role" not in message or message["role"] != "user":<br> break<br> else:<br> messages_to_scan += 1<br> # iterate through the last n messages in reverse<br> # if code blocks are found, execute the code blocks and return the output<br> # if no code blocks are found, continue<br> for i in range(min(len(messages), messages_to_scan)):<br> message = messages[-(i + 1)]<br> if not message["content"]:<br> continue<br> code_blocks = extract_code(message["content"])<br> if len(code_blocks) == 1 and code_blocks[0][0] == UNKNOWN:<br> continue<br> # found code blocks, execute code and push "last_n_messages" back<br> exitcode, logs = self.execute_code_blocks(code_blocks)<br> code_execution_config["last_n_messages"] = last_n_messages<br> exitcode2str = "execution succeeded" if exitcode == 0 else "execution failed"<br> return True, f"exitcode: {exitcode} ({exitcode2str})\nCode output: {logs}"<br> # no code blocks are found, push last_n_messages back and return.<br> code_execution_config["last_n_messages"] = last_n_messages<br> return False, None<br>

``generate_function_call_reply #

generate_function_call_reply(messages=None, sender=None, config=None)

Generate a reply using function call.

"function_call" replaced by "tool_calls" as of OpenAI API v1.1.0 See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions

Source code in autogen/agentchat/conversable_agent.py

<br>2339<br>2340<br>2341<br>2342<br>2343<br>2344<br>2345<br>2346<br>2347<br>2348<br>2349<br>2350<br>2351<br>2352<br>2353<br>2354<br>2355<br>2356<br>2357<br>2358<br>2359<br>2360<br>2361<br>2362<br>2363<br>2364<br>2365<br> <br>def generate_function_call_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Optional[dict[str, Any]]]:<br> """Generate a reply using function call.<br> "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)<br> See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions<br> """<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender]<br> message = messages[-1]<br> if message.get("function_call"):<br> call_id = message.get("id", None)<br> func_call = message["function_call"]<br> func = self._function_map.get(func_call.get("name", None), None)<br> if inspect.iscoroutinefunction(func):<br> coro = self.a_execute_function(func_call, call_id=call_id)<br> _, func_return = self._run_async_in_thread(coro)<br> else:<br> _, func_return = self.execute_function(message["function_call"], call_id=call_id)<br> return True, func_return<br> return False, None<br>

``a_generate_function_call_replyasync#

a_generate_function_call_reply(messages=None, sender=None, config=None)

Generate a reply using async function call.

Source code in autogen/agentchat/conversable_agent.py

<br>2367<br>2368<br>2369<br>2370<br>2371<br>2372<br>2373<br>2374<br>2375<br>2376<br>2377<br>2378<br>2379<br>2380<br>2381<br>2382<br>2383<br>2384<br>2385<br>2386<br>2387<br>2388<br>2389<br>2390<br>2391<br>2392<br>2393<br>2394<br> <br>async def a_generate_function_call_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Optional[dict[str, Any]]]:<br> """Generate a reply using async function call.<br> "function_call" replaced by "tool_calls" as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)<br> See https://platform.openai.com/docs/api-reference/chat/create#chat-create-functions<br> """<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender]<br> message = messages[-1]<br> if "function_call" in message:<br> call_id = message.get("id", None)<br> func_call = message["function_call"]<br> func_name = func_call.get("name", "")<br> func = self._function_map.get(func_name, None)<br> if func and inspect.iscoroutinefunction(func):<br> _, func_return = await self.a_execute_function(func_call, call_id=call_id)<br> else:<br> _, func_return = self.execute_function(func_call, call_id=call_id)<br> return True, func_return<br> return False, None<br>

``generate_tool_calls_reply #

generate_tool_calls_reply(messages=None, sender=None, config=None)

Generate a reply using tool call.

Source code in autogen/agentchat/conversable_agent.py

<br>2399<br>2400<br>2401<br>2402<br>2403<br>2404<br>2405<br>2406<br>2407<br>2408<br>2409<br>2410<br>2411<br>2412<br>2413<br>2414<br>2415<br>2416<br>2417<br>2418<br>2419<br>2420<br>2421<br>2422<br>2423<br>2424<br>2425<br>2426<br>2427<br>2428<br>2429<br>2430<br>2431<br>2432<br>2433<br>2434<br>2435<br>2436<br>2437<br>2438<br>2439<br>2440<br>2441<br>2442<br>2443<br>2444<br>2445<br> <br>def generate_tool_calls_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Optional[dict[str, Any]]]:<br> """Generate a reply using tool call."""<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender]<br> message = messages[-1]<br> tool_returns = []<br> for tool_call in message.get("tool_calls", []):<br> function_call = tool_call.get("function", {})<br> tool_call_id = tool_call.get("id", None)<br> func = self._function_map.get(function_call.get("name", None), None)<br> if inspect.iscoroutinefunction(func):<br> coro = self.a_execute_function(function_call, call_id=tool_call_id)<br> _, func_return = self._run_async_in_thread(coro)<br> else:<br> _, func_return = self.execute_function(function_call, call_id=tool_call_id)<br> content = func_return.get("content", "")<br> if content is None:<br> content = ""<br> if tool_call_id is not None:<br> tool_call_response = {<br> "tool_call_id": tool_call_id,<br> "role": "tool",<br> "content": content,<br> }<br> else:<br> # Do not include tool_call_id if it is not present.<br> # This is to make the tool call object compatible with Mistral API.<br> tool_call_response = {<br> "role": "tool",<br> "content": content,<br> }<br> tool_returns.append(tool_call_response)<br> if tool_returns:<br> return True, {<br> "role": "tool",<br> "tool_responses": tool_returns,<br> "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),<br> }<br> return False, None<br>

``a_generate_tool_calls_replyasync#

a_generate_tool_calls_reply(messages=None, sender=None, config=None)

Generate a reply using async function call.

Source code in autogen/agentchat/conversable_agent.py

<br>2457<br>2458<br>2459<br>2460<br>2461<br>2462<br>2463<br>2464<br>2465<br>2466<br>2467<br>2468<br>2469<br>2470<br>2471<br>2472<br>2473<br>2474<br>2475<br>2476<br>2477<br>2478<br>2479<br>2480<br> <br>async def a_generate_tool_calls_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Optional[dict[str, Any]]]:<br> """Generate a reply using async function call."""<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender]<br> message = messages[-1]<br> async_tool_calls = []<br> for tool_call in message.get("tool_calls", []):<br> async_tool_calls.append(self._a_execute_tool_call(tool_call))<br> if async_tool_calls:<br> tool_returns = await asyncio.gather(*async_tool_calls)<br> return True, {<br> "role": "tool",<br> "tool_responses": tool_returns,<br> "content": "\n\n".join([self._str_for_tool_response(tool_return) for tool_return in tool_returns]),<br> }<br> return False, None<br>

``check_termination_and_human_reply #

check_termination_and_human_reply(messages=None, sender=None, config=None)

Check if the conversation should be terminated, and if human reply is provided.

This method checks for conditions that require the conversation to be terminated, such as reaching a maximum number of consecutive auto-replies or encountering a termination message. Additionally, it prompts for and processes human input based on the configured human input mode, which can be 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter for the conversation and prints relevant messages based on the human input received.

PARAMETER DESCRIPTION
messages A list of message dictionaries, representing the conversation history.
TYPE:Optional[list[dict[str, Any]]]DEFAULT:None
sender The agent object representing the sender of the message.
TYPE:Optional[Agent]DEFAULT:None
config Configuration object, defaults to the current instance if not provided.
TYPE:Optional[Any]DEFAULT:None
RETURNS DESCRIPTION
bool A tuple containing a boolean indicating if the conversation
Union[str, None] should be terminated, and a human reply which can be a string, a dictionary, or None.

Source code in autogen/agentchat/conversable_agent.py

<br>2482<br>2483<br>2484<br>2485<br>2486<br>2487<br>2488<br>2489<br>2490<br>2491<br>2492<br>2493<br>2494<br>2495<br>2496<br>2497<br>2498<br>2499<br>2500<br>2501<br>2502<br>2503<br>2504<br>2505<br>2506<br>2507<br>2508<br>2509<br>2510<br>2511<br>2512<br>2513<br>2514<br>2515<br>2516<br>2517<br>2518<br>2519<br>2520<br>2521<br>2522<br>2523<br>2524<br>2525<br>2526<br>2527<br>2528<br>2529<br>2530<br>2531<br>2532<br>2533<br>2534<br>2535<br>2536<br>2537<br>2538<br>2539<br>2540<br>2541<br>2542<br>2543<br>2544<br>2545<br>2546<br>2547<br>2548<br>2549<br>2550<br>2551<br>2552<br>2553<br>2554<br>2555<br>2556<br>2557<br>2558<br>2559<br>2560<br>2561<br>2562<br>2563<br>2564<br>2565<br>2566<br>2567<br>2568<br>2569<br>2570<br>2571<br>2572<br>2573<br>2574<br>2575<br>2576<br>2577<br>2578<br>2579<br>2580<br>2581<br>2582<br>2583<br>2584<br>2585<br>2586<br>2587<br>2588<br>2589<br>2590<br>2591<br>2592<br>2593<br>2594<br>2595<br>2596<br>2597<br>2598<br>2599<br>2600<br>2601<br>2602<br>2603<br>2604<br>2605<br>2606<br>2607<br>2608<br>2609<br>2610<br>2611<br>2612<br>2613<br>2614<br>2615<br>2616<br>2617<br>2618<br>2619<br>2620<br>2621<br>2622<br>2623<br>2624<br> <br>def check_termination_and_human_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Union[str, None]]:<br> """Check if the conversation should be terminated, and if human reply is provided.<br> This method checks for conditions that require the conversation to be terminated, such as reaching<br> a maximum number of consecutive auto-replies or encountering a termination message. Additionally,<br> it prompts for and processes human input based on the configured human input mode, which can be<br> 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter<br> for the conversation and prints relevant messages based on the human input received.<br> Args:<br> messages: A list of message dictionaries, representing the conversation history.<br> sender: The agent object representing the sender of the message.<br> config: Configuration object, defaults to the current instance if not provided.<br> Returns:<br> A tuple containing a boolean indicating if the conversation<br> should be terminated, and a human reply which can be a string, a dictionary, or None.<br> """<br> iostream = IOStream.get_default()<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender] if sender else []<br> termination_reason = None<br> # if there are no messages, continue the conversation<br> if not messages:<br> return False, None<br> message = messages[-1]<br> reply = ""<br> no_human_input_msg = ""<br> sender_name = "the sender" if sender is None else sender.name<br> if self.human_input_mode == "ALWAYS":<br> reply = self.get_human_input(<br> 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: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if not reply and self._is_termination_msg(message):<br> termination_reason = f"Termination message condition on agent '{self.name}' met"<br> elif reply == "exit":<br> termination_reason = "User requested to end the conversation"<br> reply = reply if reply or not self._is_termination_msg(message) else "exit"<br> else:<br> if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:<br> if self.human_input_mode == "NEVER":<br> termination_reason = "Maximum number of consecutive auto-replies reached"<br> reply = "exit"<br> else:<br> # self.human_input_mode == "TERMINATE":<br> terminate = self._is_termination_msg(message)<br> reply = self.get_human_input(<br> f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "<br> if terminate<br> else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if reply != "exit" and terminate:<br> termination_reason = (<br> f"Termination message condition on agent '{self.name}' met and no human input provided"<br> )<br> elif reply == "exit":<br> termination_reason = "User requested to end the conversation"<br> reply = reply if reply or not terminate else "exit"<br> elif self._is_termination_msg(message):<br> if self.human_input_mode == "NEVER":<br> termination_reason = f"Termination message condition on agent '{self.name}' met"<br> reply = "exit"<br> else:<br> # self.human_input_mode == "TERMINATE":<br> reply = self.get_human_input(<br> f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if not reply or reply == "exit":<br> termination_reason = (<br> f"Termination message condition on agent '{self.name}' met and no human input provided"<br> )<br> reply = reply or "exit"<br> # print the no_human_input_msg<br> if no_human_input_msg:<br> iostream.send(<br> TerminationAndHumanReplyNoInputEvent(<br> no_human_input_msg=no_human_input_msg, sender=sender, recipient=self<br> )<br> )<br> # stop the conversation<br> if reply == "exit":<br> # reset the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] = 0<br> if termination_reason:<br> iostream.send(TerminationEvent(termination_reason=termination_reason))<br> return True, None<br> # send the human reply<br> if reply or self._max_consecutive_auto_reply_dict[sender] == 0:<br> # reset the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] = 0<br> # User provided a custom response, return function and tool failures indicating user interruption<br> tool_returns = []<br> if message.get("function_call", False):<br> tool_returns.append({<br> "role": "function",<br> "name": message["function_call"].get("name", ""),<br> "content": "USER INTERRUPTED",<br> })<br> if message.get("tool_calls", False):<br> tool_returns.extend([<br> {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}<br> for tool_call in message["tool_calls"]<br> ])<br> response = {"role": "user", "content": reply}<br> if tool_returns:<br> response["tool_responses"] = tool_returns<br> return True, response<br> # increment the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] += 1<br> if self.human_input_mode != "NEVER":<br> iostream.send(UsingAutoReplyEvent(human_input_mode=self.human_input_mode, sender=sender, recipient=self))<br> return False, None<br>

``a_check_termination_and_human_replyasync#

a_check_termination_and_human_reply(messages=None, sender=None, config=None)

(async) Check if the conversation should be terminated, and if human reply is provided.

PARAMETER DESCRIPTION
messages A list of message dictionaries, representing the conversation history.
TYPE:Optional[List[Dict]]DEFAULT:None
sender The agent object representing the sender of the message.
TYPE:Optional[Agent]DEFAULT:None
config Configuration object, defaults to the current instance if not provided.
TYPE:Optional[Any]DEFAULT:None
RETURNS DESCRIPTION
bool Tuple[bool, Union[str, Dict, None]]: A tuple containing a boolean indicating if the conversation
Union[str, None] should be terminated, and a human reply which can be a string, a dictionary, or None.

Source code in autogen/agentchat/conversable_agent.py

<br>2626<br>2627<br>2628<br>2629<br>2630<br>2631<br>2632<br>2633<br>2634<br>2635<br>2636<br>2637<br>2638<br>2639<br>2640<br>2641<br>2642<br>2643<br>2644<br>2645<br>2646<br>2647<br>2648<br>2649<br>2650<br>2651<br>2652<br>2653<br>2654<br>2655<br>2656<br>2657<br>2658<br>2659<br>2660<br>2661<br>2662<br>2663<br>2664<br>2665<br>2666<br>2667<br>2668<br>2669<br>2670<br>2671<br>2672<br>2673<br>2674<br>2675<br>2676<br>2677<br>2678<br>2679<br>2680<br>2681<br>2682<br>2683<br>2684<br>2685<br>2686<br>2687<br>2688<br>2689<br>2690<br>2691<br>2692<br>2693<br>2694<br>2695<br>2696<br>2697<br>2698<br>2699<br>2700<br>2701<br>2702<br>2703<br>2704<br>2705<br>2706<br>2707<br>2708<br>2709<br>2710<br>2711<br>2712<br>2713<br>2714<br>2715<br>2716<br>2717<br>2718<br>2719<br>2720<br>2721<br>2722<br>2723<br>2724<br>2725<br>2726<br>2727<br>2728<br>2729<br>2730<br>2731<br>2732<br>2733<br>2734<br>2735<br>2736<br>2737<br>2738<br>2739<br>2740<br>2741<br>2742<br>2743<br>2744<br>2745<br>2746<br>2747<br>2748<br>2749<br>2750<br>2751<br>2752<br>2753<br>2754<br>2755<br>2756<br>2757<br>2758<br>2759<br>2760<br>2761<br>2762<br>2763<br>2764<br> <br>async def a_check_termination_and_human_reply(<br> self,<br> messages: Optional[list[dict[str, Any]]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> tuple[bool, Union[str, None]]:<br> """(async) Check if the conversation should be terminated, and if human reply is provided.<br> This method checks for conditions that require the conversation to be terminated, such as reaching<br> a maximum number of consecutive auto-replies or encountering a termination message. Additionally,<br> it prompts for and processes human input based on the configured human input mode, which can be<br> 'ALWAYS', 'NEVER', or 'TERMINATE'. The method also manages the consecutive auto-reply counter<br> for the conversation and prints relevant messages based on the human input received.<br> Args:<br> messages (Optional[List[Dict]]): A list of message dictionaries, representing the conversation history.<br> sender (Optional[Agent]): The agent object representing the sender of the message.<br> config (Optional[Any]): Configuration object, defaults to the current instance if not provided.<br> Returns:<br> Tuple[bool, Union[str, Dict, None]]: A tuple containing a boolean indicating if the conversation<br> should be terminated, and a human reply which can be a string, a dictionary, or None.<br> """<br> iostream = IOStream.get_default()<br> if config is None:<br> config = self<br> if messages is None:<br> messages = self._oai_messages[sender] if sender else []<br> termination_reason = None<br> message = messages[-1] if messages else {}<br> reply = ""<br> no_human_input_msg = ""<br> sender_name = "the sender" if sender is None else sender.name<br> if self.human_input_mode == "ALWAYS":<br> reply = await self.a_get_human_input(<br> 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: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if not reply and self._is_termination_msg(message):<br> termination_reason = f"Termination message condition on agent '{self.name}' met"<br> elif reply == "exit":<br> termination_reason = "User requested to end the conversation"<br> reply = reply if reply or not self._is_termination_msg(message) else "exit"<br> else:<br> if self._consecutive_auto_reply_counter[sender] >= self._max_consecutive_auto_reply_dict[sender]:<br> if self.human_input_mode == "NEVER":<br> termination_reason = "Maximum number of consecutive auto-replies reached"<br> reply = "exit"<br> else:<br> # self.human_input_mode == "TERMINATE":<br> terminate = self._is_termination_msg(message)<br> reply = await self.a_get_human_input(<br> f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "<br> if terminate<br> else f"Please give feedback to {sender_name}. Press enter to skip and use auto-reply, or type 'exit' to stop the conversation: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if reply != "exit" and terminate:<br> termination_reason = (<br> f"Termination message condition on agent '{self.name}' met and no human input provided"<br> )<br> elif reply == "exit":<br> termination_reason = "User requested to end the conversation"<br> reply = reply if reply or not terminate else "exit"<br> elif self._is_termination_msg(message):<br> if self.human_input_mode == "NEVER":<br> termination_reason = f"Termination message condition on agent '{self.name}' met"<br> reply = "exit"<br> else:<br> # self.human_input_mode == "TERMINATE":<br> reply = await self.a_get_human_input(<br> f"Please give feedback to {sender_name}. Press enter or type 'exit' to stop the conversation: "<br> )<br> no_human_input_msg = "NO HUMAN INPUT RECEIVED." if not reply else ""<br> # if the human input is empty, and the message is a termination message, then we will terminate the conversation<br> if not reply or reply == "exit":<br> termination_reason = (<br> f"Termination message condition on agent '{self.name}' met and no human input provided"<br> )<br> reply = reply or "exit"<br> # print the no_human_input_msg<br> if no_human_input_msg:<br> iostream.send(<br> TerminationAndHumanReplyNoInputEvent(<br> no_human_input_msg=no_human_input_msg, sender=sender, recipient=self<br> )<br> )<br> # stop the conversation<br> if reply == "exit":<br> # reset the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] = 0<br> if termination_reason:<br> iostream.send(TerminationEvent(termination_reason=termination_reason))<br> return True, None<br> # send the human reply<br> if reply or self._max_consecutive_auto_reply_dict[sender] == 0:<br> # User provided a custom response, return function and tool results indicating user interruption<br> # reset the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] = 0<br> tool_returns = []<br> if message.get("function_call", False):<br> tool_returns.append({<br> "role": "function",<br> "name": message["function_call"].get("name", ""),<br> "content": "USER INTERRUPTED",<br> })<br> if message.get("tool_calls", False):<br> tool_returns.extend([<br> {"role": "tool", "tool_call_id": tool_call.get("id", ""), "content": "USER INTERRUPTED"}<br> for tool_call in message["tool_calls"]<br> ])<br> response = {"role": "user", "content": reply}<br> if tool_returns:<br> response["tool_responses"] = tool_returns<br> return True, response<br> # increment the consecutive_auto_reply_counter<br> self._consecutive_auto_reply_counter[sender] += 1<br> if self.human_input_mode != "NEVER":<br> iostream.send(UsingAutoReplyEvent(human_input_mode=self.human_input_mode, sender=sender, recipient=self))<br> return False, None<br>

``get_human_input #

get_human_input(prompt)

Get human input.

Override this method to customize the way to get human input.

PARAMETER DESCRIPTION
prompt prompt for the human input.
TYPE:str
RETURNS DESCRIPTION
str human input.
TYPE:str

Source code in autogen/agentchat/conversable_agent.py

<br>2943<br>2944<br>2945<br>2946<br>2947<br>2948<br>2949<br>2950<br>2951<br>2952<br>2953<br>2954<br>2955<br>2956<br>2957<br>2958<br> <br>def get_human_input(self, prompt: str) -> str:<br> """Get human input.<br> Override this method to customize the way to get human input.<br> Args:<br> prompt (str): prompt for the human input.<br> Returns:<br> str: human input.<br> """<br> iostream = IOStream.get_default()<br> reply = iostream.input(prompt)<br> self._human_input.append(reply)<br> return reply<br>

``a_get_human_inputasync#

a_get_human_input(prompt)

(Async) Get human input.

Override this method to customize the way to get human input.

PARAMETER DESCRIPTION
prompt prompt for the human input.
TYPE:str
RETURNS DESCRIPTION
str human input.
TYPE:str

Source code in autogen/agentchat/conversable_agent.py

<br>2960<br>2961<br>2962<br>2963<br>2964<br>2965<br>2966<br>2967<br>2968<br>2969<br>2970<br>2971<br>2972<br>2973<br>2974<br>2975<br> <br>async def a_get_human_input(self, prompt: str) -> str:<br> """(Async) Get human input.<br> Override this method to customize the way to get human input.<br> Args:<br> prompt (str): prompt for the human input.<br> Returns:<br> str: human input.<br> """<br> iostream = IOStream.get_default()<br> reply = await iostream.input(prompt)<br> self._human_input.append(reply)<br> return reply<br>

``run_code #

run_code(code, **kwargs)

Run the code and return the result.

Override this function to modify the way to run the code.

PARAMETER DESCRIPTION
code the code to be executed.
TYPE:str
**kwargs other keyword arguments.
TYPE:AnyDEFAULT:{}
RETURNS DESCRIPTION
int A tuple of (exitcode, logs, image).
exitcode the exit code of the code execution.
TYPE:int
logs the logs of the code execution.
TYPE:str
image the docker image used for the code execution.
TYPE:str or None

Source code in autogen/agentchat/conversable_agent.py

<br>2992<br>2993<br>2994<br>2995<br>2996<br>2997<br>2998<br>2999<br>3000<br>3001<br>3002<br>3003<br>3004<br>3005<br>3006<br>3007<br> <br>def run_code(self, code: str, **kwargs: Any) -> tuple[int, str, Optional[str]]:<br> """Run the code and return the result.<br> Override this function to modify the way to run the code.<br> Args:<br> code (str): the code to be executed.<br> **kwargs: other keyword arguments.<br> Returns:<br> A tuple of (exitcode, logs, image).<br> exitcode (int): the exit code of the code execution.<br> logs (str): the logs of the code execution.<br> image (str or None): the docker image used for the code execution.<br> """<br> return execute_code(code, **kwargs)<br>

``execute_code_blocks #

execute_code_blocks(code_blocks)

Execute the code blocks and return the result.

Source code in autogen/agentchat/conversable_agent.py

<br>3009<br>3010<br>3011<br>3012<br>3013<br>3014<br>3015<br>3016<br>3017<br>3018<br>3019<br>3020<br>3021<br>3022<br>3023<br>3024<br>3025<br>3026<br>3027<br>3028<br>3029<br>3030<br>3031<br>3032<br>3033<br>3034<br>3035<br>3036<br>3037<br>3038<br>3039<br>3040<br>3041<br>3042<br>3043<br>3044<br> <br>def execute_code_blocks(self, code_blocks):<br> """Execute the code blocks and return the result."""<br> iostream = IOStream.get_default()<br> logs_all = ""<br> for i, code_block in enumerate(code_blocks):<br> lang, code = code_block<br> if not lang:<br> lang = infer_lang(code)<br> iostream.send(ExecuteCodeBlockEvent(code=code, language=lang, code_block_count=i, recipient=self))<br> if lang in ["bash", "shell", "sh"]:<br> exitcode, logs, image = self.run_code(code, lang=lang, **self._code_execution_config)<br> elif lang in PYTHON_VARIANTS:<br> filename = code[11 : code.find("\n")].strip() if code.startswith("# filename: ") else None<br> exitcode, logs, image = self.run_code(<br> code,<br> lang="python",<br> filename=filename,<br> **self._code_execution_config,<br> )<br> else:<br> # In case the language is not supported, we return an error message.<br> exitcode, logs, image = (<br> 1,<br> f"unknown language {lang}",<br> None,<br> )<br> # raise NotImplementedError<br> if image is not None:<br> self._code_execution_config["use_docker"] = image<br> logs_all += "\n" + logs<br> if exitcode != 0:<br> return exitcode, logs_all<br> return exitcode, logs_all<br>

``execute_function #

execute_function(func_call, call_id=None, verbose=False)

Execute a function call and return the result.

Override this function to modify the way to execute function and tool calls.

PARAMETER DESCRIPTION
func_call a dictionary extracted from openai message at "function_call" or "tool_calls" with keys "name" and "arguments".
TYPE:dict[str, Any]
call_id a string to identify the tool call.
TYPE:Optional[str]DEFAULT:None
verbose Whether to send messages about the execution details to the output stream. When True, both the function call arguments and the execution result will be displayed. Defaults to False.
TYPE:boolDEFAULT:False
RETURNS DESCRIPTION
bool A tuple of (is_exec_success, result_dict).
is_exec_success whether the execution is successful.
TYPE:boolean
result_dict a dictionary with keys "name", "role", and "content". Value of "role" is "function".
TYPE:tuple[bool, dict[str, Any]]

"function_call" deprecated as of OpenAI API v1.1.0 See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function\_call

Source code in autogen/agentchat/conversable_agent.py

<br>3076<br>3077<br>3078<br>3079<br>3080<br>3081<br>3082<br>3083<br>3084<br>3085<br>3086<br>3087<br>3088<br>3089<br>3090<br>3091<br>3092<br>3093<br>3094<br>3095<br>3096<br>3097<br>3098<br>3099<br>3100<br>3101<br>3102<br>3103<br>3104<br>3105<br>3106<br>3107<br>3108<br>3109<br>3110<br>3111<br>3112<br>3113<br>3114<br>3115<br>3116<br>3117<br>3118<br>3119<br>3120<br>3121<br>3122<br>3123<br>3124<br>3125<br>3126<br>3127<br>3128<br>3129<br>3130<br>3131<br>3132<br>3133<br>3134<br>3135<br>3136<br>3137<br>3138<br>3139<br>3140<br>3141<br>3142<br>3143<br> <br>def execute_function(<br> self, func_call: dict[str, Any], call_id: Optional[str] = None, verbose: bool = False<br>) -> tuple[bool, dict[str, Any]]:<br> """Execute a function call and return the result.<br> Override this function to modify the way to execute function and tool calls.<br> Args:<br> func_call: a dictionary extracted from openai message at "function_call" or "tool_calls" with keys "name" and "arguments".<br> call_id: a string to identify the tool call.<br> verbose (bool): Whether to send messages about the execution details to the<br> output stream. When True, both the function call arguments and the execution<br> result will be displayed. Defaults to False.<br> Returns:<br> A tuple of (is_exec_success, result_dict).<br> is_exec_success (boolean): whether the execution is successful.<br> result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".<br> "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)<br> See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call<br> """<br> iostream = IOStream.get_default()<br> func_name = func_call.get("name", "")<br> func = self._function_map.get(func_name, None)<br> is_exec_success = False<br> if func is not None:<br> # Extract arguments from a json-like string and put it into a dict.<br> input_string = self._format_json_str(func_call.get("arguments", "{}"))<br> try:<br> arguments = json.loads(input_string)<br> except json.JSONDecodeError as e:<br> arguments = None<br> content = f"Error: {e}\n The argument must be in JSON format."<br> # Try to execute the function<br> if arguments is not None:<br> iostream.send(<br> ExecuteFunctionEvent(func_name=func_name, call_id=call_id, arguments=arguments, recipient=self)<br> )<br> try:<br> content = func(**arguments)<br> is_exec_success = True<br> except Exception as e:<br> content = f"Error: {e}"<br> else:<br> arguments = {}<br> content = f"Error: Function {func_name} not found."<br> iostream.send(<br> ExecutedFunctionEvent(<br> func_name=func_name,<br> call_id=call_id,<br> arguments=arguments,<br> content=content,<br> recipient=self,<br> is_exec_success=is_exec_success,<br> )<br> )<br> return is_exec_success, {<br> "name": func_name,<br> "role": "function",<br> "content": content,<br> }<br>

``a_execute_functionasync#

a_execute_function(func_call, call_id=None, verbose=False)

Execute an async function call and return the result.

Override this function to modify the way async functions and tools are executed.

PARAMETER DESCRIPTION
func_call a dictionary extracted from openai message at key "function_call" or "tool_calls" with keys "name" and "arguments".
TYPE:dict[str, Any]
call_id a string to identify the tool call.
TYPE:Optional[str]DEFAULT:None
verbose Whether to send messages about the execution details to the output stream. When True, both the function call arguments and the execution result will be displayed. Defaults to False.
TYPE:boolDEFAULT:False

Source code in autogen/agentchat/conversable_agent.py

<br>3145<br>3146<br>3147<br>3148<br>3149<br>3150<br>3151<br>3152<br>3153<br>3154<br>3155<br>3156<br>3157<br>3158<br>3159<br>3160<br>3161<br>3162<br>3163<br>3164<br>3165<br>3166<br>3167<br>3168<br>3169<br>3170<br>3171<br>3172<br>3173<br>3174<br>3175<br>3176<br>3177<br>3178<br>3179<br>3180<br>3181<br>3182<br>3183<br>3184<br>3185<br>3186<br>3187<br>3188<br>3189<br>3190<br>3191<br>3192<br>3193<br>3194<br>3195<br>3196<br>3197<br>3198<br>3199<br>3200<br>3201<br>3202<br>3203<br>3204<br>3205<br>3206<br>3207<br>3208<br>3209<br>3210<br>3211<br>3212<br>3213<br>3214<br>3215<br> <br>async def a_execute_function(<br> self, func_call: dict[str, Any], call_id: Optional[str] = None, verbose: bool = False<br>) -> tuple[bool, dict[str, Any]]:<br> """Execute an async function call and return the result.<br> Override this function to modify the way async functions and tools are executed.<br> Args:<br> func_call: a dictionary extracted from openai message at key "function_call" or "tool_calls" with keys "name" and "arguments".<br> call_id: a string to identify the tool call.<br> verbose (bool): Whether to send messages about the execution details to the<br> output stream. When True, both the function call arguments and the execution<br> result will be displayed. Defaults to False.<br> Returns:<br> A tuple of (is_exec_success, result_dict).<br> is_exec_success (boolean): whether the execution is successful.<br> result_dict: a dictionary with keys "name", "role", and "content". Value of "role" is "function".<br> "function_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)<br> See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call<br> """<br> iostream = IOStream.get_default()<br> func_name = func_call.get("name", "")<br> func = self._function_map.get(func_name, None)<br> is_exec_success = False<br> if func is not None:<br> # Extract arguments from a json-like string and put it into a dict.<br> input_string = self._format_json_str(func_call.get("arguments", "{}"))<br> try:<br> arguments = json.loads(input_string)<br> except json.JSONDecodeError as e:<br> arguments = None<br> content = f"Error: {e}\n The argument must be in JSON format."<br> # Try to execute the function<br> if arguments is not None:<br> iostream.send(<br> ExecuteFunctionEvent(func_name=func_name, call_id=call_id, arguments=arguments, recipient=self)<br> )<br> try:<br> if inspect.iscoroutinefunction(func):<br> content = await func(**arguments)<br> else:<br> # Fallback to sync function if the function is not async<br> content = func(**arguments)<br> is_exec_success = True<br> except Exception as e:<br> content = f"Error: {e}"<br> else:<br> arguments = {}<br> content = f"Error: Function {func_name} not found."<br> iostream.send(<br> ExecutedFunctionEvent(<br> func_name=func_name,<br> call_id=call_id,<br> arguments=arguments,<br> content=content,<br> recipient=self,<br> is_exec_success=is_exec_success,<br> )<br> )<br> return is_exec_success, {<br> "name": func_name,<br> "role": "function",<br> "content": content,<br> }<br>

``generate_init_message #

generate_init_message(message, **kwargs)

Generate the initial message for the agent. If message is None, input() will be called to get the initial message.

PARAMETER DESCRIPTION
message the message to be processed.
TYPE:str or None
**kwargs any additional information. It has the following reserved fields: "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. If provided, we will combine this carryover with the "message" content when generating the initial chat message.
TYPE:AnyDEFAULT:{}
RETURNS DESCRIPTION
Union[str, dict[str, Any]] str or dict: the processed message.

Source code in autogen/agentchat/conversable_agent.py

<br>3217<br>3218<br>3219<br>3220<br>3221<br>3222<br>3223<br>3224<br>3225<br>3226<br>3227<br>3228<br>3229<br>3230<br>3231<br>3232<br>3233<br>3234<br>3235<br>3236<br> <br>def generate_init_message(<br> self, message: Optional[Union[dict[str, Any], str]], **kwargs: Any<br>) -> Union[str, dict[str, Any]]:<br> """Generate the initial message for the agent.<br> If message is None, input() will be called to get the initial message.<br> Args:<br> message (str or None): the message to be processed.<br> **kwargs: any additional information. It has the following reserved fields:<br> "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.<br> If provided, we will combine this carryover with the "message" content when generating the initial chat<br> message.<br> Returns:<br> str or dict: the processed message.<br> """<br> if message is None:<br> message = self.get_human_input(">")<br> return self._handle_carryover(message, kwargs)<br>

``a_generate_init_messageasync#

a_generate_init_message(message, **kwargs)

Generate the initial message for the agent. If message is None, input() will be called to get the initial message.

RETURNS DESCRIPTION
Union[str, dict[str, Any]] str or dict: the processed message.

Source code in autogen/agentchat/conversable_agent.py

<br>3283<br>3284<br>3285<br>3286<br>3287<br>3288<br>3289<br>3290<br>3291<br>3292<br>3293<br>3294<br>3295<br>3296<br>3297<br>3298<br>3299<br>3300<br>3301<br>3302<br> <br>async def a_generate_init_message(<br> self, message: Optional[Union[dict[str, Any], str]], **kwargs: Any<br>) -> Union[str, dict[str, Any]]:<br> """Generate the initial message for the agent.<br> If message is None, input() will be called to get the initial message.<br> Args:<br> message (str or None): the message to be processed.<br> **kwargs: any additional information. It has the following reserved fields:<br> "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.<br> If provided, we will combine this carryover with the "message" content when generating the initial chat<br> message.<br> Returns:<br> str or dict: the processed message.<br> """<br> if message is None:<br> message = await self.a_get_human_input(">")<br> return self._handle_carryover(message, kwargs)<br>

``remove_tool_for_llm #

remove_tool_for_llm(tool)

Remove a tool (register for LLM tool)

Source code in autogen/agentchat/conversable_agent.py

<br>3312<br>3313<br>3314<br>3315<br>3316<br>3317<br>3318<br> <br>def remove_tool_for_llm(self, tool: Tool) -> None:<br> """Remove a tool (register for LLM tool)"""<br> try:<br> self._register_for_llm(tool=tool, api_style="tool", is_remove=True)<br> self._tools.remove(tool)<br> except ValueError:<br> raise ValueError(f"Tool {tool} not found in collection")<br>

``register_function #

register_function(function_map, silent_override=False)

Register functions to the agent.

PARAMETER DESCRIPTION
function_map a dictionary mapping function names to functions. if function_map[name] is None, the function will be removed from the function_map.
TYPE:dict[str, Union[Callable[..., Any]]]
silent_override whether to print warnings when overriding functions.
TYPE:boolDEFAULT:False

Source code in autogen/agentchat/conversable_agent.py

<br>3320<br>3321<br>3322<br>3323<br>3324<br>3325<br>3326<br>3327<br>3328<br>3329<br>3330<br>3331<br>3332<br>3333<br>3334<br> <br>def register_function(self, function_map: dict[str, Union[Callable[..., Any]]], silent_override: bool = False):<br> """Register functions to the agent.<br> Args:<br> function_map: a dictionary mapping function names to functions. if function_map[name] is None, the function will be removed from the function_map.<br> silent_override: whether to print warnings when overriding functions.<br> """<br> for name, func in function_map.items():<br> self._assert_valid_name(name)<br> if func is None and name not in self._function_map:<br> warnings.warn(f"The function {name} to remove doesn't exist", name)<br> if not silent_override and name in self._function_map:<br> warnings.warn(f"Function '{name}' is being overridden.", UserWarning)<br> self._function_map.update(function_map)<br> self._function_map = {k: v for k, v in self._function_map.items() if v is not None}<br>

``update_function_signature #

update_function_signature(func_sig, is_remove, silent_override=False)

Update a function_signature in the LLM configuration for function_call.

PARAMETER DESCRIPTION
func_sig description/name of the function to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat/create-functions
TYPE:str or dict
is_remove whether removing the function from llm_config with name 'func_sig'
TYPE:None
silent_override whether to print warnings when overriding functions.
TYPE:boolDEFAULT:False

Deprecated as of OpenAI API v1.1.0 See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function\_call

Source code in autogen/agentchat/conversable_agent.py

<br>3336<br>3337<br>3338<br>3339<br>3340<br>3341<br>3342<br>3343<br>3344<br>3345<br>3346<br>3347<br>3348<br>3349<br>3350<br>3351<br>3352<br>3353<br>3354<br>3355<br>3356<br>3357<br>3358<br>3359<br>3360<br>3361<br>3362<br>3363<br>3364<br>3365<br>3366<br>3367<br>3368<br>3369<br>3370<br>3371<br>3372<br>3373<br>3374<br>3375<br>3376<br>3377<br>3378<br>3379<br>3380<br>3381<br>3382<br>3383<br>3384<br>3385<br>3386<br>3387<br> <br>def update_function_signature(<br> self, func_sig: Union[str, dict[str, Any]], is_remove: None, silent_override: bool = False<br>):<br> """Update a function_signature in the LLM configuration for function_call.<br> Args:<br> 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<br> is_remove: whether removing the function from llm_config with name 'func_sig'<br> silent_override: whether to print warnings when overriding functions.<br> Deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/v1.1.0)<br> See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call<br> """<br> if not isinstance(self.llm_config, (dict, LLMConfig)):<br> error_msg = "To update a function signature, agent must have an llm_config"<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> if is_remove:<br> if "functions" not in self.llm_config or len(self.llm_config["functions"]) == 0:<br> error_msg = f"The agent config doesn't have function {func_sig}."<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> else:<br> self.llm_config["functions"] = [<br> func for func in self.llm_config["functions"] if func["name"] != func_sig<br> ]<br> else:<br> if not isinstance(func_sig, dict):<br> raise ValueError(<br> f"The function signature must be of the type dict. Received function signature type {type(func_sig)}"<br> )<br> if "name" not in func_sig:<br> raise ValueError(f"The function signature must have a 'name' key. Received: {func_sig}")<br> self._assert_valid_name(func_sig["name"]), func_sig<br> if "functions" in self.llm_config:<br> if not silent_override and any(<br> func["name"] == func_sig["name"] for func in self.llm_config["functions"]<br> ):<br> warnings.warn(f"Function '{func_sig['name']}' is being overridden.", UserWarning)<br> self.llm_config["functions"] = [<br> func for func in self.llm_config["functions"] if func.get("name") != func_sig["name"]<br> ] + [func_sig]<br> else:<br> self.llm_config["functions"] = [func_sig]<br> # Do this only if llm_config is a dict. If llm_config is LLMConfig, LLMConfig will handle this.<br> if len(self.llm_config["functions"]) == 0 and isinstance(self.llm_config, dict):<br> del self.llm_config["functions"]<br> self.client = OpenAIWrapper(**self.llm_config)<br>

``update_tool_signature #

update_tool_signature(tool_sig, is_remove, silent_override=False)

Update a tool_signature in the LLM configuration for tool_call.

PARAMETER DESCRIPTION
tool_sig description/name of the tool to update/remove to the model. See: https://platform.openai.com/docs/api-reference/chat/create#chat-create-tools
TYPE:str or dict
is_remove whether removing the tool from llm_config with name 'tool_sig'
TYPE:bool
silent_override whether to print warnings when overriding functions.
TYPE:boolDEFAULT:False

Source code in autogen/agentchat/conversable_agent.py

<br>3389<br>3390<br>3391<br>3392<br>3393<br>3394<br>3395<br>3396<br>3397<br>3398<br>3399<br>3400<br>3401<br>3402<br>3403<br>3404<br>3405<br>3406<br>3407<br>3408<br>3409<br>3410<br>3411<br>3412<br>3413<br>3414<br>3415<br>3416<br>3417<br>3418<br>3419<br>3420<br>3421<br>3422<br>3423<br>3424<br>3425<br>3426<br>3427<br>3428<br>3429<br>3430<br>3431<br>3432<br>3433<br>3434<br>3435<br>3436<br>3437<br>3438<br>3439<br>3440<br>3441<br>3442<br>3443<br>3444<br>3445<br>3446<br>3447<br> <br>def update_tool_signature(<br> self, tool_sig: Union[str, dict[str, Any]], is_remove: bool, silent_override: bool = False<br>):<br> """Update a tool_signature in the LLM configuration for tool_call.<br> Args:<br> 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<br> is_remove: whether removing the tool from llm_config with name 'tool_sig'<br> silent_override: whether to print warnings when overriding functions.<br> """<br> if not self.llm_config:<br> error_msg = "To update a tool signature, agent must have an llm_config"<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> if is_remove:<br> if "tools" not in self.llm_config or len(self.llm_config["tools"]) == 0:<br> error_msg = f"The agent config doesn't have tool {tool_sig}."<br> logger.error(error_msg)<br> raise AssertionError(error_msg)<br> else:<br> current_tools = self.llm_config["tools"]<br> filtered_tools = []<br> # Loop through and rebuild tools list without the tool to remove<br> for tool in current_tools:<br> tool_name = tool["function"]["name"]<br> # Match by tool name, or by tool signature<br> is_different = tool_name != tool_sig if isinstance(tool_sig, str) else tool != tool_sig<br> if is_different:<br> filtered_tools.append(tool)<br> self.llm_config["tools"] = filtered_tools<br> else:<br> if not isinstance(tool_sig, dict):<br> raise ValueError(<br> f"The tool signature must be of the type dict. Received tool signature type {type(tool_sig)}"<br> )<br> self._assert_valid_name(tool_sig["function"]["name"])<br> if "tools" in self.llm_config and len(self.llm_config["tools"]) > 0:<br> if not silent_override and any(<br> tool["function"]["name"] == tool_sig["function"]["name"] for tool in self.llm_config["tools"]<br> ):<br> warnings.warn(f"Function '{tool_sig['function']['name']}' is being overridden.", UserWarning)<br> self.llm_config["tools"] = [<br> tool<br> for tool in self.llm_config["tools"]<br> if tool.get("function", {}).get("name") != tool_sig["function"]["name"]<br> ] + [tool_sig]<br> else:<br> self.llm_config["tools"] = [tool_sig]<br> # Do this only if llm_config is a dict. If llm_config is LLMConfig, LLMConfig will handle this.<br> if len(self.llm_config["tools"]) == 0 and isinstance(self.llm_config, dict):<br> del self.llm_config["tools"]<br> self.client = OpenAIWrapper(**self.llm_config)<br>

``can_execute_function #

can_execute_function(name)

Whether the agent can execute the function.

Source code in autogen/agentchat/conversable_agent.py

<br>3449<br>3450<br>3451<br>3452<br> <br>def can_execute_function(self, name: Union[list[str], str]) -> bool:<br> """Whether the agent can execute the function."""<br> names = name if isinstance(name, list) else [name]<br> return all([n in self._function_map for n in names])<br>

``register_for_llm #

register_for_llm(*, name=None, description=None, api_style='tool', silent_override=False)

Decorator factory for registering a function to be used by an agent.

It's return value is used to decorate a function to be registered to the agent. The function uses type hints to specify the arguments and return type. The function name is used as the default name for the function, but a custom name can be provided. The function description is used to describe the function in the agent's configuration.

PARAMETER DESCRIPTION
name name of the function. If None, the function name will be used (default: None).
TYPE:optional(strDEFAULT:None
description description of the function (default: None). It is mandatory for the initial decorator, but the following ones can omit it.
TYPE:optional(strDEFAULT:None
api_style (literal): the API style for function call. For Azure OpenAI API, use version 2023-12-01-preview or later. "function" style will be deprecated. For earlier version use "function" if "tool" doesn't work. See Azure OpenAI documentation for details.
TYPE:Literal['function', 'tool']DEFAULT:'tool'
silent_override whether to suppress any override warning messages.
TYPE:boolDEFAULT:False
RETURNS DESCRIPTION
Callable[[Union[F, Tool]], Tool] The decorator for registering a function to be used by an agent.

Examples:

@user_proxy.register_for_execution()
@agent2.register_for_llm()
@agent1.register_for_llm(description="This is a very useful function")
def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
     return a + str(b * c)

For Azure OpenAI versions prior to 2023-12-01-preview, set api_style to "function" if "tool" doesn't work:

@agent2.register_for_llm(api_style="function")
def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:
     return a + str(b * c)

Source code in autogen/agentchat/conversable_agent.py

<br>3514<br>3515<br>3516<br>3517<br>3518<br>3519<br>3520<br>3521<br>3522<br>3523<br>3524<br>3525<br>3526<br>3527<br>3528<br>3529<br>3530<br>3531<br>3532<br>3533<br>3534<br>3535<br>3536<br>3537<br>3538<br>3539<br>3540<br>3541<br>3542<br>3543<br>3544<br>3545<br>3546<br>3547<br>3548<br>3549<br>3550<br>3551<br>3552<br>3553<br>3554<br>3555<br>3556<br>3557<br>3558<br>3559<br>3560<br>3561<br>3562<br>3563<br>3564<br>3565<br>3566<br>3567<br>3568<br>3569<br>3570<br>3571<br>3572<br>3573<br>3574<br>3575<br>3576<br>3577<br>3578<br>3579<br>3580<br>3581<br>3582<br>3583<br>3584<br>3585<br>3586<br>3587<br>3588<br> <br>def register_for_llm(<br> self,<br> *,<br> name: Optional[str] = None,<br> description: Optional[str] = None,<br> api_style: Literal["function", "tool"] = "tool",<br> silent_override: bool = False,<br>) -> Callable[[Union[F, Tool]], Tool]:<br> """Decorator factory for registering a function to be used by an agent.<br> It's return value is used to decorate a function to be registered to the agent. The function uses type hints to<br> specify the arguments and return type. The function name is used as the default name for the function,<br> but a custom name can be provided. The function description is used to describe the function in the<br> agent's configuration.<br> Args:<br> name (optional(str)): name of the function. If None, the function name will be used (default: None).<br> description (optional(str)): description of the function (default: None). It is mandatory<br> for the initial decorator, but the following ones can omit it.<br> api_style: (literal): the API style for function call.<br> For Azure OpenAI API, use version 2023-12-01-preview or later.<br> `"function"` style will be deprecated. For earlier version use<br> `"function"` if `"tool"` doesn't work.<br> See [Azure OpenAI documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/function-calling?tabs=python) for details.<br> silent_override (bool): whether to suppress any override warning messages.<br> Returns:<br> The decorator for registering a function to be used by an agent.<br> Examples:<br> ```<br> @user_proxy.register_for_execution()<br> @agent2.register_for_llm()<br> @agent1.register_for_llm(description="This is a very useful function")<br> def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:<br> return a + str(b * c)<br> ```<br> For Azure OpenAI versions prior to 2023-12-01-preview, set `api_style`<br> to `"function"` if `"tool"` doesn't work:<br> ```<br> @agent2.register_for_llm(api_style="function")<br> def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14) -> str:<br> return a + str(b * c)<br> ```<br> """<br> def _decorator(<br> func_or_tool: Union[F, Tool], name: Optional[str] = name, description: Optional[str] = description<br> ) -> Tool:<br> """Decorator for registering a function to be used by an agent.<br> Args:<br> func_or_tool: The function or the tool to be registered.<br> name: The name of the function or the tool.<br> description: The description of the function or the tool.<br> Returns:<br> The function to be registered, with the _description attribute set to the function description.<br> Raises:<br> ValueError: if the function description is not provided and not propagated by a previous decorator.<br> RuntimeError: if the LLM config is not set up before registering a function.<br> """<br> tool = self._create_tool_if_needed(func_or_tool, name, description)<br> self._register_for_llm(tool, api_style, silent_override=silent_override)<br> if tool not in self._tools:<br> self._tools.append(tool)<br> return tool<br> return _decorator<br>

``register_for_execution #

register_for_execution(name=None, description=None, *, serialize=True, silent_override=False)

Decorator factory for registering a function to be executed by an agent.

It's return value is used to decorate a function to be registered to the agent.

PARAMETER DESCRIPTION
name name of the function. If None, the function name will be used (default: None).
TYPE:Optional[str]DEFAULT:None
description description of the function (default: None).
TYPE:Optional[str]DEFAULT:None
serialize whether to serialize the return value
TYPE:boolDEFAULT:True
silent_override whether to suppress any override warning messages
TYPE:boolDEFAULT:False
RETURNS DESCRIPTION
Callable[[Union[Tool, F]], Tool] The decorator for registering a function to be used by an agent.

Examples:

@user_proxy.register_for_execution()
@agent2.register_for_llm()
@agent1.register_for_llm(description="This is a very useful function")
def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14):
     return a + str(b * c)

Source code in autogen/agentchat/conversable_agent.py

<br>3663<br>3664<br>3665<br>3666<br>3667<br>3668<br>3669<br>3670<br>3671<br>3672<br>3673<br>3674<br>3675<br>3676<br>3677<br>3678<br>3679<br>3680<br>3681<br>3682<br>3683<br>3684<br>3685<br>3686<br>3687<br>3688<br>3689<br>3690<br>3691<br>3692<br>3693<br>3694<br>3695<br>3696<br>3697<br>3698<br>3699<br>3700<br>3701<br>3702<br>3703<br>3704<br>3705<br>3706<br>3707<br>3708<br>3709<br>3710<br>3711<br>3712<br>3713<br>3714<br>3715<br>3716<br>3717<br>3718<br>3719<br>3720<br>3721<br> <br>def register_for_execution(<br> self,<br> name: Optional[str] = None,<br> description: Optional[str] = None,<br> *,<br> serialize: bool = True,<br> silent_override: bool = False,<br>) -> Callable[[Union[Tool, F]], Tool]:<br> """Decorator factory for registering a function to be executed by an agent.<br> It's return value is used to decorate a function to be registered to the agent.<br> Args:<br> name: name of the function. If None, the function name will be used (default: None).<br> description: description of the function (default: None).<br> serialize: whether to serialize the return value<br> silent_override: whether to suppress any override warning messages<br> Returns:<br> The decorator for registering a function to be used by an agent.<br> Examples:<br> ```<br> @user_proxy.register_for_execution()<br> @agent2.register_for_llm()<br> @agent1.register_for_llm(description="This is a very useful function")<br> def my_function(a: Annotated[str, "description of a parameter"] = "a", b: int, c=3.14):<br> return a + str(b * c)<br> ```<br> """<br> def _decorator(<br> func_or_tool: Union[Tool, F], name: Optional[str] = name, description: Optional[str] = description<br> ) -> Tool:<br> """Decorator for registering a function to be used by an agent.<br> Args:<br> func_or_tool: the function or the tool to be registered.<br> name: the name of the function.<br> description: the description of the function.<br> Returns:<br> The tool to be registered.<br> """<br> tool = self._create_tool_if_needed(func_or_tool, name, description)<br> chat_context = ChatContext(self)<br> chat_context_params = {param: chat_context for param in tool._chat_context_param_names}<br> self.register_function(<br> {tool.name: self._wrap_function(tool.func, chat_context_params, serialize=serialize)},<br> silent_override=silent_override,<br> )<br> return tool<br> return _decorator<br>

``register_model_client #

register_model_client(model_client_cls, **kwargs)

Register a model client.

PARAMETER DESCRIPTION
model_client_cls A custom client class that follows the Client interface
TYPE:ModelClient
**kwargs The kwargs for the custom client class to be initialized with
TYPE:AnyDEFAULT:{}

Source code in autogen/agentchat/conversable_agent.py

<br>3723<br>3724<br>3725<br>3726<br>3727<br>3728<br>3729<br>3730<br> <br>def register_model_client(self, model_client_cls: ModelClient, **kwargs: Any):<br> """Register a model client.<br> Args:<br> model_client_cls: A custom client class that follows the Client interface<br> **kwargs: The kwargs for the custom client class to be initialized with<br> """<br> self.client.register_model_client(model_client_cls, **kwargs)<br>

``register_hook #

register_hook(hookable_method, hook)

Registers a hook to be called by a hookable method, in order to add a capability to the agent. Registered hooks are kept in lists (one per hookable method), and are called in their order of registration.

PARAMETER DESCRIPTION
hookable_method A hookable method name implemented by ConversableAgent.
TYPE:str
hook A method implemented by a subclass of AgentCapability.
TYPE:Callable

Source code in autogen/agentchat/conversable_agent.py

<br>3732<br>3733<br>3734<br>3735<br>3736<br>3737<br>3738<br>3739<br>3740<br>3741<br>3742<br>3743<br> <br>def register_hook(self, hookable_method: str, hook: Callable):<br> """Registers a hook to be called by a hookable method, in order to add a capability to the agent.<br> Registered hooks are kept in lists (one per hookable method), and are called in their order of registration.<br> Args:<br> hookable_method: A hookable method name implemented by ConversableAgent.<br> hook: A method implemented by a subclass of AgentCapability.<br> """<br> assert hookable_method in self.hook_lists, f"{hookable_method} is not a hookable method."<br> hook_list = self.hook_lists[hookable_method]<br> assert hook not in hook_list, f"{hook} is already registered as a hook."<br> hook_list.append(hook)<br>

``update_agent_state_before_reply #

update_agent_state_before_reply(messages)

Calls any registered capability hooks to update the agent's state. Primarily used to update context variables. Will, potentially, modify the messages.

Source code in autogen/agentchat/conversable_agent.py

<br>3745<br>3746<br>3747<br>3748<br>3749<br>3750<br>3751<br>3752<br>3753<br>3754<br> <br>def update_agent_state_before_reply(self, messages: list[dict[str, Any]]) -> None:<br> """Calls any registered capability hooks to update the agent's state.<br> Primarily used to update context variables.<br> Will, potentially, modify the messages.<br> """<br> hook_list = self.hook_lists["update_agent_state"]<br> # Call each hook (in order of registration) to process the messages.<br> for hook in hook_list:<br> hook(self, messages)<br>

``process_all_messages_before_reply #

process_all_messages_before_reply(messages)

Calls any registered capability hooks to process all messages, potentially modifying the messages.

Source code in autogen/agentchat/conversable_agent.py

<br>3756<br>3757<br>3758<br>3759<br>3760<br>3761<br>3762<br>3763<br>3764<br>3765<br>3766<br>3767<br> <br>def process_all_messages_before_reply(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:<br> """Calls any registered capability hooks to process all messages, potentially modifying the messages."""<br> hook_list = self.hook_lists["process_all_messages_before_reply"]<br> # If no hooks are registered, or if there are no messages to process, return the original message list.<br> if len(hook_list) == 0 or messages is None:<br> return messages<br> # Call each hook (in order of registration) to process the messages.<br> processed_messages = messages<br> for hook in hook_list:<br> processed_messages = hook(processed_messages)<br> return processed_messages<br>

``process_last_received_message #

process_last_received_message(messages)

Calls any registered capability hooks to use and potentially modify the text of the last message, as long as the last message is not a function call or exit command.

Source code in autogen/agentchat/conversable_agent.py

<br>3769<br>3770<br>3771<br>3772<br>3773<br>3774<br>3775<br>3776<br>3777<br>3778<br>3779<br>3780<br>3781<br>3782<br>3783<br>3784<br>3785<br>3786<br>3787<br>3788<br>3789<br>3790<br>3791<br>3792<br>3793<br>3794<br>3795<br>3796<br>3797<br>3798<br>3799<br>3800<br>3801<br>3802<br>3803<br>3804<br>3805<br>3806<br>3807<br>3808<br> <br>def process_last_received_message(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:<br> """Calls any registered capability hooks to use and potentially modify the text of the last message,<br> as long as the last message is not a function call or exit command.<br> """<br> # If any required condition is not met, return the original message list.<br> hook_list = self.hook_lists["process_last_received_message"]<br> if len(hook_list) == 0:<br> return messages # No hooks registered.<br> if messages is None:<br> return None # No message to process.<br> if len(messages) == 0:<br> return messages # No message to process.<br> last_message = messages[-1]<br> if "function_call" in last_message:<br> return messages # Last message is a function call.<br> if "context" in last_message:<br> return messages # Last message contains a context key.<br> if "content" not in last_message:<br> return messages # Last message has no content.<br> user_content = last_message["content"]<br> if not isinstance(user_content, str) and not isinstance(user_content, list):<br> # if the user_content is a string, it is for regular LLM<br> # if the user_content is a list, it should follow the multimodal LMM format.<br> return messages<br> if user_content == "exit":<br> return messages # Last message is an exit command.<br> # Call each hook (in order of registration) to process the user's message.<br> processed_user_content = user_content<br> for hook in hook_list:<br> processed_user_content = hook(processed_user_content)<br> if processed_user_content == user_content:<br> return messages # No hooks actually modified the user's message.<br> # Replace the last user message with the expanded one.<br> messages = messages.copy()<br> messages[-1]["content"] = processed_user_content<br> return messages<br>

``print_usage_summary #

print_usage_summary(mode=['actual', 'total'])

Print the usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3810<br>3811<br>3812<br>3813<br>3814<br>3815<br>3816<br>3817<br>3818<br>3819<br> <br>def print_usage_summary(self, mode: Union[str, list[str]] = ["actual", "total"]) -> None:<br> """Print the usage summary."""<br> iostream = IOStream.get_default()<br> if self.client is None:<br> iostream.send(ConversableAgentUsageSummaryNoCostIncurredEvent(recipient=self))<br> else:<br> iostream.send(ConversableAgentUsageSummaryEvent(recipient=self))<br> if self.client is not None:<br> self.client.print_usage_summary(mode)<br>

``get_actual_usage #

get_actual_usage()

Get the actual usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3821<br>3822<br>3823<br>3824<br>3825<br>3826<br> <br>def get_actual_usage(self) -> Union[None, dict[str, int]]:<br> """Get the actual usage summary."""<br> if self.client is None:<br> return None<br> else:<br> return self.client.actual_usage_summary<br>

``get_total_usage #

get_total_usage()

Get the total usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3828<br>3829<br>3830<br>3831<br>3832<br>3833<br> <br>def get_total_usage(self) -> Union[None, dict[str, int]]:<br> """Get the total usage summary."""<br> if self.client is None:<br> return None<br> else:<br> return self.client.total_usage_summary<br>

``register_handoff #

register_handoff(condition)

Register a single handoff condition (OnContextCondition or OnCondition).

PARAMETER DESCRIPTION
condition The condition to add (OnContextCondition, OnCondition)
TYPE:Union[OnContextCondition, OnCondition]

Source code in autogen/agentchat/conversable_agent.py

<br>3979<br>3980<br>3981<br>3982<br>3983<br>3984<br>3985<br>3986<br> <br>def register_handoff(self, condition: Union["OnContextCondition", "OnCondition"]) -> None:<br> """<br> Register a single handoff condition (OnContextCondition or OnCondition).<br> Args:<br> condition: The condition to add (OnContextCondition, OnCondition)<br> """<br> self.handoffs.add(condition)<br>

``register_handoffs #

register_handoffs(conditions)

Register multiple handoff conditions (OnContextCondition or OnCondition).

PARAMETER DESCRIPTION
conditions List of conditions to add
TYPE:list[Union[OnContextCondition, OnCondition]]

Source code in autogen/agentchat/conversable_agent.py

<br>3988<br>3989<br>3990<br>3991<br>3992<br>3993<br>3994<br>3995<br> <br>def register_handoffs(self, conditions: list[Union["OnContextCondition", "OnCondition"]]) -> None:<br> """<br> Register multiple handoff conditions (OnContextCondition or OnCondition).<br> Args:<br> conditions: List of conditions to add<br> """<br> self.handoffs.add_many(conditions)<br>

Back to top