# UserProxyAgent

## ``autogen.UserProxyAgent [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent "Permanent link")

```
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`](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/ConversableAgent/#autogen.ConversableAgent.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.

Initialize a UserProxyAgent.

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](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.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](https://docs.ag2.ai/latest/docs/api-reference/autogen/ConversableAgent).
```

Source code in `autogen/agentchat/user_proxy_agent.py`

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

### ``name`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.name "Permanent link")

```
name
```

Get the name of the agent.

### ``description`property``writable`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.description "Permanent link")

```
description
```

Get the description of the agent.

### ``system\_message`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.system_message "Permanent link")

```
system_message
```

Return the system message.

### ``DEFAULT\_CONFIG`class-attribute``instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.DEFAULT_CONFIG "Permanent link")

```
DEFAULT_CONFIG = False
```

### ``MAX\_CONSECUTIVE\_AUTO\_REPLY`class-attribute``instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.MAX_CONSECUTIVE_AUTO_REPLY "Permanent link")

```
MAX_CONSECUTIVE_AUTO_REPLY = 100
```

### ``DEFAULT\_SUMMARY\_PROMPT`class-attribute``instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.DEFAULT_SUMMARY_PROMPT "Permanent link")

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

### ``DEFAULT\_SUMMARY\_METHOD`class-attribute``instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.DEFAULT_SUMMARY_METHOD "Permanent link")

```
DEFAULT_SUMMARY_METHOD = 'last_msg'
```

### ``llm\_config`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.llm_config "Permanent link")

```
llm_config = _validate_llm_config(llm_config)
```

### ``handoffs`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.handoffs "Permanent link")

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

### ``input\_guardrails`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.input_guardrails "Permanent link")

```
input_guardrails = []
```

### ``output\_guardrails`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.output_guardrails "Permanent link")

```
output_guardrails = []
```

### ``silent`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.silent "Permanent link")

```
silent = silent
```

### ``run\_executor`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run_executor "Permanent link")

```
run_executor = None
```

### ``client`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.client "Permanent link")

```
client = _create_client(llm_config)
```

### ``client\_cache`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.client_cache "Permanent link")

```
client_cache = None
```

### ``human\_input\_mode`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.human_input_mode "Permanent link")

```
human_input_mode = human_input_mode
```

### ``reply\_at\_receive`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.reply_at_receive "Permanent link")

```
reply_at_receive = defaultdict(bool)
```

### ``context\_variables`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.context_variables "Permanent link")

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

### ``hook\_lists`instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.hook_lists "Permanent link")

```
hook_lists = {'process_last_received_message': [], 'process_all_messages_before_reply': [], 'process_message_before_send': [], 'update_agent_state': [], 'safeguard_tool_inputs': [], 'safeguard_tool_outputs': [], 'safeguard_llm_inputs': [], 'safeguard_llm_outputs': [], 'safeguard_human_inputs': []}
```

### ``code\_executor`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.code_executor "Permanent link")

```
code_executor
```

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

### ``chat\_messages`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.chat_messages "Permanent link")

```
chat_messages
```

A dictionary of conversations from agent to list of messages.

### ``use\_docker`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.use_docker "Permanent link")

```
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.

### ``tools`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.tools "Permanent link")

```
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\_map`property`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.function_map "Permanent link")

```
function_map
```

Return the function map.

### ``DEFAULT\_USER\_PROXY\_AGENT\_DESCRIPTIONS`class-attribute``instance-attribute`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.DEFAULT_USER_PROXY_AGENT_DESCRIPTIONS "Permanent link")

````
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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.send "Permanent link")

```
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](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create). For example, one agent can send a message A as:<br>**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>1091<br>1092<br>1093<br>1094<br>1095<br>1096<br>1097<br>1098<br>1099<br>1100<br>1101<br>1102<br>1103<br>1104<br>1105<br>1106<br>1107<br>1108<br>1109<br>1110<br>1111<br>1112<br>1113<br>1114<br>1115<br>1116<br>1117<br>1118<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>``` | ````<br>def send(<br>    self,<br>    message: dict[str, Any] | str,<br>    recipient: Agent,<br>    request_reply: bool | None = None,<br>    silent: bool | None = 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, recipient, role="assistant", name=self.name)<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\_send`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_send "Permanent link")

```
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>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>1166<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>``` | ````<br>async def a_send(<br>    self,<br>    message: dict[str, Any] | str,<br>    recipient: Agent,<br>    request_reply: bool | None = None,<br>    silent: bool | None = 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, recipient, role="assistant", name=self.name)<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.receive "Permanent link")

```
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](https://docs.ag2.ai/latest/docs/api-reference/autogen/OpenAIWrapper/#autogen.OpenAIWrapper.create).<br>**TYPE:**`dict or str` |
| `sender` | sender of an Agent instance.<br>**TYPE:**`Agent` |
| `request_reply` | whether a reply is requested from the sender. If None, the value is determined by `self.reply_at_receive[sender]`.<br>**TYPE:**`bool or None`**DEFAULT:**`None` |
| `silent` | (Experimental) whether to print the message received.<br>**TYPE:**`bool or None`**DEFAULT:**`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>1208<br>1209<br>1210<br>1211<br>1212<br>1213<br>1214<br>1215<br>1216<br>1217<br>1218<br>1219<br>1220<br>1221<br>1222<br>1223<br>1224<br>1225<br>1226<br>1227<br>1228<br>1229<br>1230<br>1231<br>1232<br>1233<br>1234<br>1235<br>1236<br>1237<br>1238<br>1239<br>1240<br>1241<br>1242<br>1243<br>``` | ```<br>def receive(<br>    self,<br>    message: dict[str, Any] | str,<br>    sender: Agent,<br>    request_reply: bool | None = None,<br>    silent: bool | None = 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\_receive`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_receive "Permanent link")

```
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>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>1272<br>1273<br>1274<br>1275<br>1276<br>1277<br>1278<br>1279<br>1280<br>``` | ```<br>async def a_receive(<br>    self,<br>    message: dict[str, Any] | str,<br>    sender: Agent,<br>    request_reply: bool | None = None,<br>    silent: bool | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_reply "Permanent link")

```
generate_reply(messages=None, sender=None, exclude=())
```

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.<br>**TYPE:**`list[dict[str, Any]] | None`**DEFAULT:**`None` |
| `sender` | sender of an Agent instance.<br>**TYPE:**`Optional[Agent]`**DEFAULT:**`None` |
| `exclude` | 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.<br>**TYPE:**`Container[Any]`**DEFAULT:**`()` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `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>3144<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>def generate_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Optional["Agent"] = None,<br>    exclude: Container[Any] = (),<br>) -> str | dict[str, Any] | None:<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>        exclude: 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 reply_func in exclude:<br>            continue<br>        if is_coroutine_callable(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\_reply`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_generate_reply "Permanent link")

```
a_generate_reply(messages=None, sender=None, exclude=())
```

