GroupChatManager - AG2

GroupChatManager

``autogen.GroupChatManager #

GroupChatManager(groupchat, name='chat_manager', max_consecutive_auto_reply=maxsize, human_input_mode='NEVER', system_message='Group chat manager.', silent=False, **kwargs)

Bases: ConversableAgent

(In preview) A chat manager agent that can manage a group chat of multiple agents.

Source code in autogen/agentchat/groupchat.py

<br>1079<br>1080<br>1081<br>1082<br>1083<br>1084<br>1085<br>1086<br>1087<br>1088<br>1089<br>1090<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> ```
def init(
self,
groupchat: GroupChat,
name: str

``nameproperty#

name

Get the name of the agent.

description`propertywritable`#

description

Get the description of the agent.

``system_messageproperty#

system_message

Return the system message.

DEFAULT\_CONFIG`class-attributeinstance-attribute`#

DEFAULT_CONFIG = False

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

MAX_CONSECUTIVE_AUTO_REPLY = 100

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

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

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

DEFAULT_SUMMARY_METHOD = 'last_msg'

``llm_configinstance-attribute#

llm_config = _validate_llm_config(llm_config)

``handoffsinstance-attribute#

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

``input_guardrailsinstance-attribute#

input_guardrails = []

``output_guardrailsinstance-attribute#

output_guardrails = []

``silentinstance-attribute#

silent = silent

``run_executorinstance-attribute#

run_executor = None

``clientinstance-attribute#

client = _create_client(llm_config)

``client_cacheinstance-attribute#

client_cache = None

``human_input_modeinstance-attribute#

human_input_mode = human_input_mode

``reply_at_receiveinstance-attribute#

reply_at_receive = defaultdict(bool)

``context_variablesinstance-attribute#

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

``hook_listsinstance-attribute#

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

``code_executorproperty#

code_executor

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

``chat_messagesproperty#

chat_messages

A dictionary of conversations from agent to list of messages.

``use_dockerproperty#

use_docker

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

``toolsproperty#

tools

Get the agent's tools (registered for LLM)

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

``function_mapproperty#

function_map

Return the function map.

``groupchatproperty#

groupchat

Returns the group chat managed by the group chat manager.

``last_speakerproperty#

last_speaker

Return the agent who sent the last message to group chat manager.

In a group chat, an agent will always send a message to the group chat manager, and the group chat manager will send the message to all other agents in the group chat. So, when an agent receives a message, it will always be from the group chat manager. With this property, the agent receiving the message can know who actually sent the message.

Example:

from autogen import ConversableAgent
from autogen import GroupChat, GroupChatManager

def print_messages(recipient, messages, sender, config):
    # Print the message immediately
    print(f"Sender: {sender.name} | Recipient: {recipient.name} | Message: {messages[-1].get('content')}")
    print(f"Real Sender: {sender.last_speaker.name}")
    assert sender.last_speaker.name in messages[-1].get("content")
    return False, None  # Required to ensure the agent communication flow continues

agent_a = ConversableAgent("agent A", default_auto_reply="I'm agent A.")
agent_b = ConversableAgent("agent B", default_auto_reply="I'm agent B.")
agent_c = ConversableAgent("agent C", default_auto_reply="I'm agent C.")
for agent in [agent_a, agent_b, agent_c]:
    agent.register_reply([ConversableAgent, None], reply_func=print_messages, config=None)
group_chat = GroupChat(
    [agent_a, agent_b, agent_c],
    messages=[],
    max_round=6,
    speaker_selection_method="random",
    allow_repeat_speaker=True,
)
chat_manager = GroupChatManager(group_chat)
groupchat_result = agent_a.initiate_chat(chat_manager, message="Hi, there, I'm agent A.")

``send #

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

Send a message to another agent.

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

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>1084<br>1085<br>1086<br>1087<br>1088<br>1089<br>1090<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> ````
def send(
self,
message: dict[str, Any]

``a_sendasync#

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

(async) Send a message to another agent.

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

Source code in autogen/agentchat/conversable_agent.py

<br>1132<br>1133<br>1134<br>1135<br>1136<br>1137<br>1138<br>1139<br>1140<br>1141<br>1142<br>1143<br>1144<br>1145<br>1146<br>1147<br>1148<br>1149<br>1150<br>1151<br>1152<br>1153<br>1154<br>1155<br>1156<br>1157<br>1158<br>1159<br>1160<br>1161<br>1162<br>1163<br>1164<br>1165<br>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> ````
async def a_send(
self,
message: dict[str, Any]

``receive #

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

Receive a message from another agent.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>1201<br>1202<br>1203<br>1204<br>1205<br>1206<br>1207<br>1208<br>1209<br>1210<br>1211<br>1212<br>1213<br>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> ```
def receive(
self,
message: dict[str, Any]

``a_receiveasync#

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

(async) Receive a message from another agent.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>1238<br>1239<br>1240<br>1241<br>1242<br>1243<br>1244<br>1245<br>1246<br>1247<br>1248<br>1249<br>1250<br>1251<br>1252<br>1253<br>1254<br>1255<br>1256<br>1257<br>1258<br>1259<br>1260<br>1261<br>1262<br>1263<br>1264<br>1265<br>1266<br>1267<br>1268<br>1269<br>1270<br>1271<br>1272<br>1273<br> ```
async def a_receive(
self,
message: dict[str, Any]

``generate_reply #

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

Source code in autogen/agentchat/conversable_agent.py

<br>2820<br>2821<br>2822<br>2823<br>2824<br>2825<br>2826<br>2827<br>2828<br>2829<br>2830<br>2831<br>2832<br>2833<br>2834<br>2835<br>2836<br>2837<br>2838<br>2839<br>2840<br>2841<br>2842<br>2843<br>2844<br>2845<br>2846<br>2847<br>2848<br>2849<br>2850<br>2851<br>2852<br>2853<br>2854<br>2855<br>2856<br>2857<br>2858<br>2859<br>2860<br>2861<br>2862<br>2863<br>2864<br>2865<br>2866<br>2867<br>2868<br>2869<br>2870<br>2871<br>2872<br>2873<br>2874<br>2875<br>2876<br>2877<br>2878<br>2879<br>2880<br>2881<br>2882<br>2883<br>2884<br>2885<br>2886<br>2887<br>2888<br>2889<br>2890<br>2891<br> ```
def generate_reply(
self,
messages: list[dict[str, Any]]

``a_generate_replyasync#

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]

Source code in autogen/agentchat/conversable_agent.py

<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> ```
async def a_generate_reply(
self,
messages: list[dict[str, Any]]

``set_ui_tools #

set_ui_tools(tools)

Set the UI tools for the agent.

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

Source code in autogen/agentchat/conversable_agent.py

<br>3686<br>3687<br>3688<br>3689<br>3690<br>3691<br>3692<br>3693<br>3694<br>3695<br>3696<br>3697<br>3698<br>3699<br>3700<br>3701<br>3702<br>3703<br>3704<br>3705<br>3706<br> <br>def set_ui_tools(self, tools: list[Tool]) -> None:<br> """Set the UI tools for the agent.<br> Args:<br> tools: a list of tools to be set.<br> """<br> # Unset the previous UI tools<br> self._unset_previous_ui_tools()<br> # Set the new UI tools<br> for tool in tools:<br> # Register the tool for LLM<br> self._register_for_llm(tool, api_style="tool", silent_override=True)<br> if tool not in self._tools:<br> self._tools.append(tool)<br> # Register for execution<br> self.register_for_execution(serialize=False, silent_override=True)(tool)<br> # Set the current UI tools<br> self._ui_tools = tools<br>

``unset_ui_tools #

unset_ui_tools(tools)

Unset the UI tools for the agent.

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

Source code in autogen/agentchat/conversable_agent.py

<br>3708<br>3709<br>3710<br>3711<br>3712<br>3713<br>3714<br>3715<br> <br>def unset_ui_tools(self, tools: list[Tool]) -> None:<br> """Unset the UI tools for the agent.<br> Args:<br> tools: a list of tools to be unset.<br> """<br> for tool in tools:<br> self.remove_tool_for_llm(tool)<br>

``update_system_message #

update_system_message(system_message)

Update the system message.

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

Source code in autogen/agentchat/conversable_agent.py

<br>944<br>945<br>946<br>947<br>948<br>949<br>950<br> <br>def update_system_message(self, system_message: str) -> None:<br> """Update the system message.<br> Args:<br> system_message (str): system message for the ChatCompletion inference.<br> """<br> self._oai_system_message[0]["content"] = system_message<br>

``register_reply #

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

Register a reply function.

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

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>532<br>533<br>534<br>535<br>536<br>537<br>538<br>539<br>540<br>541<br>542<br>543<br>544<br>545<br>546<br>547<br>548<br>549<br>550<br>551<br>552<br>553<br>554<br>555<br>556<br>557<br>558<br>559<br>560<br>561<br>562<br>563<br>564<br>565<br>566<br>567<br>568<br>569<br>570<br>571<br>572<br>573<br>574<br>575<br>576<br>577<br>578<br>579<br>580<br>581<br>582<br>583<br>584<br>585<br>586<br>587<br>588<br>589<br>590<br>591<br>592<br>593<br>594<br>595<br>596<br>597<br>598<br>599<br>600<br>601<br>602<br> ````
def register_reply(
self,
trigger: type[Agent]

``replace_reply_func #

replace_reply_func(old_reply_func, new_reply_func)

Replace a registered reply function with a new one.

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

Source code in autogen/agentchat/conversable_agent.py

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

``register_nested_chats #

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

Register a nested chat reply function.

PARAMETER DESCRIPTION
chat_queue a list of chat objects to be initiated. If use_async is used, then all messages in chat_queue must have a chat-id associated with them.
TYPE:list
trigger refer to register_reply for details.
TYPE:Agent class, str, Agent instance, callable, or list
reply_func_from_nested_chats the reply function for the nested chat. The function takes a chat_queue for nested chat, recipient agent, a list of messages, a sender agent and a config as input and returns a reply message. Default to "summary_from_nested_chats", which corresponds to a built-in reply function that get summary from the nested chat_queue.
<br>def reply_func_from_nested_chats(<br> chat_queue: List[Dict],<br> recipient: ConversableAgent,<br> messages: Optional[List[Dict]] = None,<br> sender: Optional[Agent] = None,<br> config: Optional[Any] = None,<br>) -> Tuple[bool, Union[str, Dict, None]]:<br>
TYPE:(Callable, str)DEFAULT:'summary_from_nested_chats'
position Ref to register_reply for details. Default to 2. It means we first check the termination and human reply, then check the registered nested chat reply.
TYPE:intDEFAULT:2
use_async Uses a_initiate_chats internally to start nested chats. If the original chat is initiated with a_initiate_chats, you may set this to true so nested chats do not run in sync.
TYPE:`bool
kwargs Ref to register_reply for details.
TYPE:AnyDEFAULT:{}

Source code in autogen/agentchat/conversable_agent.py

<br>873<br>874<br>875<br>876<br>877<br>878<br>879<br>880<br>881<br>882<br>883<br>884<br>885<br>886<br>887<br>888<br>889<br>890<br>891<br>892<br>893<br>894<br>895<br>896<br>897<br>898<br>899<br>900<br>901<br>902<br>903<br>904<br>905<br>906<br>907<br>908<br>909<br>910<br>911<br>912<br>913<br>914<br>915<br>916<br>917<br>918<br>919<br>920<br>921<br>922<br>923<br>924<br>925<br>926<br>927<br>928<br>929<br>930<br>931<br>932<br>933<br>934<br>935<br>936<br>937<br> ````
def register_nested_chats(
self,
chat_queue: list[dict[str, Any]],
trigger: type[Agent]

``update_max_consecutive_auto_reply #

update_max_consecutive_auto_reply(value, sender=None)

Update the maximum number of consecutive auto replies.

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

Source code in autogen/agentchat/conversable_agent.py

<br>952<br>953<br>954<br>955<br>956<br>957<br>958<br>959<br>960<br>961<br>962<br>963<br>964<br> ```
def update_max_consecutive_auto_reply(self, value: int, sender: Agent

``max_consecutive_auto_reply #

max_consecutive_auto_reply(sender=None)

The maximum number of consecutive auto replies.

Source code in autogen/agentchat/conversable_agent.py

<br>966<br>967<br>968<br> ```
def max_consecutive_auto_reply(self, sender: Agent

``last_message #

last_message(agent=None)

The last message exchanged with the agent.

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

Source code in autogen/agentchat/conversable_agent.py

<br> 979<br> 980<br> 981<br> 982<br> 983<br> 984<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> ```
def last_message(self, agent: Agent

``initiate_chat #

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

Initiate a chat with the recipient agent.

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

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

Example of a callable message (returning a string):



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



Example of a callable message (returning a dict):



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

TYPE:(str, dict or Callable)DEFAULT:None
**kwargs any additional information. It has the following reserved fields: - "carryover": a string or a list of string to specify the carryover information to be passed to this chat. If provided, we will combine this carryover (by attaching a "context: " string and the carryover content after the message content) with the "message" content when generating the initial chat message in generate_init_message. - "verbose": a boolean to specify whether to print the message and carryover in a chat. Default is False.
TYPE:AnyDEFAULT:{}
RAISES DESCRIPTION
RuntimeError if any async reply functions are registered and not ignored in sync chat.
RETURNS DESCRIPTION
ChatResult an ChatResult object.
TYPE:ChatResult

Source code in autogen/agentchat/conversable_agent.py

<br>1329<br>1330<br>1331<br>1332<br>1333<br>1334<br>1335<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> ````
def initiate_chat(
self,
recipient: "ConversableAgent",
clear_history: bool = True,
silent: bool

``run #

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

Source code in autogen/agentchat/conversable_agent.py

<br>1491<br>1492<br>1493<br>1494<br>1495<br>1496<br>1497<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> ```
def run(
self,
recipient: Optional["ConversableAgent"] = None,
clear_history: bool = True,
silent: bool

``a_initiate_chatasync#

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

(async) Initiate a chat with the recipient agent.

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

Args: Please refer to initiate_chat.

RETURNS DESCRIPTION
ChatResult an ChatResult object.
TYPE:ChatResult

Source code in autogen/agentchat/conversable_agent.py

<br>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>1637<br>1638<br>1639<br>1640<br>1641<br>1642<br>1643<br>1644<br>1645<br>1646<br>1647<br>1648<br>1649<br>1650<br>1651<br>1652<br>1653<br>1654<br>1655<br>1656<br>1657<br>1658<br>1659<br>1660<br>1661<br>1662<br>1663<br>1664<br>1665<br>1666<br>1667<br>1668<br>1669<br>1670<br>1671<br>1672<br>1673<br>1674<br>1675<br>1676<br>1677<br> ```
async def a_initiate_chat(
self,
recipient: "ConversableAgent",
clear_history: bool = True,
silent: bool

``a_runasync#

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

Source code in autogen/agentchat/conversable_agent.py

<br>1679<br>1680<br>1681<br>1682<br>1683<br>1684<br>1685<br>1686<br>1687<br>1688<br>1689<br>1690<br>1691<br>1692<br>1693<br>1694<br>1695<br>1696<br>1697<br>1698<br>1699<br>1700<br>1701<br>1702<br>1703<br>1704<br>1705<br>1706<br>1707<br>1708<br>1709<br>1710<br>1711<br>1712<br>1713<br>1714<br>1715<br>1716<br>1717<br>1718<br>1719<br>1720<br>1721<br>1722<br>1723<br>1724<br>1725<br>1726<br>1727<br>1728<br>1729<br>1730<br>1731<br>1732<br>1733<br>1734<br>1735<br>1736<br>1737<br>1738<br>1739<br>1740<br>1741<br>1742<br>1743<br>1744<br>1745<br>1746<br>1747<br>1748<br>1749<br>1750<br>1751<br>1752<br>1753<br>1754<br>1755<br>1756<br>1757<br>1758<br>1759<br>1760<br>1761<br>1762<br>1763<br>1764<br>1765<br>1766<br>1767<br>1768<br>1769<br>1770<br>1771<br>1772<br>1773<br>1774<br>1775<br>1776<br>1777<br>1778<br>1779<br>1780<br>1781<br>1782<br>1783<br> ```
async def a_run(
self,
recipient: Optional["ConversableAgent"] = None,
clear_history: bool = True,
silent: bool

``initiate_chats #

initiate_chats(chat_queue)

(Experimental) Initiate chats with multiple agents.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>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> <br>def initiate_chats(self, chat_queue: list[dict[str, Any]]) -> list[ChatResult]:<br> """(Experimental) Initiate chats with multiple agents.<br> Args:<br> chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.<br> Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)<br> Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.<br> """<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> self._finished_chats = initiate_chats(_chat_queue)<br> return self._finished_chats<br>

``sequential_run #

sequential_run(chat_queue)

(Experimental) Initiate chats with multiple agents sequentially.

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

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

Source code in autogen/agentchat/conversable_agent.py

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

``a_initiate_chatsasync#

a_initiate_chats(chat_queue)

Source code in autogen/agentchat/conversable_agent.py

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

``a_sequential_runasync#

a_sequential_run(chat_queue)

(Experimental) Initiate chats with multiple agents sequentially.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>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> <br>async def a_sequential_run(<br> self,<br> chat_queue: list[dict[str, Any]],<br>) -> list[AsyncRunResponseProtocol]:<br> """(Experimental) Initiate chats with multiple agents sequentially.<br> Args:<br> chat_queue (List[Dict]): a list of dictionaries containing the information of the chats.<br> Each dictionary should contain the input arguments for [`initiate_chat`](#initiate-chat)<br> Returns: a list of ChatResult objects corresponding to the finished chats in the chat_queue.<br> """<br> iostreams = [AsyncThreadIOStream() for _ in range(len(chat_queue))]<br> # todo: add agents<br> responses = [AsyncRunResponse(iostream, agents=[]) for iostream in iostreams]<br> async def _a_initiate_chats(<br> iostreams: list[AsyncThreadIOStream] = iostreams,<br> responses: list[AsyncRunResponseProtocol] = responses,<br> ) -> None:<br> response = responses[0]<br> try:<br> _chat_queue = self._check_chat_queue_for_sender(chat_queue)<br> consolidate_chat_info(_chat_queue)<br> _validate_recipients(_chat_queue)<br> finished_chats = []<br> for chat_info, response, iostream in zip(_chat_queue, responses, iostreams):<br> with IOStream.set_default(iostream):<br> _chat_carryover = chat_info.get("carryover", [])<br> finished_chat_indexes_to_exclude_from_carryover = chat_info.get(<br> "finished_chat_indexes_to_exclude_from_carryover", []<br> )<br> if isinstance(_chat_carryover, str):<br> _chat_carryover = [_chat_carryover]<br> chat_info["carryover"] = _chat_carryover + [<br> r.summary<br> for i, r in enumerate(finished_chats)<br> if i not in finished_chat_indexes_to_exclude_from_carryover<br> ]<br> if not chat_info.get("silent", False):<br> IOStream.get_default().send(PostCarryoverProcessingEvent(chat_info=chat_info))<br> sender = chat_info["sender"]<br> chat_res = await sender.a_initiate_chat(**chat_info)<br> IOStream.get_default().send(<br> RunCompletionEvent(<br> history=chat_res.chat_history,<br> summary=chat_res.summary,<br> cost=chat_res.cost,<br> last_speaker=(self if chat_res.chat_history[-1]["name"] == self.name else sender).name,<br> )<br> )<br> finished_chats.append(chat_res)<br> except Exception as e:<br> response.iostream.send(ErrorEvent(error=e))<br> asyncio.create_task(_a_initiate_chats())<br> return responses<br>

``get_chat_results #

get_chat_results(chat_index=None)

A summary from the finished chats of particular agents.

Source code in autogen/agentchat/conversable_agent.py

<br>2078<br>2079<br>2080<br>2081<br>2082<br>2083<br> ```
def get_chat_results(self, chat_index: int

``reset #

reset()

Reset the agent.

Source code in autogen/agentchat/conversable_agent.py

<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> <br>def reset(self) -> None:<br> """Reset the agent."""<br> self.clear_history()<br> self.reset_consecutive_auto_reply_counter()<br> self.stop_reply_at_receive()<br> if self.client is not None:<br> self.client.clear_usage_summary()<br> for reply_func_tuple in self._reply_func_list:<br> if reply_func_tuple["reset_config"] is not None:<br> reply_func_tuple["reset_config"](reply_func_tuple["config"])<br> else:<br> reply_func_tuple["config"] = copy.copy(reply_func_tuple["init_config"])<br>

``stop_reply_at_receive #

stop_reply_at_receive(sender=None)

Reset the reply_at_receive of the sender.

Source code in autogen/agentchat/conversable_agent.py

<br>2098<br>2099<br>2100<br>2101<br>2102<br>2103<br> ```
def stop_reply_at_receive(self, sender: Agent

``reset_consecutive_auto_reply_counter #

reset_consecutive_auto_reply_counter(sender=None)

Reset the consecutive_auto_reply_counter of the sender.

Source code in autogen/agentchat/conversable_agent.py

<br>2105<br>2106<br>2107<br>2108<br>2109<br>2110<br> ```
def reset_consecutive_auto_reply_counter(self, sender: Agent

``clear_history #

clear_history(recipient=None, nr_messages_to_preserve=None)

Clear the chat history of the agent.

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

Source code in autogen/agentchat/conversable_agent.py

<br>2112<br>2113<br>2114<br>2115<br>2116<br>2117<br>2118<br>2119<br>2120<br>2121<br>2122<br>2123<br>2124<br>2125<br>2126<br>2127<br>2128<br>2129<br>2130<br>2131<br>2132<br>2133<br>2134<br>2135<br>2136<br>2137<br>2138<br>2139<br>2140<br>2141<br> ```
def clear_history(self, recipient: Agent

``generate_oai_reply #

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>2143<br>2144<br>2145<br>2146<br>2147<br>2148<br>2149<br>2150<br>2151<br>2152<br>2153<br>2154<br>2155<br>2156<br>2157<br>2158<br>2159<br>2160<br>2161<br>2162<br>2163<br>2164<br>2165<br>2166<br>2167<br>2168<br>2169<br>2170<br>2171<br>2172<br>2173<br>2174<br>2175<br> ```
def generate_oai_reply(
self,
messages: list[dict[str, Any]]

``a_generate_oai_replyasync#

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>2227<br>2228<br>2229<br>2230<br>2231<br>2232<br>2233<br>2234<br>2235<br>2236<br>2237<br>2238<br>2239<br>2240<br>2241<br>2242<br>2243<br>2244<br>2245<br>2246<br>2247<br>2248<br>2249<br>2250<br>2251<br>2252<br>2253<br>2254<br> ```
async def a_generate_oai_reply(
self,
messages: list[dict[str, Any]]

``generate_code_execution_reply #

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

Generate a reply using code execution.

Source code in autogen/agentchat/conversable_agent.py

<br>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>2328<br>2329<br>2330<br>2331<br>2332<br>2333<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> ```
def generate_code_execution_reply(
self,
messages: list[dict[str, Any]]

``generate_function_call_reply #

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

Generate a reply using function call.

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

Source code in autogen/agentchat/conversable_agent.py

<br>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> ```
def generate_function_call_reply(
self,
messages: list[dict[str, Any]]

``a_generate_function_call_replyasync#

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

Generate a reply using async function call.

Source code in autogen/agentchat/conversable_agent.py

<br>2400<br>2401<br>2402<br>2403<br>2404<br>2405<br>2406<br>2407<br>2408<br>2409<br>2410<br>2411<br>2412<br>2413<br>2414<br>2415<br>2416<br>2417<br>2418<br>2419<br>2420<br>2421<br>2422<br>2423<br>2424<br>2425<br>2426<br>2427<br> ```
async def a_generate_function_call_reply(
self,
messages: list[dict[str, Any]]

``generate_tool_calls_reply #

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

Generate a reply using tool call.

Source code in autogen/agentchat/conversable_agent.py

<br>2432<br>2433<br>2434<br>2435<br>2436<br>2437<br>2438<br>2439<br>2440<br>2441<br>2442<br>2443<br>2444<br>2445<br>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>2464<br>2465<br>2466<br>2467<br>2468<br>2469<br>2470<br>2471<br>2472<br>2473<br>2474<br>2475<br>2476<br>2477<br>2478<br>2479<br>2480<br>2481<br>2482<br>2483<br>2484<br>2485<br>2486<br>2487<br>2488<br>2489<br>2490<br> ```
def generate_tool_calls_reply(
self,
messages: list[dict[str, Any]]

``a_generate_tool_calls_replyasync#

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

Generate a reply using async function call.

Source code in autogen/agentchat/conversable_agent.py

<br>2502<br>2503<br>2504<br>2505<br>2506<br>2507<br>2508<br>2509<br>2510<br>2511<br>2512<br>2513<br>2514<br>2515<br>2516<br>2517<br>2518<br>2519<br>2520<br>2521<br>2522<br>2523<br>2524<br>2525<br> ```
async def a_generate_tool_calls_reply(
self,
messages: list[dict[str, Any]]

``check_termination_and_human_reply #

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.
TYPE:Optional[List[Dict]]DEFAULT:None
sender The agent object representing the sender of the message.
TYPE:Optional[Agent]DEFAULT:None
config Configuration object, defaults to the current instance if not provided.
TYPE:Optional[Any]DEFAULT:None
iostream The IOStream object to use for sending messages.
TYPE:Optional[IOStreamProtocol]DEFAULT:None
RETURNS DESCRIPTION
bool A tuple containing a boolean indicating if the conversation
`str None`

Source code in autogen/agentchat/conversable_agent.py

<br>2527<br>2528<br>2529<br>2530<br>2531<br>2532<br>2533<br>2534<br>2535<br>2536<br>2537<br>2538<br>2539<br>2540<br>2541<br>2542<br>2543<br>2544<br>2545<br>2546<br>2547<br>2548<br>2549<br>2550<br>2551<br>2552<br>2553<br>2554<br>2555<br>2556<br>2557<br>2558<br>2559<br>2560<br>2561<br>2562<br>2563<br>2564<br>2565<br>2566<br>2567<br>2568<br>2569<br>2570<br>2571<br>2572<br>2573<br>2574<br>2575<br>2576<br>2577<br>2578<br>2579<br>2580<br>2581<br>2582<br>2583<br>2584<br>2585<br>2586<br>2587<br>2588<br>2589<br>2590<br>2591<br>2592<br>2593<br>2594<br>2595<br>2596<br>2597<br>2598<br>2599<br>2600<br>2601<br>2602<br>2603<br>2604<br>2605<br>2606<br>2607<br>2608<br>2609<br>2610<br>2611<br>2612<br>2613<br>2614<br>2615<br>2616<br>2617<br>2618<br>2619<br>2620<br>2621<br>2622<br>2623<br>2624<br>2625<br>2626<br>2627<br>2628<br>2629<br>2630<br>2631<br>2632<br>2633<br>2634<br>2635<br>2636<br>2637<br>2638<br>2639<br>2640<br>2641<br>2642<br>2643<br>2644<br>2645<br>2646<br>2647<br>2648<br>2649<br>2650<br>2651<br>2652<br>2653<br>2654<br>2655<br>2656<br>2657<br>2658<br>2659<br>2660<br>2661<br>2662<br>2663<br>2664<br>2665<br>2666<br>2667<br>2668<br>2669<br>2670<br>2671<br>2672<br>2673<br>2674<br> ```
def check_termination_and_human_reply(
self,
messages: list[dict[str, Any]]

``a_check_termination_and_human_replyasync#

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.
TYPE:Optional[List[Dict]]DEFAULT:None
sender The agent object representing the sender of the message.
TYPE:Optional[Agent]DEFAULT:None
config Configuration object, defaults to the current instance if not provided.
TYPE:Optional[Any]DEFAULT:None
iostream The AsyncIOStreamProtocol object to use for sending messages.
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>2676<br>2677<br>2678<br>2679<br>2680<br>2681<br>2682<br>2683<br>2684<br>2685<br>2686<br>2687<br>2688<br>2689<br>2690<br>2691<br>2692<br>2693<br>2694<br>2695<br>2696<br>2697<br>2698<br>2699<br>2700<br>2701<br>2702<br>2703<br>2704<br>2705<br>2706<br>2707<br>2708<br>2709<br>2710<br>2711<br>2712<br>2713<br>2714<br>2715<br>2716<br>2717<br>2718<br>2719<br>2720<br>2721<br>2722<br>2723<br>2724<br>2725<br>2726<br>2727<br>2728<br>2729<br>2730<br>2731<br>2732<br>2733<br>2734<br>2735<br>2736<br>2737<br>2738<br>2739<br>2740<br>2741<br>2742<br>2743<br>2744<br>2745<br>2746<br>2747<br>2748<br>2749<br>2750<br>2751<br>2752<br>2753<br>2754<br>2755<br>2756<br>2757<br>2758<br>2759<br>2760<br>2761<br>2762<br>2763<br>2764<br>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>2815<br>2816<br>2817<br>2818<br> ```
async def a_check_termination_and_human_reply(
self,
messages: list[dict[str, Any]]

``get_human_input #

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.
TYPE:str
iostream The InputStream object to use for sending messages.
TYPE:Optional[InputStream]DEFAULT:None

Returns: str: human input.

Source code in autogen/agentchat/conversable_agent.py

<br>2998<br>2999<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> ```
def get_human_input(self, prompt: str, *, iostream: InputStream

``a_get_human_inputasync#

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.
TYPE:str
iostream The AsyncInputStream object to use for sending messages.
TYPE:Optional[AsyncInputStream]DEFAULT:None

Returns: str: human input.

Source code in autogen/agentchat/conversable_agent.py

<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> ```
async def a_get_human_input(self, prompt: str, *, iostream: AsyncInputStream

``run_code #

run_code(code, **kwargs)

Run the code and return the result.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>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> ```
def run_code(self, code: str, **kwargs: Any) -> tuple[int, str, str

``execute_code_blocks #

execute_code_blocks(code_blocks)

Execute the code blocks and return the result.

Source code in autogen/agentchat/conversable_agent.py

<br>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> <br>def execute_code_blocks(self, code_blocks):<br> """Execute the code blocks and return the result."""<br> iostream = IOStream.get_default()<br> logs_all = ""<br> for i, code_block in enumerate(code_blocks):<br> lang, code = code_block<br> if not lang:<br> lang = infer_lang(code)<br> iostream.send(ExecuteCodeBlockEvent(code=code, language=lang, code_block_count=i, recipient=self))<br> if lang in ["bash", "shell", "sh"]:<br> exitcode, logs, image = self.run_code(code, lang=lang, **self._code_execution_config)<br> elif lang in PYTHON_VARIANTS:<br> filename = code[11 : code.find("\n")].strip() if code.startswith("# filename: ") else None<br> exitcode, logs, image = self.run_code(<br> code,<br> lang="python",<br> filename=filename,<br> **self._code_execution_config,<br> )<br> else:<br> # In case the language is not supported, we return an error message.<br> exitcode, logs, image = (<br> 1,<br> f"unknown language {lang}",<br> None,<br> )<br> # raise NotImplementedError<br> if image is not None:<br> self._code_execution_config["use_docker"] = image<br> logs_all += "\n" + logs<br> if exitcode != 0:<br> return exitcode, logs_all<br> return exitcode, logs_all<br>

``execute_function #

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

Execute a function call and return the result.

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

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>3127<br>3128<br>3129<br>3130<br>3131<br>3132<br>3133<br>3134<br>3135<br>3136<br>3137<br>3138<br>3139<br>3140<br>3141<br>3142<br>3143<br>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> ```
def execute_function(
self, func_call: dict[str, Any], call_id: str

``a_execute_functionasync#

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

Execute an async function call and return the result.

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>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>3216<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> ```
async def a_execute_function(
self, func_call: dict[str, Any], call_id: str

``generate_init_message #

generate_init_message(message, **kwargs)

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

PARAMETER DESCRIPTION
message the message to be processed.
TYPE:str or None
**kwargs any additional information. It has the following reserved fields: "carryover": a string or a list of string to specify the carryover information to be passed to this chat. It can be a string or a list of string. If provided, we will combine this carryover with the "message" content when generating the initial chat message.
TYPE:AnyDEFAULT:{}
RETURNS DESCRIPTION
`str dict[str, Any]`

Source code in autogen/agentchat/conversable_agent.py

<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> ```
def generate_init_message(self, message: dict[str, Any]

``a_generate_init_messageasync#

a_generate_init_message(message, **kwargs)

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

RETURNS DESCRIPTION
`str dict[str, Any]`

Source code in autogen/agentchat/conversable_agent.py

<br>3338<br>3339<br>3340<br>3341<br>3342<br>3343<br>3344<br>3345<br>3346<br>3347<br>3348<br>3349<br>3350<br>3351<br>3352<br>3353<br>3354<br>3355<br>3356<br>3357<br> ```
async def a_generate_init_message(
self, message: dict[str, Any]

``remove_tool_for_llm #

remove_tool_for_llm(tool)

Remove a tool (register for LLM tool)

Source code in autogen/agentchat/conversable_agent.py

<br>3367<br>3368<br>3369<br>3370<br>3371<br>3372<br>3373<br> <br>def remove_tool_for_llm(self, tool: Tool) -> None:<br> """Remove a tool (register for LLM tool)"""<br> try:<br> self._register_for_llm(tool=tool, api_style="tool", is_remove=True)<br> self._tools.remove(tool)<br> except ValueError:<br> raise ValueError(f"Tool {tool} not found in collection")<br>

``register_function #

register_function(function_map, silent_override=False)

Register functions to the agent.

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

Source code in autogen/agentchat/conversable_agent.py

<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> <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 #

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
TYPE:str or dict
is_remove whether removing the function from llm_config with name 'func_sig'
TYPE:boolDEFAULT:False
silent_override whether to print warnings when overriding functions.
TYPE:boolDEFAULT:False

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

Source code in autogen/agentchat/conversable_agent.py

<br>3391<br>3392<br>3393<br>3394<br>3395<br>3396<br>3397<br>3398<br>3399<br>3400<br>3401<br>3402<br>3403<br>3404<br>3405<br>3406<br>3407<br>3408<br>3409<br>3410<br>3411<br>3412<br>3413<br>3414<br>3415<br>3416<br>3417<br>3418<br>3419<br>3420<br>3421<br>3422<br>3423<br>3424<br>3425<br>3426<br>3427<br>3428<br>3429<br>3430<br>3431<br>3432<br>3433<br>3434<br>3435<br>3436<br>3437<br>3438<br>3439<br>3440<br>3441<br>3442<br> ```
def update_function_signature(
self, func_sig: str

``update_tool_signature #

update_tool_signature(tool_sig, is_remove, silent_override=False)

Update a tool_signature in the LLM configuration for tool_call.

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

Source code in autogen/agentchat/conversable_agent.py

<br>3444<br>3445<br>3446<br>3447<br>3448<br>3449<br>3450<br>3451<br>3452<br>3453<br>3454<br>3455<br>3456<br>3457<br>3458<br>3459<br>3460<br>3461<br>3462<br>3463<br>3464<br> ```
def update_tool_signature(self, tool_sig: str

``can_execute_function #

can_execute_function(name)

Whether the agent can execute the function.

Source code in autogen/agentchat/conversable_agent.py

<br>3522<br>3523<br>3524<br>3525<br> ```
def can_execute_function(self, name: list[str]

``register_for_llm #

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

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

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

PARAMETER DESCRIPTION
name name of the function. If None, the function name will be used (default: None).
TYPE:optional(str)DEFAULT:None
description description of the function (default: None). It is mandatory for the initial decorator, but the following ones can omit it.
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 for details.
TYPE:Literal['function', 'tool']DEFAULT:'tool'
silent_override whether to suppress any override warning messages.
TYPE:boolDEFAULT:False
RETURNS DESCRIPTION
`Callable[[F Tool], Tool]`

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>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>3626<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>3645<br>3646<br>3647<br>3648<br>3649<br>3650<br>3651<br>3652<br>3653<br>3654<br>3655<br>3656<br>3657<br>3658<br>3659<br> ````
def register_for_llm(
self,
*,
name: str

``register_for_execution #

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

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

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

PARAMETER DESCRIPTION
name name of the function. If None, the function name will be used (default: None).
TYPE:`str
description description of the function (default: None).
TYPE:`str
serialize whether to serialize the return value
TYPE:boolDEFAULT:True
silent_override whether to suppress any override warning messages
TYPE:boolDEFAULT:False
RETURNS DESCRIPTION
`Callable[[Tool F], Tool]`

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>3733<br>3734<br>3735<br>3736<br>3737<br>3738<br>3739<br>3740<br>3741<br>3742<br>3743<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> ````
def register_for_execution(
self,
name: str

``register_model_client #

register_model_client(model_client_cls, **kwargs)

Register a model client.

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

Source code in autogen/agentchat/conversable_agent.py

<br>3790<br>3791<br>3792<br>3793<br>3794<br>3795<br>3796<br>3797<br> <br>def register_model_client(self, model_client_cls: ModelClient, **kwargs: Any):<br> """Register a model client.<br> Args:<br> model_client_cls: A custom client class that follows the Client interface<br> **kwargs: The kwargs for the custom client class to be initialized with<br> """<br> self.client.register_model_client(model_client_cls, **kwargs)<br>

``register_hook #

register_hook(hookable_method, hook)

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

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

Source code in autogen/agentchat/conversable_agent.py

<br>3799<br>3800<br>3801<br>3802<br>3803<br>3804<br>3805<br>3806<br>3807<br>3808<br>3809<br>3810<br> <br>def register_hook(self, hookable_method: str, hook: Callable):<br> """Registers a hook to be called by a hookable method, in order to add a capability to the agent.<br> Registered hooks are kept in lists (one per hookable method), and are called in their order of registration.<br> Args:<br> hookable_method: A hookable method name implemented by ConversableAgent.<br> hook: A method implemented by a subclass of AgentCapability.<br> """<br> assert hookable_method in self.hook_lists, f"{hookable_method} is not a hookable method."<br> hook_list = self.hook_lists[hookable_method]<br> assert hook not in hook_list, f"{hook} is already registered as a hook."<br> hook_list.append(hook)<br>

``update_agent_state_before_reply #

update_agent_state_before_reply(messages)

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

Source code in autogen/agentchat/conversable_agent.py

<br>3812<br>3813<br>3814<br>3815<br>3816<br>3817<br>3818<br>3819<br>3820<br>3821<br> <br>def update_agent_state_before_reply(self, messages: list[dict[str, Any]]) -> None:<br> """Calls any registered capability hooks to update the agent's state.<br> Primarily used to update context variables.<br> Will, potentially, modify the messages.<br> """<br> hook_list = self.hook_lists["update_agent_state"]<br> # Call each hook (in order of registration) to process the messages.<br> for hook in hook_list:<br> hook(self, messages)<br>

``process_all_messages_before_reply #

process_all_messages_before_reply(messages)

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

Source code in autogen/agentchat/conversable_agent.py

<br>3823<br>3824<br>3825<br>3826<br>3827<br>3828<br>3829<br>3830<br>3831<br>3832<br>3833<br>3834<br> <br>def process_all_messages_before_reply(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:<br> """Calls any registered capability hooks to process all messages, potentially modifying the messages."""<br> hook_list = self.hook_lists["process_all_messages_before_reply"]<br> # If no hooks are registered, or if there are no messages to process, return the original message list.<br> if len(hook_list) == 0 or messages is None:<br> return messages<br> # Call each hook (in order of registration) to process the messages.<br> processed_messages = messages<br> for hook in hook_list:<br> processed_messages = hook(processed_messages)<br> return processed_messages<br>

``process_last_received_message #

process_last_received_message(messages)

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

Source code in autogen/agentchat/conversable_agent.py

<br>3836<br>3837<br>3838<br>3839<br>3840<br>3841<br>3842<br>3843<br>3844<br>3845<br>3846<br>3847<br>3848<br>3849<br>3850<br>3851<br>3852<br>3853<br>3854<br>3855<br>3856<br>3857<br>3858<br>3859<br>3860<br>3861<br>3862<br>3863<br>3864<br>3865<br>3866<br>3867<br>3868<br>3869<br>3870<br>3871<br>3872<br>3873<br>3874<br>3875<br> <br>def process_last_received_message(self, messages: list[dict[str, Any]]) -> list[dict[str, Any]]:<br> """Calls any registered capability hooks to use and potentially modify the text of the last message,<br> as long as the last message is not a function call or exit command.<br> """<br> # If any required condition is not met, return the original message list.<br> hook_list = self.hook_lists["process_last_received_message"]<br> if len(hook_list) == 0:<br> return messages # No hooks registered.<br> if messages is None:<br> return None # No message to process.<br> if len(messages) == 0:<br> return messages # No message to process.<br> last_message = messages[-1]<br> if "function_call" in last_message:<br> return messages # Last message is a function call.<br> if "context" in last_message:<br> return messages # Last message contains a context key.<br> if "content" not in last_message:<br> return messages # Last message has no content.<br> user_content = last_message["content"]<br> if not isinstance(user_content, str) and not isinstance(user_content, list):<br> # if the user_content is a string, it is for regular LLM<br> # if the user_content is a list, it should follow the multimodal LMM format.<br> return messages<br> if user_content == "exit":<br> return messages # Last message is an exit command.<br> # Call each hook (in order of registration) to process the user's message.<br> processed_user_content = user_content<br> for hook in hook_list:<br> processed_user_content = hook(processed_user_content)<br> if processed_user_content == user_content:<br> return messages # No hooks actually modified the user's message.<br> # Replace the last user message with the expanded one.<br> messages = messages.copy()<br> messages[-1]["content"] = processed_user_content<br> return messages<br>

``print_usage_summary #

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

Print the usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3958<br>3959<br>3960<br>3961<br>3962<br>3963<br>3964<br>3965<br>3966<br>3967<br> ```
def print_usage_summary(self, mode: str

``get_actual_usage #

get_actual_usage()

Get the actual usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3969<br>3970<br>3971<br>3972<br>3973<br>3974<br> ```
def get_actual_usage(self) -> None

``get_total_usage #

get_total_usage()

Get the total usage summary.

Source code in autogen/agentchat/conversable_agent.py

<br>3976<br>3977<br>3978<br>3979<br>3980<br>3981<br> ```
def get_total_usage(self) -> None

``register_handoff #

register_handoff(condition)

Register a single handoff condition (OnContextCondition or OnCondition).

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

Source code in autogen/agentchat/conversable_agent.py

<br>4145<br>4146<br>4147<br>4148<br>4149<br>4150<br>4151<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 #

register_handoffs(conditions)

Register multiple handoff conditions (OnContextCondition or OnCondition).

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

Source code in autogen/agentchat/conversable_agent.py

<br>4153<br>4154<br>4155<br>4156<br>4157<br>4158<br>4159<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 #

register_input_guardrail(guardrail)

Register a guardrail to be used for input validation.

PARAMETER DESCRIPTION
guardrail The guardrail to register.
TYPE:Guardrail

Source code in autogen/agentchat/conversable_agent.py

<br>4161<br>4162<br>4163<br>4164<br>4165<br>4166<br>4167<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 #

register_input_guardrails(guardrails)

Register multiple guardrails to be used for input validation.

PARAMETER DESCRIPTION
guardrails List of guardrails to register.
TYPE:list[Guardrail]

Source code in autogen/agentchat/conversable_agent.py

<br>4169<br>4170<br>4171<br>4172<br>4173<br>4174<br>4175<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 #

register_output_guardrail(guardrail)

Register a guardrail to be used for output validation.

PARAMETER DESCRIPTION
guardrail The guardrail to register.
TYPE:Guardrail

Source code in autogen/agentchat/conversable_agent.py

<br>4177<br>4178<br>4179<br>4180<br>4181<br>4182<br>4183<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 #

register_output_guardrails(guardrails)

Register multiple guardrails to be used for output validation.

PARAMETER DESCRIPTION
guardrails List of guardrails to register.
TYPE:list[Guardrail]

Source code in autogen/agentchat/conversable_agent.py

<br>4185<br>4186<br>4187<br>4188<br>4189<br>4190<br>4191<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 #

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.
TYPE:Optional[list[dict[str, Any]]]DEFAULT:None

Source code in autogen/agentchat/conversable_agent.py

<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> ```
def run_input_guardrails(self, messages: list[dict[str, Any]]

``run_output_guardrails #

run_output_guardrails(reply)

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

PARAMETER DESCRIPTION
reply The reply generated by the agent.
TYPE:`str

Source code in autogen/agentchat/conversable_agent.py

<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> ```
def run_output_guardrails(self, reply: str

``chat_messages_for_summary #

chat_messages_for_summary(agent)

The list of messages in the group chat as a conversation to summarize. The agent is ignored.

Source code in autogen/agentchat/groupchat.py

<br>1131<br>1132<br>1133<br>1134<br>1135<br> <br>def chat_messages_for_summary(self, agent: Agent) -> list[dict[str, Any]]:<br> """The list of messages in the group chat as a conversation to summarize.<br> The agent is ignored.<br> """<br> return self._groupchat.messages<br>

``run_chat #

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

Run a group chat.

Source code in autogen/agentchat/groupchat.py

<br>1194<br>1195<br>1196<br>1197<br>1198<br>1199<br>1200<br>1201<br>1202<br>1203<br>1204<br>1205<br>1206<br>1207<br>1208<br>1209<br>1210<br>1211<br>1212<br>1213<br>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>1244<br>1245<br>1246<br>1247<br>1248<br>1249<br>1250<br>1251<br>1252<br>1253<br>1254<br>1255<br>1256<br>1257<br>1258<br>1259<br>1260<br>1261<br>1262<br>1263<br>1264<br>1265<br>1266<br>1267<br>1268<br>1269<br>1270<br>1271<br>1272<br>1273<br>1274<br>1275<br>1276<br>1277<br>1278<br>1279<br>1280<br>1281<br>1282<br>1283<br>1284<br>1285<br>1286<br>1287<br>1288<br>1289<br>1290<br>1291<br>1292<br>1293<br>1294<br>1295<br>1296<br>1297<br>1298<br>1299<br>1300<br>1301<br>1302<br>1303<br>1304<br>1305<br>1306<br>1307<br>1308<br>1309<br>1310<br>1311<br>1312<br>1313<br>1314<br>1315<br>1316<br>1317<br>1318<br>1319<br>1320<br>1321<br>1322<br>1323<br>1324<br>1325<br> ```
def run_chat(
self,
messages: list[dict[str, Any]]

``a_run_chatasync#

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

Run a group chat asynchronously.

Source code in autogen/agentchat/groupchat.py

<br>1327<br>1328<br>1329<br>1330<br>1331<br>1332<br>1333<br>1334<br>1335<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> ```
async def a_run_chat(
self,
messages: list[dict[str, Any]]

``resume #

resume(messages, remove_termination_string=None, silent=False)

Resumes a group chat using the previous messages as a starting point. Requires the agents, group chat, and group chat manager to be established as per the original group chat.

PARAMETER DESCRIPTION
messages The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
TYPE:`list[dict[str, Any]]
remove_termination_string Remove the termination string from the last message to prevent immediate termination If a string is provided, this string will be removed from last message. If a function is provided, the last message will be passed to this function.
TYPE:`str
silent (Experimental) whether to print the messages for this conversation. Default is False.
TYPE:`bool
RETURNS DESCRIPTION
tuple[ConversableAgent, dict[str, Any]] A tuple containing the last agent who spoke and their message

Source code in autogen/agentchat/groupchat.py

<br>1447<br>1448<br>1449<br>1450<br>1451<br>1452<br>1453<br>1454<br>1455<br>1456<br>1457<br>1458<br>1459<br>1460<br>1461<br>1462<br>1463<br>1464<br>1465<br>1466<br>1467<br>1468<br>1469<br>1470<br>1471<br>1472<br>1473<br>1474<br>1475<br>1476<br>1477<br>1478<br>1479<br>1480<br>1481<br>1482<br>1483<br>1484<br>1485<br>1486<br>1487<br>1488<br>1489<br>1490<br>1491<br>1492<br>1493<br>1494<br>1495<br>1496<br>1497<br>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> ```
def resume(
self,
messages: list[dict[str, Any]]

``a_resumeasync#

a_resume(messages, remove_termination_string=None, silent=False)

Resumes a group chat using the previous messages as a starting point, asynchronously. Requires the agents, group chat, and group chat manager to be established as per the original group chat.

PARAMETER DESCRIPTION
messages The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
TYPE:`list[dict[str, Any]]
remove_termination_string Remove the termination string from the last message to prevent immediate termination If a string is provided, this string will be removed from last message. If a function is provided, the last message will be passed to this function, and the function returns the string after processing.
TYPE:`str
silent (Experimental) whether to print the messages for this conversation. Default is False.
TYPE:`bool
RETURNS DESCRIPTION
tuple[ConversableAgent, dict[str, Any]] A tuple containing the last agent who spoke and their message

Source code in autogen/agentchat/groupchat.py

<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>1637<br>1638<br>1639<br>1640<br>1641<br>1642<br>1643<br>1644<br>1645<br>1646<br>1647<br>1648<br>1649<br>1650<br>1651<br> ```
async def a_resume(
self,
messages: list[dict[str, Any]]

``messages_from_string #

messages_from_string(message_string)

Reads the saved state of messages in Json format for resume and returns as a messages list

PARAMETER DESCRIPTION
message_string Json string, the saved state
TYPE:str
RETURNS DESCRIPTION
list[dict[str, Any]] A list of messages

Source code in autogen/agentchat/groupchat.py

<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> <br>def messages_from_string(self, message_string: str) -> list[dict[str, Any]]:<br> """Reads the saved state of messages in Json format for resume and returns as a messages list<br> Args:<br> message_string: Json string, the saved state<br> Returns:<br> A list of messages<br> """<br> try:<br> state = json.loads(message_string)<br> except json.JSONDecodeError:<br> raise Exception("Messages string is not a valid JSON string")<br> return state<br>

``messages_to_string #

messages_to_string(messages)

Converts the provided messages into a Json string that can be used for resuming the chat. The state is made up of a list of messages

PARAMETER DESCRIPTION
messages set of messages to convert to a string
TYPE:list[dict[str, Any]]
RETURNS DESCRIPTION
str A JSON representation of the messages which can be persisted for resuming later

Source code in autogen/agentchat/groupchat.py

<br>1731<br>1732<br>1733<br>1734<br>1735<br>1736<br>1737<br>1738<br>1739<br>1740<br>1741<br> <br>def messages_to_string(self, messages: list[dict[str, Any]]) -> str:<br> """Converts the provided messages into a Json string that can be used for resuming the chat.<br> The state is made up of a list of messages<br> Args:<br> messages: set of messages to convert to a string<br> Returns:<br> A JSON representation of the messages which can be persisted for resuming later<br> """<br> return json.dumps(messages)<br>

``clear_agents_history #

clear_agents_history(reply, groupchat)

Clears history of messages for all agents or a selected one. Can preserve a selected number of last messages.

This function is called when the user manually provides the "clear history" phrase in their reply.

When "clear history" is provided, the history of messages for all agents is cleared.

When "clear history <agent_name>" is provided, the history of messages for the selected agent is cleared.

When "clear history <nr_of_messages_to_preserve>" is provided, the history of messages for all agents is cleared

except for the last <nr_of_messages_to_preserve> messages.

When "clear history <agent_name>``<nr_of_messages_to_preserve>" is provided, the history of messages for the selected

agent is cleared except for the last <nr_of_messages_to_preserve> messages.

The phrase "clear history" and optional arguments are cut out from the reply before it is passed to the chat.

Args:

reply (dict): reply message dict to analyze.

groupchat (GroupChat): GroupChat object.

Source code in autogen/agentchat/groupchat.py

<br>1754<br>1755<br>1756<br>1757<br>1758<br>1759<br>1760<br>1761<br>1762<br>1763<br>1764<br>1765<br>1766<br>1767<br>1768<br>1769<br>1770<br>1771<br>1772<br>1773<br>1774<br>1775<br>1776<br>1777<br>1778<br>1779<br>1780<br>1781<br>1782<br>1783<br>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> <br>def clear_agents_history(self, reply: dict[str, Any], groupchat: GroupChat) -> str:<br> """Clears history of messages for all agents or a selected one. Can preserve a selected number of last messages.\n<br> \n<br> This function is called when the user manually provides the "clear history" phrase in their reply.\n<br> When "clear history" is provided, the history of messages for all agents is cleared.\n<br> When "clear history `<agent_name>`" is provided, the history of messages for the selected agent is cleared.\n<br> When "clear history `<nr_of_messages_to_preserve>`" is provided, the history of messages for all agents is cleared\n<br> except for the last `<nr_of_messages_to_preserve>` messages.\n<br> When "clear history `<agent_name>` `<nr_of_messages_to_preserve>`" is provided, the history of messages for the selected\n<br> agent is cleared except for the last `<nr_of_messages_to_preserve>` messages.\n<br> The phrase "clear history" and optional arguments are cut out from the reply before it is passed to the chat.\n<br> \n<br> Args:\n<br> reply (dict): reply message dict to analyze.\n<br> groupchat (GroupChat): GroupChat object.\n<br> """<br> iostream = IOStream.get_default()<br> raw_reply_content = reply.get("content")<br> if isinstance(raw_reply_content, str):<br> reply_content = raw_reply_content<br> elif isinstance(raw_reply_content, (list, type(None))):<br> reply_content = content_str(raw_reply_content)<br> reply["content"] = reply_content<br> else:<br> reply_content = str(raw_reply_content)<br> reply["content"] = reply_content<br> # Split the reply into words<br> words = reply_content.split()<br> # Find the position of "clear" to determine where to start processing<br> clear_word_index = next(i for i in reversed(range(len(words))) if words[i].upper() == "CLEAR")<br> # Extract potential agent name and steps<br> words_to_check = words[clear_word_index + 2 : clear_word_index + 4]<br> nr_messages_to_preserve = None<br> nr_messages_to_preserve_provided = False<br> agent_to_memory_clear = None<br> for word in words_to_check:<br> if word.isdigit():<br> nr_messages_to_preserve = int(word)<br> nr_messages_to_preserve_provided = True<br> elif word[:-1].isdigit(): # for the case when number of messages is followed by dot or other sign<br> nr_messages_to_preserve = int(word[:-1])<br> nr_messages_to_preserve_provided = True<br> else:<br> for agent in groupchat.agents:<br> if agent.name == word or agent.name == word[:-1]:<br> agent_to_memory_clear = agent<br> break<br> # preserve last tool call message if clear history called inside of tool response<br> if "tool_responses" in reply and not nr_messages_to_preserve:<br> nr_messages_to_preserve = 1<br> logger.warning(<br> "The last tool call message will be saved to prevent errors caused by tool response without tool call."<br> )<br> # clear history<br> iostream.send(<br> ClearAgentsHistoryEvent(agent=agent_to_memory_clear, nr_events_to_preserve=nr_messages_to_preserve)<br> )<br> if agent_to_memory_clear:<br> agent_to_memory_clear.clear_history(nr_messages_to_preserve=nr_messages_to_preserve)<br> else:<br> if nr_messages_to_preserve:<br> # clearing history for groupchat here<br> temp = groupchat.messages[-nr_messages_to_preserve:]<br> groupchat.messages.clear()<br> groupchat.messages.extend(temp)<br> else:<br> # clearing history for groupchat here<br> groupchat.messages.clear()<br> # clearing history for agents<br> for agent in groupchat.agents:<br> agent.clear_history(nr_messages_to_preserve=nr_messages_to_preserve)<br> # Reconstruct the reply without the "clear history" command and parameters<br> skip_words_number = 2 + int(bool(agent_to_memory_clear)) + int(nr_messages_to_preserve_provided)<br> reply_content = " ".join(words[:clear_word_index] + words[clear_word_index + skip_words_number :])<br> return reply_content<br>

Back to top