(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 |
| --- | --- |
| `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>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>3237<br>3238<br>3239<br>3240<br>3241<br>3242<br>3243<br>3244<br>3245<br>3246<br>3247<br>3248<br>3249<br>3250<br>3251<br>3252<br>3253<br>3254<br>3255<br>3256<br>3257<br>3258<br>3259<br>3260<br>3261<br>3262<br>3263<br>3264<br>3265<br>3266<br>3267<br>3268<br>3269<br>3270<br>3271<br>3272<br>3273<br>3274<br>3275<br>3276<br>3277<br>3278<br>3279<br>3280<br>3281<br>3282<br>3283<br>3284<br>3285<br>3286<br>3287<br>3288<br>3289<br>3290<br>3291<br>``` | ```<br>async def a_generate_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Optional["Agent"] = None,<br>    exclude: Container[Any] = (),<br>) -> 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>        exclude: 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>    # Get sync functions to skip (those with async equivalents)<br>    sync_to_skip = self._get_sync_funcs_to_skip_in_async_chat()<br>    for reply_func_tuple in self._reply_func_list:<br>        reply_func = reply_func_tuple["reply_func"]<br>        if reply_func in exclude:<br>            continue<br>        if reply_func in sync_to_skip:<br>            continue<br>        if self._match_trigger(reply_func_tuple["trigger"], sender):<br>            if is_coroutine_callable(reply_func):<br>                final, reply = await reply_func(<br>                    self,<br>                    messages=messages,<br>                    sender=sender,<br>                    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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.set_ui_tools "Permanent link")

```
set_ui_tools(tools)
```

Set the UI tools for the agent.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `tools` | a list of tools to be set.<br>**TYPE:**`list[Tool]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4039<br>4040<br>4041<br>4042<br>4043<br>4044<br>4045<br>4046<br>4047<br>4048<br>4049<br>4050<br>4051<br>4052<br>4053<br>4054<br>4055<br>4056<br>4057<br>4058<br>4059<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.unset_ui_tools "Permanent link")

```
unset_ui_tools(tools)
```

Unset the UI tools for the agent.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `tools` | a list of tools to be unset.<br>**TYPE:**`list[Tool]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4061<br>4062<br>4063<br>4064<br>4065<br>4066<br>4067<br>4068<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.update_system_message "Permanent link")

```
update_system_message(system_message)
```

Update the system message.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `system_message` | system message for the ChatCompletion inference.<br>**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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_reply "Permanent link")

```
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`.<br>**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>```<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>**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.<br>**TYPE:**`int`**DEFAULT:**`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.<br>**TYPE:**`Any`**DEFAULT:**`None` |
| `reset_config` | the function to reset the config. The function returns None. Signature: `def reset_config(config: Any)`<br>**TYPE:**`Callable`**DEFAULT:**`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.<br>**TYPE:**`bool`**DEFAULT:**`False` |
| `remove_other_reply_funcs` | whether to remove other reply functions when registering this reply function.<br>**TYPE:**`bool`**DEFAULT:**`False` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>607<br>608<br>``` | ````<br>def register_reply(<br>    self,<br>    trigger: type[Agent] | str | Agent | Callable[[Agent], bool] | list,<br>    reply_func: Callable,<br>    position: int = 0,<br>    config: Any | None = None,<br>    reset_config: Callable[..., Any] | None = 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 is_coroutine_callable(reply_func),<br>        },<br>    )<br>```` |

### ``replace\_reply\_func [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.replace_reply_func "Permanent link")

```
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.<br>**TYPE:**`Callable` |
| `new_reply_func` | the new reply function to replace the old one.<br>**TYPE:**`Callable` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>610<br>611<br>612<br>613<br>614<br>615<br>616<br>617<br>618<br>619<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_nested_chats "Permanent link")

```
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.<br>**TYPE:**`list` |
| `trigger` | refer to `register_reply` for details.<br>**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>```<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>**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.<br>**TYPE:**`int`**DEFAULT:**`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.<br>**TYPE:**`bool | None`**DEFAULT:**`None` |
| `kwargs` | Ref to `register_reply` for details.<br>**TYPE:**`Any`**DEFAULT:**`{}` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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: type[Agent] | str | Agent | Callable[[Agent], bool] | list,<br>    reply_func_from_nested_chats: str | Callable[..., Any] = "summary_from_nested_chats",<br>    position: int = 2,<br>    use_async: 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 is_coroutine_callable(reply_func_from_nested_chats):<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.update_max_consecutive_auto_reply "Permanent link")

```
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.<br>**TYPE:**`int` |
| `sender` | when the sender is provided, only update the max\_consecutive\_auto\_reply for that sender.<br>**TYPE:**`Agent`**DEFAULT:**`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: Agent | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.max_consecutive_auto_reply "Permanent link")

```
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: Agent | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.chat_messages_for_summary "Permanent link")

```
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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.last_message "Permanent link")

```
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.<br>**TYPE:**`Agent`**DEFAULT:**`None` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `dict[str, Any] | None` | 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>1009<br>``` | ```<br>def last_message(self, agent: Agent | None = None) -> dict[str, Any] | None:<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] if conversation else None<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>    messages = self._oai_messages[agent]<br>    return messages[-1] if messages else None<br>``` |

### ``initiate\_chat [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.initiate_chat "Permanent link")

```
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.<br>**TYPE:**`ConversableAgent` |
| `clear_history` | whether to clear the chat history with the agent. Default is True.<br>**TYPE:**`bool`**DEFAULT:**`True` |
| `silent` | (Experimental) whether to print the messages for this conversation. Default is False.<br>**TYPE:**`bool or None`**DEFAULT:**`False` |
| `cache` | the cache client to be used for this conversation. Default is None.<br>**TYPE:**`AbstractCache or None`**DEFAULT:**`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.<br>**TYPE:**`int or None`**DEFAULT:**`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.<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>```<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>**TYPE:**`str or callable`**DEFAULT:**`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 an 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".<br>**TYPE:**`dict`**DEFAULT:**`{}` |
| `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>```<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>```<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.<br>  <br>Example of a callable message (returning a string):<br>  <br>  <br>  <br>```<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>  <br>  <br>  <br>Example of a callable message (returning a dict):<br>  <br>  <br>  <br>```<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>  <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.<br>**TYPE:**`Any`**DEFAULT:**`{}` |

| RAISES | DESCRIPTION |
| --- | --- |
| `RuntimeError` | if any async reply functions are registered and not ignored in sync chat. |

| RETURNS | DESCRIPTION |
| --- | --- |
| `ChatResult` | an ChatResult object.<br>**TYPE:**`ChatResult` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>1336<br>1337<br>1338<br>1339<br>1340<br>1341<br>1342<br>1343<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>``` | ````<br>def initiate_chat(<br>    self,<br>    recipient: "ConversableAgent",<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: dict[str, Any] | str | Callable[..., Any] | None = 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 an 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>        is_termination = 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>                last_message = self.chat_messages[recipient][-1]<br>                if self._should_terminate_chat(recipient, last_message):<br>                    break<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(<br>                TerminationEvent(<br>                    termination_reason=f"Maximum turns ({max_turns}) reached", sender=self, recipient=recipient<br>                )<br>            )<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run "Permanent link")

```
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)
```

Run a chat with an optional recipient agent, returning a response that can be processed or iterated over.

This method starts a chat in a background thread and returns immediately with a RunResponse object that provides access to events as they occur.

For step-by-step execution with control over each event, use run\_iter() instead.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `recipient` | The recipient agent to chat with. If None, creates a temporary executor agent for single-agent mode.<br>**TYPE:**`Optional[ConversableAgent]`**DEFAULT:**`None` |
| `clear_history` | Whether to clear the chat history with the agent. Default is True.<br>**TYPE:**`bool`**DEFAULT:**`True` |
| `silent` | Whether to suppress console output. Default is False.<br>**TYPE:**`bool | None`**DEFAULT:**`False` |
| `cache` | Cache client for this conversation. Default is None.<br>**TYPE:**`AbstractCache | None`**DEFAULT:**`None` |
| `max_turns` | Maximum number of conversation turns. One turn is one round trip. If None, chat continues until termination condition is met.<br>**TYPE:**`int | None`**DEFAULT:**`None` |
| `summary_method` | Method to summarize chat. Default is "last\_msg". Options: "last\_msg", "reflection\_with\_llm", or a callable.<br>**TYPE:**`str | Callable[..., Any] | None`**DEFAULT:**`DEFAULT_SUMMARY_METHOD` |
| `summary_args` | Arguments passed to summary\_method.<br>**TYPE:**`dict[str, Any] | None`**DEFAULT:**`{}` |
| `message` | Initial message to send. Can be a string, dict, or callable.<br>**TYPE:**`dict[str, Any] | str | Callable[..., Any] | None`**DEFAULT:**`None` |
| `executor_kwargs` | Kwargs for executor agent (single-agent mode only).<br>**TYPE:**`dict[str, Any] | None`**DEFAULT:**`None` |
| `tools` | Tools to register with the executor (single-agent mode only).<br>**TYPE:**`Tool | Iterable[Tool] | None`**DEFAULT:**`None` |
| `user_input` | Whether to enable user input mode. Default is False.<br>**TYPE:**`bool | None`**DEFAULT:**`False` |
| `msg_to` | Direction of initial message - "agent" or "user". Default is "agent".<br>**TYPE:**`str | None`**DEFAULT:**`'agent'` |
| `**kwargs` | Additional arguments passed to initiate\_chat.<br>**TYPE:**`Any`**DEFAULT:**`{}` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `RunResponseProtocol` | RunResponseProtocol |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>1498<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>1608<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>``` | ```<br>def run(<br>    self,<br>    recipient: Optional["ConversableAgent"] = None,<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: dict[str, Any] | str | Callable[..., Any] | None = None,<br>    executor_kwargs: dict[str, Any] | None = None,<br>    tools: Tool | Iterable[Tool] | None = None,<br>    user_input: bool | None = False,<br>    msg_to: str | None = "agent",<br>    **kwargs: Any,<br>) -> RunResponseProtocol:<br>    """Run a chat with an optional recipient agent, returning a response that can be<br>    processed or iterated over.<br>    This method starts a chat in a background thread and returns immediately with a<br>    RunResponse object that provides access to events as they occur.<br>    For step-by-step execution with control over each event, use run_iter() instead.<br>    Args:<br>        recipient: The recipient agent to chat with. If None, creates a temporary<br>            executor agent for single-agent mode.<br>        clear_history: Whether to clear the chat history with the agent. Default is True.<br>        silent: Whether to suppress console output. Default is False.<br>        cache: Cache client for this conversation. Default is None.<br>        max_turns: Maximum number of conversation turns. One turn is one round trip.<br>            If None, chat continues until termination condition is met.<br>        summary_method: Method to summarize chat. Default is "last_msg".<br>            Options: "last_msg", "reflection_with_llm", or a callable.<br>        summary_args: Arguments passed to summary_method.<br>        message: Initial message to send. Can be a string, dict, or callable.<br>        executor_kwargs: Kwargs for executor agent (single-agent mode only).<br>        tools: Tools to register with the executor (single-agent mode only).<br>        user_input: Whether to enable user input mode. Default is False.<br>        msg_to: Direction of initial message - "agent" or "user". Default is "agent".<br>        **kwargs: Additional arguments passed to initiate_chat.<br>    Returns:<br>        RunResponseProtocol<br>    """<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>        daemon=True,<br>    ).start()<br>    return response<br>``` |

### ``run\_iter [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run_iter "Permanent link")

```
run_iter(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', yield_on=None, **kwargs)
```

Run a chat with iterator-based stepped execution.

Iterate over events as they occur. The background thread blocks after each event until you advance to the next iteration.

Example

for event in agent.run\_iter(message="Hello"): if isinstance(event, TextEvent): print(event.content.content) if should\_abort(event): break # Cleanup happens automatically

| RETURNS | DESCRIPTION |
| --- | --- |
| `RunIterResponse` | An iterator that yields events as they occur.<br>**TYPE:**`RunIterResponse` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>1678<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>``` | ```<br>def run_iter(<br>    self,<br>    recipient: Optional["ConversableAgent"] = None,<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: dict[str, Any] | str | Callable[..., Any] | None = None,<br>    executor_kwargs: dict[str, Any] | None = None,<br>    tools: Tool | Iterable[Tool] | None = None,<br>    user_input: bool | None = False,<br>    msg_to: str | None = "agent",<br>    yield_on: Sequence[type["BaseEvent"]] | None = None,<br>    **kwargs: Any,<br>) -> RunIterResponse:<br>    """Run a chat with iterator-based stepped execution.<br>    Iterate over events as they occur. The background thread blocks after each<br>    event until you advance to the next iteration.<br>    Example:<br>        for event in agent.run_iter(message="Hello"):<br>            if isinstance(event, TextEvent):<br>                print(event.content.content)<br>            if should_abort(event):<br>                break  # Cleanup happens automatically<br>    Args:<br>        recipient: The recipient agent to chat with. If None, creates a temporary<br>            executor agent for single-agent mode.<br>        clear_history: Whether to clear the chat history with the agent. Default is True.<br>        silent: Whether to suppress console output. Default is False.<br>        cache: Cache client for this conversation. Default is None.<br>        max_turns: Maximum number of conversation turns. One turn is one round trip.<br>            If None, chat continues until termination condition is met.<br>        summary_method: Method to summarize chat. Default is "last_msg".<br>            Options: "last_msg", "reflection_with_llm", or a callable.<br>        summary_args: Arguments passed to summary_method.<br>        message: Initial message to send. Can be a string, dict, or callable.<br>        executor_kwargs: Kwargs for executor agent (single-agent mode only).<br>        tools: Tools to register with the executor (single-agent mode only).<br>        user_input: Whether to enable user input mode. Default is False.<br>        msg_to: Direction of initial message - "agent" or "user". Default is "agent".<br>        yield_on: List of event types to yield. If None, yields all events.<br>            Example: [TextEvent, TerminationEvent] to only yield text messages.<br>        **kwargs: Additional arguments passed to initiate_chat.<br>    Returns:<br>        RunIterResponse: An iterator that yields events as they occur.<br>    """<br>    agents = [self, recipient] if recipient else [self]<br>    def create_thread(iostream: ThreadIOStream) -> threading.Thread:<br>        if recipient is None:<br>            def initiate_chat() -> 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>                        iostream.send(ErrorEvent(error=e))<br>        else:<br>            def initiate_chat() -> 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>                        _last_speaker = (<br>                            recipient if chat_result.chat_history[-1]["name"] == recipient.name else self<br>                        )<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>                        iostream.send(ErrorEvent(error=e))<br>        return threading.Thread(target=initiate_chat, daemon=True)<br>    return RunIterResponse(<br>        start_thread_func=create_thread,<br>        yield_on=yield_on,<br>        agents=agents,<br>    )<br>``` |

### ``a\_initiate\_chat`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_initiate_chat "Permanent link")

```
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.<br>**TYPE:**`ChatResult` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>1776<br>1777<br>1778<br>1779<br>1780<br>1781<br>1782<br>1783<br>1784<br>1785<br>1786<br>1787<br>1788<br>1789<br>1790<br>1791<br>1792<br>1793<br>1794<br>1795<br>1796<br>1797<br>1798<br>1799<br>1800<br>1801<br>1802<br>1803<br>1804<br>1805<br>1806<br>1807<br>1808<br>1809<br>1810<br>1811<br>1812<br>1813<br>1814<br>1815<br>1816<br>1817<br>1818<br>1819<br>1820<br>1821<br>1822<br>1823<br>1824<br>1825<br>1826<br>1827<br>1828<br>1829<br>1830<br>1831<br>1832<br>1833<br>1834<br>1835<br>1836<br>1837<br>1838<br>1839<br>1840<br>1841<br>1842<br>1843<br>1844<br>1845<br>1846<br>1847<br>1848<br>1849<br>1850<br>1851<br>1852<br>``` | ```<br>async def a_initiate_chat(<br>    self,<br>    recipient: "ConversableAgent",<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: str | Callable[..., Any] | None = 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>        is_termination = 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>                last_message = self.chat_messages[recipient][-1]<br>                if self._should_terminate_chat(recipient, last_message):<br>                    break<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(<br>                TerminationEvent(<br>                    termination_reason=f"Maximum turns ({max_turns}) reached", sender=self, recipient=recipient<br>                )<br>            )<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\_run`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_run "Permanent link")

```
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)
```

Async version of run().

For step-by-step execution with control over each event, use a\_run\_iter() instead.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>1854<br>1855<br>1856<br>1857<br>1858<br>1859<br>1860<br>1861<br>1862<br>1863<br>1864<br>1865<br>1866<br>1867<br>1868<br>1869<br>1870<br>1871<br>1872<br>1873<br>1874<br>1875<br>1876<br>1877<br>1878<br>1879<br>1880<br>1881<br>1882<br>1883<br>1884<br>1885<br>1886<br>1887<br>1888<br>1889<br>1890<br>1891<br>1892<br>1893<br>1894<br>1895<br>1896<br>1897<br>1898<br>1899<br>1900<br>1901<br>1902<br>1903<br>1904<br>1905<br>1906<br>1907<br>1908<br>1909<br>1910<br>1911<br>1912<br>1913<br>1914<br>1915<br>1916<br>1917<br>1918<br>1919<br>1920<br>1921<br>1922<br>1923<br>1924<br>1925<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>1939<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>``` | ```<br>async def a_run(<br>    self,<br>    recipient: Optional["ConversableAgent"] = None,<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: dict[str, Any] | str | Callable[..., Any] | None = None,<br>    executor_kwargs: dict[str, Any] | None = None,<br>    tools: Tool | Iterable[Tool] | None = None,<br>    user_input: bool | None = False,<br>    msg_to: str | None = "agent",<br>    **kwargs: Any,<br>) -> AsyncRunResponseProtocol:<br>    """Async version of run().<br>    For step-by-step execution with control over each event, use a_run_iter() instead.<br>    """<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.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>                    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.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>                    iostream.send(ErrorEvent(error=e))<br>    asyncio.create_task(initiate_chat())<br>    return response<br>``` |

### ``a\_run\_iter [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_run_iter "Permanent link")

```
a_run_iter(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', yield_on=None, **kwargs)
```

Async version of run\_iter() for async contexts.

Iterate over events as they occur using async for. The background thread blocks after each event until you advance to the next iteration.

Example

async for event in agent.a\_run\_iter(message="Hello"): if isinstance(event, TextEvent): print(event.content.content) if should\_abort(event): break # Cleanup happens automatically

| RETURNS | DESCRIPTION |
| --- | --- |
| `AsyncRunIterResponse` | An async iterator that yields events as they occur.<br>**TYPE:**`AsyncRunIterResponse` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>2004<br>2005<br>2006<br>2007<br>2008<br>2009<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>2075<br>2076<br>2077<br>2078<br>2079<br>2080<br>2081<br>2082<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>2095<br>2096<br>2097<br>2098<br>2099<br>2100<br>2101<br>2102<br>2103<br>2104<br>2105<br>``` | ```<br>def a_run_iter(<br>    self,<br>    recipient: Optional["ConversableAgent"] = None,<br>    clear_history: bool = True,<br>    silent: bool | None = False,<br>    cache: AbstractCache | None = None,<br>    max_turns: int | None = None,<br>    summary_method: str | Callable[..., Any] | None = DEFAULT_SUMMARY_METHOD,<br>    summary_args: dict[str, Any] | None = {},<br>    message: dict[str, Any] | str | Callable[..., Any] | None = None,<br>    executor_kwargs: dict[str, Any] | None = None,<br>    tools: Tool | Iterable[Tool] | None = None,<br>    user_input: bool | None = False,<br>    msg_to: str | None = "agent",<br>    yield_on: Sequence[type["BaseEvent"]] | None = None,<br>    **kwargs: Any,<br>) -> AsyncRunIterResponse:<br>    """Async version of run_iter() for async contexts.<br>    Iterate over events as they occur using async for. The background thread blocks<br>    after each event until you advance to the next iteration.<br>    Example:<br>        async for event in agent.a_run_iter(message="Hello"):<br>            if isinstance(event, TextEvent):<br>                print(event.content.content)<br>            if should_abort(event):<br>                break  # Cleanup happens automatically<br>    Args:<br>        recipient: The recipient agent to chat with. If None, creates a temporary<br>            executor agent for single-agent mode.<br>        clear_history: Whether to clear the chat history with the agent. Default is True.<br>        silent: Whether to suppress console output. Default is False.<br>        cache: Cache client for this conversation. Default is None.<br>        max_turns: Maximum number of conversation turns. One turn is one round trip.<br>            If None, chat continues until termination condition is met.<br>        summary_method: Method to summarize chat. Default is "last_msg".<br>            Options: "last_msg", "reflection_with_llm", or a callable.<br>        summary_args: Arguments passed to summary_method.<br>        message: Initial message to send. Can be a string, dict, or callable.<br>        executor_kwargs: Kwargs for executor agent (single-agent mode only).<br>        tools: Tools to register with the executor (single-agent mode only).<br>        user_input: Whether to enable user input mode. Default is False.<br>        msg_to: Direction of initial message - "agent" or "user". Default is "agent".<br>        yield_on: List of event types to yield. If None, yields all events.<br>            Example: [TextEvent, TerminationEvent] to only yield text messages.<br>        **kwargs: Additional arguments passed to initiate_chat.<br>    Returns:<br>        AsyncRunIterResponse: An async iterator that yields events as they occur.<br>    """<br>    agents = [self, recipient] if recipient else [self]<br>    def create_thread(iostream: ThreadIOStream) -> threading.Thread:<br>        if recipient is None:<br>            async def async_initiate_chat() -> 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>                    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.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>            def run_in_thread() -> None:<br>                with IOStream.set_default(iostream):<br>                    try:<br>                        asyncio.run(async_initiate_chat())<br>                    except Exception as e:<br>                        iostream.send(ErrorEvent(error=e))<br>        else:<br>            async def async_initiate_chat() -> None:<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.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>            def run_in_thread() -> None:<br>                with IOStream.set_default(iostream):<br>                    try:<br>                        asyncio.run(async_initiate_chat())<br>                    except Exception as e:<br>                        iostream.send(ErrorEvent(error=e))<br>        return threading.Thread(target=run_in_thread, daemon=True)<br>    return AsyncRunIterResponse(<br>        start_thread_func=create_thread,<br>        yield_on=yield_on,<br>        agents=agents,<br>    )<br>``` |

### ``initiate\_chats [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.initiate_chats "Permanent link")

```
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`](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/#autogen.UserProxyAgent.initiate_chats--initiate-chat)<br>**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>2250<br>2251<br>2252<br>2253<br>2254<br>2255<br>2256<br>2257<br>2258<br>2259<br>2260<br>2261<br>2262<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.sequential_run "Permanent link")

```
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`](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/#autogen.UserProxyAgent.sequential_run--initiate-chat)<br>**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>2264<br>2265<br>2266<br>2267<br>2268<br>2269<br>2270<br>2271<br>2272<br>2273<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>2323<br>2324<br>2325<br>2326<br>2327<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, daemon=True).start()<br>    return responses<br>``` |

### ``a\_initiate\_chats`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_initiate_chats "Permanent link")

```
a_initiate_chats(chat_queue)
```

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>2329<br>2330<br>2331<br>2332<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\_run`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_sequential_run "Permanent link")

```
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`](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/#autogen.UserProxyAgent.a_sequential_run--initiate-chat)<br>**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>2334<br>2335<br>2336<br>2337<br>2338<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>2366<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>2395<br>2396<br>2397<br>2398<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.send(PostCarryoverProcessingEvent(chat_info=chat_info))<br>                    sender = chat_info["sender"]<br>                    chat_res = await sender.a_initiate_chat(**chat_info)<br>                    iostream.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>            iostream.send(ErrorEvent(error=e))<br>    asyncio.create_task(_a_initiate_chats())<br>    return responses<br>``` |

### ``get\_chat\_results [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.get_chat_results "Permanent link")

```
get_chat_results(chat_index=None)
```

A summary from the finished chats of particular agents.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>2400<br>2401<br>2402<br>2403<br>2404<br>2405<br>``` | ```<br>def get_chat_results(self, chat_index: int | None = None) -> 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.reset "Permanent link")

```
reset()
```

Reset the agent.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.stop_reply_at_receive "Permanent link")

```
stop_reply_at_receive(sender=None)
```

Reset the reply\_at\_receive of the sender.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>2420<br>2421<br>2422<br>2423<br>2424<br>2425<br>``` | ```<br>def stop_reply_at_receive(self, sender: Agent | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.reset_consecutive_auto_reply_counter "Permanent link")

```
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>2427<br>2428<br>2429<br>2430<br>2431<br>2432<br>``` | ```<br>def reset_consecutive_auto_reply_counter(self, sender: Agent | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.clear_history "Permanent link")

```
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.<br>**TYPE:**`Agent | None`**DEFAULT:**`None` |
| `nr_messages_to_preserve` | the number of newest messages to preserve in the chat history.<br>**TYPE:**`int | None`**DEFAULT:**`None` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>2446<br>2447<br>2448<br>2449<br>2450<br>2451<br>2452<br>2453<br>2454<br>2455<br>2456<br>2457<br>2458<br>2459<br>2460<br>2461<br>2462<br>2463<br>``` | ```<br>def clear_history(self, recipient: Agent | None = None, nr_messages_to_preserve: int | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_oai_reply "Permanent link")

```
generate_oai_reply(messages=None, sender=None, config=None, **kwargs)
```

Generate a reply using autogen.oai.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>2481<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>``` | ```<br>def generate_oai_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: OpenAIWrapper | None = None,<br>    **kwargs: Any,<br>) -> tuple[bool, str | dict[str, Any] | None]:<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>    # Process messages before sending to LLM, hook point for llm input monitoring<br>    processed_messages = self._process_llm_input(self._oai_system_message + messages)<br>    if processed_messages is None:<br>        return True, {"content": "LLM call blocked by safeguard", "role": "assistant"}<br>    extracted_response = self._generate_oai_reply_from_client(<br>        client,<br>        self._oai_system_message + messages,<br>        self.client_cache,<br>        **kwargs,<br>    )<br>    # Process LLM response<br>    if extracted_response is not None:<br>        processed_extracted_response = self._process_llm_output(extracted_response)<br>        if processed_extracted_response is None:<br>            raise ValueError("safeguard_llm_outputs hook returned None")<br>    return (False, None) if extracted_response is None else (True, extracted_response)<br>``` |

### ``a\_generate\_oai\_reply`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_generate_oai_reply "Permanent link")

```
a_generate_oai_reply(messages=None, sender=None, config=None, **kwargs)
```

Generate a reply using autogen.oai asynchronously.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<br>async def a_generate_oai_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>    **kwargs: Any,<br>) -> tuple[bool, str | dict[str, Any] | None]:<br>    """Generate a reply using autogen.oai asynchronously."""<br>    iostream = IOStream.get_default()<br>    def _generate_oai_reply(<br>        self, iostream: IOStream, *args: Any, **kw: Any<br>    ) -> tuple[bool, str | dict[str, Any] | None]:<br>        with IOStream.set_default(iostream):<br>            return self.generate_oai_reply(*args, **kw)<br>    return await asyncio.get_event_loop().run_in_executor(<br>        None,<br>        functools.partial(<br>            _generate_oai_reply,<br>            self=self,<br>            iostream=iostream,<br>            messages=messages,<br>            sender=sender,<br>            config=config,<br>            **kwargs,<br>        ),<br>    )<br>``` |

### ``generate\_code\_execution\_reply [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_code_execution_reply "Permanent link")

```
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>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>``` | ```<br>def generate_code_execution_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: dict[str, Any] | Literal[False] | None = 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_function_call_reply "Permanent link")

```
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](https://github.com/openai/openai-python/releases/tag/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>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>``` | ```<br>def generate_function_call_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>) -> tuple[bool, dict[str, Any] | None]:<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 is_coroutine_callable(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\_reply`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_generate_function_call_reply "Permanent link")

```
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>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>``` | ```<br>async def a_generate_function_call_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>) -> tuple[bool, dict[str, Any] | None]:<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 message.get("function_call"):<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 is_coroutine_callable(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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_tool_calls_reply "Permanent link")

```
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>2754<br>2755<br>2756<br>2757<br>2758<br>2759<br>2760<br>2761<br>2762<br>2763<br>2764<br>2765<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>``` | ```<br>def generate_tool_calls_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>) -> tuple[bool, dict[str, Any] | None]:<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>        function_name = function_call.get("name", "")<br>        if function_name == "__structured_output":<br>            return True, function_call.get("arguments", {})<br>        # Hook: Process tool input before execution<br>        processed_call = self._process_tool_input(function_call)<br>        if processed_call is None:<br>            raise ValueError("safeguard_tool_inputs hook returned None")<br>        tool_call_id = tool_call.get("id", None)<br>        func = self._function_map.get(processed_call.get("name", None), None)<br>        if is_coroutine_callable(func):<br>            coro = self.a_execute_function(processed_call, call_id=tool_call_id)<br>            _, func_return = self._run_async_in_thread(coro)<br>        else:<br>            _, func_return = self.execute_function(processed_call, call_id=tool_call_id)<br>        # Hook: Process tool output before returning<br>        processed_return = self._process_tool_output(func_return)<br>        if processed_return is None:<br>            raise ValueError("safeguard_tool_outputs hook returned None")<br>        content = processed_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\_reply`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_generate_tool_calls_reply "Permanent link")

```
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>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>2839<br>2840<br>2841<br>2842<br>2843<br>2844<br>2845<br>2846<br>2847<br>2848<br>2849<br>``` | ```<br>async def a_generate_tool_calls_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>) -> tuple[bool, dict[str, Any] | None]:<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.check_termination_and_human_reply "Permanent link")

```
check_termination_and_human_reply(messages=None, sender=None, config=None, iostream=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.<br>**TYPE:**`Optional[List[Dict]]`**DEFAULT:**`None` |
| `sender` | The agent object representing the sender of the message.<br>**TYPE:**`Optional[Agent]`**DEFAULT:**`None` |
| `config` | Configuration object, defaults to the current instance if not provided.<br>**TYPE:**`Optional[Any]`**DEFAULT:**`None` |
| `iostream` | The IOStream object to use for sending messages.<br>**TYPE:**`Optional[IOStreamProtocol]`**DEFAULT:**`None` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `bool` | A tuple containing a boolean indicating if the conversation |
| `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>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>2908<br>2909<br>2910<br>2911<br>2912<br>2913<br>2914<br>2915<br>2916<br>2917<br>2918<br>2919<br>2920<br>2921<br>2922<br>2923<br>2924<br>2925<br>2926<br>2927<br>2928<br>2929<br>2930<br>2931<br>2932<br>2933<br>2934<br>2935<br>2936<br>2937<br>2938<br>2939<br>2940<br>2941<br>2942<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>2959<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>2976<br>2977<br>2978<br>2979<br>2980<br>2981<br>2982<br>2983<br>2984<br>2985<br>2986<br>2987<br>2988<br>2989<br>2990<br>2991<br>2992<br>2993<br>2994<br>2995<br>2996<br>2997<br>2998<br>``` | ```<br>def check_termination_and_human_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>    iostream: IOStreamProtocol | None = None,<br>) -> tuple[bool, 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 (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>        iostream (Optional[IOStreamProtocol]): The IOStream object to use for sending messages.<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 or 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>            iostream=iostream,<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>                    iostream=iostream,<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>                    iostream=iostream,<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, sender=self, recipient=sender))<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\_reply`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_check_termination_and_human_reply "Permanent link")

```
a_check_termination_and_human_reply(messages=None, sender=None, config=None, iostream=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.<br>**TYPE:**`Optional[List[Dict]]`**DEFAULT:**`None` |
| `sender` | The agent object representing the sender of the message.<br>**TYPE:**`Optional[Agent]`**DEFAULT:**`None` |
| `config` | Configuration object, defaults to the current instance if not provided.<br>**TYPE:**`Optional[Any]`**DEFAULT:**`None` |
| `iostream` | The AsyncIOStreamProtocol object to use for sending messages.<br>**TYPE:**`Optional[AsyncIOStreamProtocol]`**DEFAULT:**`None` |

Returns: Tuple\[bool, Union\[str, Dict, None\]\]: A tuple containing a boolean indicating if the conversation 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>3000<br>3001<br>3002<br>3003<br>3004<br>3005<br>3006<br>3007<br>3008<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>3045<br>3046<br>3047<br>3048<br>3049<br>3050<br>3051<br>3052<br>3053<br>3054<br>3055<br>3056<br>3057<br>3058<br>3059<br>3060<br>3061<br>3062<br>3063<br>3064<br>3065<br>3066<br>3067<br>3068<br>3069<br>3070<br>3071<br>3072<br>3073<br>3074<br>3075<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>``` | ```<br>async def a_check_termination_and_human_reply(<br>    self,<br>    messages: list[dict[str, Any]] | None = None,<br>    sender: Agent | None = None,<br>    config: Any | None = None,<br>    iostream: AsyncIOStreamProtocol | None = None,<br>) -> tuple[bool, 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>        iostream (Optional[AsyncIOStreamProtocol]): The AsyncIOStreamProtocol object to use for sending messages.<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 or 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>            iostream=iostream,<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>                    iostream=iostream,<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>                    iostream=iostream,<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, sender=self, recipient=sender))<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.get_human_input "Permanent link")

```
get_human_input(prompt, *, iostream=None)
```

Get human input.

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

| PARAMETER | DESCRIPTION |
| --- | --- |
| `prompt` | prompt for the human input.<br>**TYPE:**`str` |
| `iostream` | The InputStream object to use for sending messages.<br>**TYPE:**`Optional[InputStream]`**DEFAULT:**`None` |

Returns: str: human input.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<br>def get_human_input(self, prompt: str, *, iostream: InputStream | None = None) -> 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>        iostream (Optional[InputStream]): The InputStream object to use for sending messages.<br>    Returns:<br>        str: human input.<br>    """<br>    iostream = iostream or IOStream.get_default()<br>    reply = iostream.input(prompt)<br>    # Process the human input through hooks<br>    processed_reply = self._process_human_input("" if not isinstance(reply, str) and iscoroutine(reply) else reply)<br>    if processed_reply is None:<br>        raise ValueError("safeguard_human_inputs hook returned None")<br>    self._human_input.append(processed_reply)<br>    return processed_reply<br>``` |

### ``a\_get\_human\_input`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_get_human_input "Permanent link")

```
a_get_human_input(prompt, *, iostream=None)
```

(Async) Get human input.

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

| PARAMETER | DESCRIPTION |
| --- | --- |
| `prompt` | prompt for the human input.<br>**TYPE:**`str` |
| `iostream` | The AsyncInputStream object to use for sending messages.<br>**TYPE:**`Optional[AsyncInputStream]`**DEFAULT:**`None` |

Returns: str: human input.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>3388<br>3389<br>3390<br>3391<br>3392<br>``` | ```<br>async def a_get_human_input(self, prompt: str, *, iostream: AsyncInputStream | None = None) -> 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>        iostream (Optional[AsyncInputStream]): The AsyncInputStream object to use for sending messages.<br>    Returns:<br>        str: human input.<br>    """<br>    iostream = iostream or IOStream.get_default()<br>    input_func = iostream.input<br>    if is_coroutine_callable(input_func):<br>        reply = await input_func(prompt)<br>    else:<br>        reply = await asyncio.to_thread(input_func, prompt)<br>    self._human_input.append(reply)<br>    return reply<br>``` |

### ``run\_code [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run_code "Permanent link")

```
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.<br>**TYPE:**`str` |
| `**kwargs` | other keyword arguments.<br>**TYPE:**`Any`**DEFAULT:**`{}` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `int` | A tuple of (exitcode, logs, image). |
| `exitcode` | the exit code of the code execution.<br>**TYPE:**`int` |
| `logs` | the logs of the code execution.<br>**TYPE:**`str` |
| `image` | the docker image used for the code execution.<br>**TYPE:**`str or None` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<br>def run_code(self, code: str, **kwargs: Any) -> tuple[int, str, str | None]:<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.execute_code_blocks "Permanent link")

```
execute_code_blocks(code_blocks)
```

Execute the code blocks and return the result.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.execute_function "Permanent link")

```
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".<br>**TYPE:**`dict[str, Any]` |
| `call_id` | a string to identify the tool call.<br>**TYPE:**`str | None`**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.<br>**TYPE:**`bool`**DEFAULT:**`False` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `bool` | A tuple of (is\_exec\_success, result\_dict). |
| `is_exec_success` | whether the execution is successful.<br>**TYPE:**`boolean` |
| `result_dict` | a dictionary with keys "name", "role", and "content". Value of "role" is "function".<br>**TYPE:**`tuple[bool, dict[str, Any]]` |

"function\_call" deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/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>3478<br>3479<br>3480<br>3481<br>3482<br>3483<br>3484<br>3485<br>3486<br>3487<br>3488<br>3489<br>3490<br>3491<br>3492<br>3493<br>3494<br>3495<br>3496<br>3497<br>3498<br>3499<br>3500<br>3501<br>3502<br>3503<br>3504<br>3505<br>3506<br>3507<br>3508<br>3509<br>3510<br>3511<br>3512<br>3513<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>``` | ```<br>def execute_function(<br>    self, func_call: dict[str, Any], call_id: str | None = 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>                if inspect.isawaitable(content):<br>                    async def _await_result(awaitable):<br>                        return await awaitable<br>                    content = self._run_async_in_thread(_await_result(content))<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\_function`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_execute_function "Permanent link")

```
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".<br>**TYPE:**`dict[str, Any]` |
| `call_id` | a string to identify the tool call.<br>**TYPE:**`str | None`**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.<br>**TYPE:**`bool`**DEFAULT:**`False` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>3589<br>3590<br>3591<br>3592<br>3593<br>3594<br>3595<br>3596<br>3597<br>3598<br>3599<br>3600<br>3601<br>3602<br>3603<br>3604<br>3605<br>3606<br>3607<br>3608<br>3609<br>3610<br>3611<br>3612<br>3613<br>3614<br>3615<br>3616<br>3617<br>3618<br>3619<br>3620<br>3621<br>3622<br>3623<br>3624<br>3625<br>``` | ```<br>async def a_execute_function(<br>    self, func_call: dict[str, Any], call_id: str | None = 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 is_coroutine_callable(func):<br>                    content = await func(**arguments)<br>                else:<br>                    # Fallback to sync function if the function is not async<br>                    content = func(**arguments)<br>                if inspect.isawaitable(content):<br>                    content = await content<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.generate_init_message "Permanent link")

```
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.<br>**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.<br>**TYPE:**`Any`**DEFAULT:**`{}` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `str | dict[str, Any]` | str or dict: the processed message. |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>3627<br>3628<br>3629<br>3630<br>3631<br>3632<br>3633<br>3634<br>3635<br>3636<br>3637<br>3638<br>3639<br>3640<br>3641<br>3642<br>3643<br>3644<br>``` | ```<br>def generate_init_message(self, message: dict[str, Any] | str | None, **kwargs: Any) -> 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\_message`async`[\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.a_generate_init_message "Permanent link")

```
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 |
| --- | --- |
| `str | dict[str, Any]` | str or dict: the processed message. |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>``` | ```<br>async def a_generate_init_message(<br>    self, message: dict[str, Any] | str | None, **kwargs: Any<br>) -> 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.remove_tool_for_llm "Permanent link")

```
remove_tool_for_llm(tool)
```

Remove a tool (register for LLM tool)

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>3720<br>3721<br>3722<br>3723<br>3724<br>3725<br>3726<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_function "Permanent link")

```
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.<br>**TYPE:**`dict[str, Callable[..., Any]]` |
| `silent_override` | whether to print warnings when overriding functions.<br>**TYPE:**`bool`**DEFAULT:**`False` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>3728<br>3729<br>3730<br>3731<br>3732<br>3733<br>3734<br>3735<br>3736<br>3737<br>3738<br>3739<br>3740<br>3741<br>3742<br>``` | ```<br>def register_function(self, function_map: dict[str, 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.update_function_signature "Permanent link")

```
update_function_signature(func_sig, is_remove=False, 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<br>**TYPE:**`str or dict` |
| `is_remove` | whether removing the function from llm\_config with name 'func\_sig'<br>**TYPE:**`bool`**DEFAULT:**`False` |
| `silent_override` | whether to print warnings when overriding functions.<br>**TYPE:**`bool`**DEFAULT:**`False` |

Deprecated as of [OpenAI API v1.1.0](https://github.com/openai/openai-python/releases/tag/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>3744<br>3745<br>3746<br>3747<br>3748<br>3749<br>3750<br>3751<br>3752<br>3753<br>3754<br>3755<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>3768<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>``` | ```<br>def update_function_signature(<br>    self, func_sig: str | dict[str, Any], is_remove: bool = False, 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.update_tool_signature "Permanent link")

```
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<br>**TYPE:**`str or dict` |
| `is_remove` | whether removing the tool from llm\_config with name 'tool\_sig'<br>**TYPE:**`bool` |
| `silent_override` | whether to print warnings when overriding functions.<br>**TYPE:**`bool`**DEFAULT:**`False` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<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>3809<br>3810<br>3811<br>3812<br>3813<br>3814<br>3815<br>3816<br>3817<br>``` | ```<br>def update_tool_signature(self, tool_sig: str | dict[str, Any], is_remove: bool, silent_override: bool = False):<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>    self.llm_config = self._update_tool_config(<br>        self.llm_config,<br>        tool_sig=tool_sig,<br>        is_remove=is_remove,<br>        silent_override=silent_override,<br>    )<br>    self.client = OpenAIWrapper(**self.llm_config)<br>``` |

### ``can\_execute\_function [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.can_execute_function "Permanent link")

```
can_execute_function(name)
```

Whether the agent can execute the function.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>3875<br>3876<br>3877<br>3878<br>``` | ```<br>def can_execute_function(self, name: 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_for_llm "Permanent link")

```
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).<br>**TYPE:**`optional(str)`**DEFAULT:**`None` |
| `description` | description of the function (default: None). It is mandatory for the initial decorator, but the following ones can omit it.<br>**TYPE:**`optional(str)`**DEFAULT:**`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](https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/function-calling?tabs=python) for details.<br>**TYPE:**`Literal['function', 'tool']`**DEFAULT:**`'tool'` |
| `silent_override` | whether to suppress any override warning messages.<br>**TYPE:**`bool`**DEFAULT:**`False` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Callable[[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>3940<br>3941<br>3942<br>3943<br>3944<br>3945<br>3946<br>3947<br>3948<br>3949<br>3950<br>3951<br>3952<br>3953<br>3954<br>3955<br>3956<br>3957<br>3958<br>3959<br>3960<br>3961<br>3962<br>3963<br>3964<br>3965<br>3966<br>3967<br>3968<br>3969<br>3970<br>3971<br>3972<br>3973<br>3974<br>3975<br>3976<br>3977<br>3978<br>3979<br>3980<br>3981<br>3982<br>3983<br>3984<br>3985<br>3986<br>3987<br>3988<br>3989<br>3990<br>3991<br>3992<br>3993<br>3994<br>3995<br>3996<br>3997<br>3998<br>3999<br>4000<br>4001<br>4002<br>4003<br>4004<br>4005<br>4006<br>4007<br>4008<br>4009<br>4010<br>4011<br>4012<br>``` | ````<br>def register_for_llm(<br>    self,<br>    *,<br>    name: str | None = None,<br>    description: str | None = None,<br>    api_style: Literal["function", "tool"] = "tool",<br>    silent_override: bool = False,<br>) -> Callable[[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(func_or_tool: F | Tool, name: str | None = name, description: str | None = description) -> 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_for_execution "Permanent link")

```
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).<br>**TYPE:**`str | None`**DEFAULT:**`None` |
| `description` | description of the function (default: None).<br>**TYPE:**`str | None`**DEFAULT:**`None` |
| `serialize` | whether to serialize the return value<br>**TYPE:**`bool`**DEFAULT:**`True` |
| `silent_override` | whether to suppress any override warning messages<br>**TYPE:**`bool`**DEFAULT:**`False` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Callable[[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>4086<br>4087<br>4088<br>4089<br>4090<br>4091<br>4092<br>4093<br>4094<br>4095<br>4096<br>4097<br>4098<br>4099<br>4100<br>4101<br>4102<br>4103<br>4104<br>4105<br>4106<br>4107<br>4108<br>4109<br>4110<br>4111<br>4112<br>4113<br>4114<br>4115<br>4116<br>4117<br>4118<br>4119<br>4120<br>4121<br>4122<br>4123<br>4124<br>4125<br>4126<br>4127<br>4128<br>4129<br>4130<br>4131<br>4132<br>4133<br>4134<br>4135<br>4136<br>4137<br>4138<br>4139<br>4140<br>4141<br>``` | ````<br>def register_for_execution(<br>    self,<br>    name: str | None = None,<br>    description: str | None = None,<br>    *,<br>    serialize: bool = True,<br>    silent_override: bool = False,<br>) -> Callable[[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(func_or_tool: Tool | F, name: str | None = name, description: str | None = description) -> 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 = dict.fromkeys(tool._chat_context_param_names, chat_context)<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_model_client "Permanent link")

```
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<br>**TYPE:**`ModelClient` |
| `**kwargs` | The kwargs for the custom client class to be initialized with<br>**TYPE:**`Any`**DEFAULT:**`{}` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4143<br>4144<br>4145<br>4146<br>4147<br>4148<br>4149<br>4150<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_hook "Permanent link")

```
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.<br>**TYPE:**`str` |
| `hook` | A method implemented by a subclass of AgentCapability.<br>**TYPE:**`Callable` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4152<br>4153<br>4154<br>4155<br>4156<br>4157<br>4158<br>4159<br>4160<br>4161<br>4162<br>4163<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.update_agent_state_before_reply "Permanent link")

```
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>4165<br>4166<br>4167<br>4168<br>4169<br>4170<br>4171<br>4172<br>4173<br>4174<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.process_all_messages_before_reply "Permanent link")

```
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>4176<br>4177<br>4178<br>4179<br>4180<br>4181<br>4182<br>4183<br>4184<br>4185<br>4186<br>4187<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.process_last_received_message "Permanent link")

```
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>4189<br>4190<br>4191<br>4192<br>4193<br>4194<br>4195<br>4196<br>4197<br>4198<br>4199<br>4200<br>4201<br>4202<br>4203<br>4204<br>4205<br>4206<br>4207<br>4208<br>4209<br>4210<br>4211<br>4212<br>4213<br>4214<br>4215<br>4216<br>4217<br>4218<br>4219<br>4220<br>4221<br>4222<br>4223<br>4224<br>4225<br>4226<br>4227<br>4228<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.print_usage_summary "Permanent link")

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

Print the usage summary.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4311<br>4312<br>4313<br>4314<br>4315<br>4316<br>4317<br>4318<br>4319<br>4320<br>``` | ```<br>def print_usage_summary(self, mode: 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.get_actual_usage "Permanent link")

```
get_actual_usage()
```

Get the actual usage summary.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4322<br>4323<br>4324<br>4325<br>4326<br>4327<br>``` | ```<br>def get_actual_usage(self) -> 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.get_total_usage "Permanent link")

```
get_total_usage()
```

Get the total usage summary.

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4329<br>4330<br>4331<br>4332<br>4333<br>4334<br>``` | ```<br>def get_total_usage(self) -> 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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_handoff "Permanent link")

```
register_handoff(condition)
```

Register a single handoff condition (OnContextCondition or OnCondition).

| PARAMETER | DESCRIPTION |
| --- | --- |
| `condition` | The condition to add (OnContextCondition, OnCondition)<br>**TYPE:**`Union[OnContextCondition, OnCondition]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4501<br>4502<br>4503<br>4504<br>4505<br>4506<br>4507<br>``` | ```<br>def register_handoff(self, condition: Union["OnContextCondition", "OnCondition"]) -> None:<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 [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_handoffs "Permanent link")

```
register_handoffs(conditions)
```

Register multiple handoff conditions (OnContextCondition or OnCondition).

| PARAMETER | DESCRIPTION |
| --- | --- |
| `conditions` | List of conditions to add<br>**TYPE:**`list[Union[OnContextCondition, OnCondition]]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4509<br>4510<br>4511<br>4512<br>4513<br>4514<br>4515<br>``` | ```<br>def register_handoffs(self, conditions: list[Union["OnContextCondition", "OnCondition"]]) -> None:<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>``` |

### ``register\_input\_guardrail [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_input_guardrail "Permanent link")

```
register_input_guardrail(guardrail)
```

Register a guardrail to be used for input validation.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `guardrail` | The guardrail to register.<br>**TYPE:**`Guardrail` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4517<br>4518<br>4519<br>4520<br>4521<br>4522<br>4523<br>``` | ```<br>def register_input_guardrail(self, guardrail: "Guardrail") -> None:<br>    """Register a guardrail to be used for input validation.<br>    Args:<br>        guardrail: The guardrail to register.<br>    """<br>    self.input_guardrails.append(guardrail)<br>``` |

### ``register\_input\_guardrails [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_input_guardrails "Permanent link")

```
register_input_guardrails(guardrails)
```

Register multiple guardrails to be used for input validation.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `guardrails` | List of guardrails to register.<br>**TYPE:**`list[Guardrail]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4525<br>4526<br>4527<br>4528<br>4529<br>4530<br>4531<br>``` | ```<br>def register_input_guardrails(self, guardrails: list["Guardrail"]) -> None:<br>    """Register multiple guardrails to be used for input validation.<br>    Args:<br>        guardrails: List of guardrails to register.<br>    """<br>    self.input_guardrails.extend(guardrails)<br>``` |

### ``register\_output\_guardrail [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_output_guardrail "Permanent link")

```
register_output_guardrail(guardrail)
```

Register a guardrail to be used for output validation.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `guardrail` | The guardrail to register.<br>**TYPE:**`Guardrail` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4533<br>4534<br>4535<br>4536<br>4537<br>4538<br>4539<br>``` | ```<br>def register_output_guardrail(self, guardrail: "Guardrail") -> None:<br>    """Register a guardrail to be used for output validation.<br>    Args:<br>        guardrail: The guardrail to register.<br>    """<br>    self.output_guardrails.append(guardrail)<br>``` |

### ``register\_output\_guardrails [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.register_output_guardrails "Permanent link")

```
register_output_guardrails(guardrails)
```

Register multiple guardrails to be used for output validation.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `guardrails` | List of guardrails to register.<br>**TYPE:**`list[Guardrail]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4541<br>4542<br>4543<br>4544<br>4545<br>4546<br>4547<br>``` | ```<br>def register_output_guardrails(self, guardrails: list["Guardrail"]) -> None:<br>    """Register multiple guardrails to be used for output validation.<br>    Args:<br>        guardrails: List of guardrails to register.<br>    """<br>    self.output_guardrails.extend(guardrails)<br>``` |

### ``run\_input\_guardrails [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run_input_guardrails "Permanent link")

```
run_input_guardrails(messages=None)
```

Run input guardrails for an agent before the reply is generated.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `messages` | The messages to check against the guardrails.<br>**TYPE:**`Optional[list[dict[str, Any]]]`**DEFAULT:**`None` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4549<br>4550<br>4551<br>4552<br>4553<br>4554<br>4555<br>4556<br>4557<br>4558<br>4559<br>4560<br>``` | ```<br>def run_input_guardrails(self, messages: list[dict[str, Any]] | None = None) -> GuardrailResult | None:<br>    """Run input guardrails for an agent before the reply is generated.<br>    Args:<br>        messages (Optional[list[dict[str, Any]]]): The messages to check against the guardrails.<br>    """<br>    for guardrail in self.input_guardrails:<br>        guardrail_result = guardrail.check(context=messages)<br>        if guardrail_result.activated:<br>            return guardrail_result<br>    return None<br>``` |

### ``run\_output\_guardrails [\#](https://docs.ag2.ai/0.12.3/docs/api-reference/autogen/UserProxyAgent/\#autogen.UserProxyAgent.run_output_guardrails "Permanent link")

```
run_output_guardrails(reply)
```

Run output guardrails for an agent after the reply is generated.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `reply` | The reply generated by the agent.<br>**TYPE:**`str | dict[str, Any]` |

Source code in `autogen/agentchat/conversable_agent.py`

|     |     |
| --- | --- |
| ```<br>4562<br>4563<br>4564<br>4565<br>4566<br>4567<br>4568<br>4569<br>4570<br>4571<br>4572<br>4573<br>``` | ```<br>def run_output_guardrails(self, reply: str | dict[str, Any]) -> GuardrailResult | None:<br>    """Run output guardrails for an agent after the reply is generated.<br>    Args:<br>        reply (str | dict[str, Any]): The reply generated by the agent.<br>    """<br>    for guardrail in self.output_guardrails:<br>        guardrail_result = guardrail.check(context=reply)<br>        if guardrail_result.activated:<br>            return guardrail_result<br>    return None<br>``` |

Back to top
