ConversableAgent

ConversableAgent(
    name: str,
    system_message: str | list | None = 'You are a helpful AI Assistant.',
    is_termination_msg: Callable[[dict], bool] | None = None,
    max_consecutive_auto_reply: int | None = None,
    human_input_mode: Literal['ALWAYS', 'NEVER', 'TERMINATE'] = 'TERMINATE',
    function_map: dict[str, typing.Callable] | None = None,
    code_execution_config: dict | Literal[False] = False,
    llm_config: dict | Literal[False] | None = None,
    default_auto_reply: str | dict = '',
    description: str | None = None,
    chat_messages: dict[autogen.Agent, list[dict]] | None = None,
    silent: bool | None = None,
    context_variables: dict[str, typing.Any] | None = None
)

(In preview) A class for generic conversable agents which can be configured as assistant or user proxy.

After receiving each message, the agent will send a reply to the sender unless the msg is a termination msg. For example, AssistantAgent and UserProxyAgent are subclasses of this class, configured with different default settings.

To modify auto reply, override generate_reply method. To disable/enable human response in every turn, set human_input_mode to “NEVER” or “ALWAYS”. To modify the way to get human input, override get_human_input method. To modify the way to execute code blocks, single code block, or function call, override execute_code_blocks, run_code, and execute_function methods respectively.

Parameters:
NameDescription
namename of the agent.

Type: str
system_messagesystem message for the ChatCompletion inference.

Type: str | list | None

Default: ‘You are a helpful AI Assistant.‘
is_termination_msga function that takes a message in the form of a dictionary and returns a boolean value indicating if this received message is a termination message.

The dict can contain the following keys: “content”, “role”, “name”, “function_call”.

Type: Callable[[dict], bool] | None

Default: None
max_consecutive_auto_replythe maximum number of consecutive auto replies.

default to None (no limit provided, class attribute MAX_CONSECUTIVE_AUTO_REPLY will be used as the limit in this case).

When set to 0, no auto reply will be generated.

Type: int | None

Default: None
human_input_modewhether to ask for human inputs every time a message is received.

Possible values are “ALWAYS”, “TERMINATE”, “NEVER”.

(1) When “ALWAYS”, the agent prompts for human input every time a message is received.

Under this mode, the conversation stops when the human input is “exit”, or when is_termination_msg is True and there is no human input.

(2) When “TERMINATE”, the agent only prompts for human input only when a termination message is received or the number of auto reply reaches the max_consecutive_auto_reply.

(3) When “NEVER”, the agent will never prompt for human input.

Under this mode, the conversation stops when the number of auto reply reaches the max_consecutive_auto_reply or when is_termination_msg is True.

Type: Literal['ALWAYS', 'NEVER', 'TERMINATE']

Default: ‘TERMINATE’
function_mapMapping function names (passed to openai) to callable functions, also used for tool calls.

Type: dict[str, typing.Callable] | None

Default: None
code_execution_configconfig for the code execution.

To disable code execution, set to False.

Otherwise, set to a dictionary with the following keys: - work_dir (Optional, str): The working directory for the code execution.

If None, a default working directory will be used.

The default working directory is the “extensions” directory under “path_to_autogen”.

- use_docker (Optional, list, str or bool): The docker image to use for code execution.

Default is True, which means the code will be executed in a docker container.

A default list of images will be used.

If a list or a str of image name(s) is provided, the code will be executed in a docker container with the first image successfully pulled.

If False, the code will be executed in the current environment.

We strongly recommend using docker for code execution.

- timeout (Optional, int): The maximum execution time in seconds.

- last_n_messages (Experimental, int or str): The number of messages to look back for code execution.

If set to ‘auto’, it will scan backwards through all messages arriving since the agent last spoke, which is typically the last time execution was attempted.

(Default: auto)

Type: dict | Literal[False]

Default: False
llm_configllm inference configuration.

Please refer to OpenAIWrapper.create for available options.

When using OpenAI or Azure OpenAI endpoints, please specify a non-empty ‘model’ either in llm_config or in each config of ‘config_list’ in llm_config.

To disable llm-based auto reply, set to False.

When set to None, will use self.DEFAULT_CONFIG, which defaults to False.

Type: dict | Literal[False] | None

Default: None
default_auto_replydefault auto reply when no code execution or llm-based reply is generated.

Type: str | dict

Default:
descriptiona short description of the agent.

This description is used by other agents (e.g.

the GroupChatManager) to decide when to call upon this agent.

(Default: system_message)

Type: str | None

Default: None
chat_messagesthe previous chat messages that this agent had in the past with other agents.

Can be used to give the agent a memory by providing the chat history.

This will allow the agent to resume previous had conversations.

Defaults to an empty chat history.

Type: dict[autogen.Agent, list[dict]] | None

Default: None
silent(Experimental) whether to print the message sent.

If None, will use the value of silent in each function.

Type: bool | None

Default: None
context_variablesContext variables that provide a persistent context for the agent.

Note: Will maintain a reference to the passed in context variables (enabling a shared context) Only used in Swarms at this stage: https://docs.ag2.ai/docs/reference/agentchat/contrib/swarm_agent

Type: dict[str, typing.Any] | None

Default: None

Class Attributes

DEFAULT_CONFIG



DEFAULT_SUMMARY_METHOD



DEFAULT_SUMMARY_PROMPT



MAX_CONSECUTIVE_AUTO_REPLY



llm_config



Instance Attributes

chat_messages


A dictionary of conversations from agent to list of messages.

code_executor


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

description


Get the description of the agent.

function_map


Return the function map.

name


Get the name of the agent.

system_message


Return the system message.

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.

Instance Methods

a_check_termination_and_human_reply

a_check_termination_and_human_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, str | None]

(async) 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.

Parameters:
NameDescription
messagesA list of message dictionaries, representing the conversation history.

Type: list[dict] | None

Default: None
senderThe agent object representing the sender of the message.

Type: autogen.Agent | None

Default: None
configConfiguration object, defaults to the current instance if not provided.

Type: Any | None

Default: None
Returns:
TypeDescription
tuple[bool, str | None]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.

a_execute_function

a_execute_function(
    self,
    func_call,
    call_id: str | None = None,
    verbose: bool = False
) -> tuple[bool, dict[str, typing.Any]]

Execute an async function call and return the result.

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

Parameters:
NameDescription
func_calla dictionary extracted from openai message at key “function_call” or “tool_calls” with keys “name” and “arguments”.

call_ida string to identify the tool call.

Type: str | None

Default: None
verboseType: bool

Default: False
Returns:
TypeDescription
tuple[bool, dict[str, typing.Any]]A tuple of (is_exec_success, result_dict). is_exec_success (boolean): whether the execution is successful. result_dict: a dictionary with keys “name”, “role”, and “content”. Value of “role” is “function”. “function_call” deprecated as of OpenAI API v1.1.0 See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call

a_generate_function_call_reply

a_generate_function_call_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, dict | None]

Generate a reply using async 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

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None

a_generate_init_message

a_generate_init_message(
    self,
    message: dict | str | None,
    **kwargs
) -> str | dict

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

Parameters:
NameDescription
messageType: dict | str | None
**kwargs
Returns:
TypeDescription
str | dictstr or dict: the processed message.

a_generate_oai_reply

a_generate_oai_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, str | dict | None]

Generate a reply using autogen.oai asynchronously.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None

a_generate_reply

a_generate_reply(
    self,
    messages: list[dict[str, typing.Any]] | None = None,
    sender: ForwardRef('Agent') | None = None,
    **kwargs: Any
) -> str | dict[str, typing.Any] | None

(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.
Parameters:
NameDescription
messagesa list of messages in the conversation history.

Type: list[dict[str, typing.Any]] | None

Default: None
sendersender of an Agent instance.

Type: ForwardRef('Agent') | None

Default: None
**kwargsType: Any
Returns:
TypeDescription
str | dict[str, typing.Any] | Nonestr or dict or None: reply. None if no reply is generated.

a_generate_tool_calls_reply

a_generate_tool_calls_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, dict | None]

Generate a reply using async function call.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None

a_get_human_input

a_get_human_input(self, prompt: str) -> str

(Async) Get human input.

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

Parameters:
NameDescription
promptprompt for the human input.

Type: str
Returns:
TypeDescription
strstr: human input.

a_initiate_chat

a_initiate_chat(
    self,
    recipient: ConversableAgent,
    clear_history: bool = True,
    silent: bool | None = False,
    cache: autogen.cache.AbstractCache | None = None,
    max_turns: int | None = None,
    summary_method: str | Callable | None = 'last_msg',
    summary_args: dict | None = \{},
    message: str | Callable | None = None,
    **kwargs
) -> autogen.ChatResult

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

Parameters:
NameDescription
recipientType: ConversableAgent
clear_historyType: bool

Default: True
silentType: bool | None

Default: False
cacheType: autogen.cache.AbstractCache | None

Default: None
max_turnsType: int | None

Default: None
summary_methodType: str | Callable | None

Default: ‘last_msg’
summary_argsType: dict | None

Default: {}
messageType: str | Callable | None

Default: None
**kwargs
Returns:
TypeDescription
autogen.ChatResultChatResult: an ChatResult object.

a_initiate_chats

a_initiate_chats(self, chat_queue: list[dict[str, typing.Any]]) -> dict[int, autogen.ChatResult]
Parameters:
NameDescription
chat_queueType: list[dict[str, typing.Any]]

a_receive

a_receive(
    self,
    message: str | dict,
    sender: autogen.Agent,
    request_reply: bool | None = None,
    silent: bool | None = 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.

Parameters:
NameDescription
messagemessage 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”.

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: str | dict
sendersender of an Agent instance.

Type: autogen.Agent
request_replywhether a reply is requested from the sender.

If None, the value is determined by self.reply_at_receive[sender].

Type: bool | None

Default: None
silent(Experimental) whether to print the message received.

Type: bool | None

Default: False

a_run

a_run(
    self,
    message: str,
    *,
    tools: autogen.tools.Tool | Iterable[autogen.tools.Tool] | None = None,
    executor_kwargs: dict[str, typing.Any] | None = None,
    max_turns: int | None = None,
    msg_to: Literal['agent', 'user'] = 'agent',
    clear_history: bool = False,
    user_input: bool = True
) -> autogen.ChatResult

Run a chat asynchronously with the agent using the given message.

A second agent will be created to represent the user, this agent will by known by the name ‘user’.

The user can terminate the conversation when prompted or, if agent’s reply contains ‘TERMINATE’, it will terminate.

Parameters:
NameDescription
messagethe message to be processed.

Type: str
toolsthe tools to be used by the agent.

Type: autogen.tools.Tool | Iterable[autogen.tools.Tool] | None

Default: None
executor_kwargsthe keyword arguments for the executor.

Type: dict[str, typing.Any] | None

Default: None
max_turnsmaximum number of turns (a turn is equivalent to both agents having replied), defaults no None which means unlimited.

The original message is included.

Type: int | None

Default: None
msg_towhich agent is receiving the message and will be the first to reply, defaults to the agent.

Type: Literal['agent', 'user']

Default: ‘agent’
clear_historywhether to clear the chat history.

Type: bool

Default: False
user_inputthe user will be asked for input at their turn.

Type: bool

Default: True

a_send

a_send(
    self,
    message: str | dict,
    recipient: autogen.Agent,
    request_reply: bool | None = None,
    silent: bool | None = False
) -> 

(async) Send a message to another agent.

Parameters:
NameDescription
messagemessage 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: str | dict
recipientthe recipient of the message.

Type: autogen.Agent
request_replywhether to request a reply from the recipient.

Type: bool | None

Default: None
silent(Experimental) whether to print the message sent.

Type: bool | None

Default: False

can_execute_function

can_execute_function(self, name: list[str] | str) -> bool

Whether the agent can execute the function.

Parameters:
NameDescription
nameType: list[str] | str

chat_messages_for_summary

chat_messages_for_summary(self, agent: autogen.Agent) -> list[dict]

A list of messages as a conversation to summarize.

Parameters:
NameDescription
agentType: autogen.Agent

check_termination_and_human_reply

check_termination_and_human_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, str | 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.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None
Returns:
TypeDescription
tuple[bool, str | None]- 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.

clear_history

clear_history(
    self,
    recipient: autogen.Agent | None = None,
    nr_messages_to_preserve: int | None = None
) -> 

Clear the chat history of the agent.

Parameters:
NameDescription
recipientthe agent with whom the chat history to clear.

If None, clear the chat history with all agents.

Type: autogen.Agent | None

Default: None
nr_messages_to_preservethe number of newest messages to preserve in the chat history.

Type: int | None

Default: None

execute_code_blocks

execute_code_blocks(self, code_blocks) -> 

Execute the code blocks and return the result.

Parameters:
NameDescription
code_blocks

execute_function

execute_function(
    self,
    func_call,
    call_id: str | None = None,
    verbose: bool = False
) -> tuple[bool, dict[str, typing.Any]]

Execute a function call and return the result.

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

Parameters:
NameDescription
func_calla dictionary extracted from openai message at “function_call” or “tool_calls” with keys “name” and “arguments”.

call_ida string to identify the tool call.

Type: str | None

Default: None
verboseType: bool

Default: False
Returns:
TypeDescription
tuple[bool, dict[str, typing.Any]]A tuple of (is_exec_success, result_dict). is_exec_success (boolean): whether the execution is successful. result_dict: a dictionary with keys “name”, “role”, and “content”. Value of “role” is “function”. “function_call” deprecated as of OpenAI API v1.1.0 See https://platform.openai.com/docs/api-reference/chat/create#chat-create-function_call

generate_code_execution_reply

generate_code_execution_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: dict | Literal[False] | None = None
) -> 

Generate a reply using code execution.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: dict | Literal[False] | None

Default: None

generate_function_call_reply

generate_function_call_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, dict | 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

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None

generate_init_message

generate_init_message(
    self,
    message: dict | str | None,
    **kwargs
) -> str | dict

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

Parameters:
NameDescription
messagethe message to be processed.

Type: dict | str | None
**kwargsany 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.

Returns:
TypeDescription
str | dictstr or dict: the processed message.

generate_oai_reply

generate_oai_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: autogen.OpenAIWrapper | None = None
) -> tuple[bool, str | dict | None]

Generate a reply using autogen.oai.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: autogen.OpenAIWrapper | None

Default: None

generate_reply

generate_reply(
    self,
    messages: list[dict[str, typing.Any]] | None = None,
    sender: ForwardRef('Agent') | None = None,
    **kwargs: Any
) -> dict | str | None

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.
Parameters:
NameDescription
messagesa list of messages in the conversation history.

Type: list[dict[str, typing.Any]] | None

Default: None
sendersender of an Agent instance.

Type: ForwardRef('Agent') | None

Default: None
**kwargsType: Any
Returns:
TypeDescription
dict | str | Nonestr or dict or None: reply. None if no reply is generated.

generate_tool_calls_reply

generate_tool_calls_reply(
    self,
    messages: list[dict] | None = None,
    sender: autogen.Agent | None = None,
    config: Any | None = None
) -> tuple[bool, dict | None]

Generate a reply using tool call.

Parameters:
NameDescription
messagesType: list[dict] | None

Default: None
senderType: autogen.Agent | None

Default: None
configType: Any | None

Default: None

get_actual_usage

get_actual_usage(self) -> dict[str, int] | None

Get the actual usage summary.


get_chat_results

get_chat_results(self, chat_index: int | None = None) -> list[autogen.ChatResult] | autogen.ChatResult

A summary from the finished chats of particular agents.

Parameters:
NameDescription
chat_indexType: int | None

Default: None

get_context

get_context(
    self,
    key: str,
    default: Any = None
) -> Any

Get a context variable by key.

Parameters:
NameDescription
keyThe key to look up

Type: str
defaultValue to return if key doesn’t exist

Type: Any

Default: None
Returns:
TypeDescription
AnyThe value associated with the key, or default if not found

get_human_input

get_human_input(self, prompt: str) -> str

Get human input.

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

Parameters:
NameDescription
promptprompt for the human input.

Type: str
Returns:
TypeDescription
strstr: human input.

get_total_usage

get_total_usage(self) -> dict[str, int] | None

Get the total usage summary.


initiate_chat

initiate_chat(
    self,
    recipient: ConversableAgent,
    clear_history: bool = True,
    silent: bool | None = False,
    cache: autogen.cache.AbstractCache | None = None,
    max_turns: int | None = None,
    summary_method: str | Callable | None = 'last_msg',
    summary_args: dict | None = \{},
    message: dict | str | Callable | None = None,
    **kwargs
) -> autogen.ChatResult

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.

Parameters:
NameDescription
recipientthe recipient agent.

Type: ConversableAgent
clear_historywhether to clear the chat history with the agent.

Default is True.

Type: bool

Default: True
silent(Experimental) whether to print the messages for this conversation.

Default is False.

Type: bool | None

Default: False
cachethe cache client to be used for this conversation.

Default is None.

Type: autogen.cache.AbstractCache | None

Default: None
max_turnsthe 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 | None

Default: None
summary_methoda method to get a summary from the chat.

Default is DEFAULT_SUMMARY_METHOD, i.e., “last_msg”.

Type: str | Callable | None

Default: ‘last_msg’
summary_argsa 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: dict | None

Default: {}
messagethe 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).

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

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.

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

Type: dict | str | Callable | None

Default: None
**kwargsany 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.

Returns:
TypeDescription
autogen.ChatResultChatResult: an ChatResult object.

initiate_chats

initiate_chats(self, chat_queue: list[dict[str, typing.Any]]) -> list[autogen.ChatResult]

(Experimental) Initiate chats with multiple agents.

Parameters:
NameDescription
chat_queuea list of dictionaries containing the information of the chats.

Each dictionary should contain the input arguments for initiate_chat

Type: list[dict[str, typing.Any]]
Returns:
TypeDescription
list[autogen.ChatResult]a list of ChatResult objects corresponding to the finished chats in the chat_queue.

last_message

last_message(self, agent: autogen.Agent | None = None) -> dict | None

The last message exchanged with the agent.

Parameters:
NameDescription
agentThe 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: autogen.Agent | None

Default: None
Returns:
TypeDescription
dict | NoneThe last message exchanged with the agent.

max_consecutive_auto_reply

max_consecutive_auto_reply(self, sender: autogen.Agent | None = None) -> int

The maximum number of consecutive auto replies.

Parameters:
NameDescription
senderType: autogen.Agent | None

Default: None

pop_context

pop_context(
    self,
    key: str,
    default: Any = None
) -> Any

Remove and return a context variable.

Parameters:
NameDescription
keyThe key to remove

Type: str
defaultValue to return if key doesn’t exist

Type: Any

Default: None
Returns:
TypeDescription
AnyThe value that was removed, or default if key not found

print_usage_summary(self, mode: list[str] | str = ['actual', 'total']) -> None

Print the usage summary.

Parameters:
NameDescription
modeType: list[str] | str

Default: [‘actual’, ‘total’]

process_all_messages_before_reply

process_all_messages_before_reply(self, messages: list[dict]) -> list[dict]

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

Parameters:
NameDescription
messagesType: list[dict]

process_last_received_message

process_last_received_message(self, messages: list[dict]) -> list[dict]

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.

Parameters:
NameDescription
messagesType: list[dict]

receive

receive(
    self,
    message: str | dict,
    sender: autogen.Agent,
    request_reply: bool | None = None,
    silent: bool | None = 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.

Parameters:
NameDescription
messagemessage 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: str | dict
sendersender of an Agent instance.

Type: autogen.Agent
request_replywhether a reply is requested from the sender.

If None, the value is determined by self.reply_at_receive[sender].

Type: bool | None

Default: None
silent(Experimental) whether to print the message received.

Type: bool | None

Default: False

register_for_execution

register_for_execution(self, name: str | None = None) -> Callable[[~| autogen.tools.Tool], autogen.tools.Tool]

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.

Parameters:
NameDescription
namename of the function.

If None, the function name will be used (default: None).

Type: str | None

Default: None
Returns:
TypeDescription
Callable[[~F | autogen.tools.Tool], autogen.tools.Tool]The decorator for registering a function to be used by an agent.

register_for_llm

register_for_llm(
    self,
    *,
    name: str | None = None,
    description: str | None = None,
    api_style: Literal['function', 'tool'] = 'tool'
) -> Callable[[~| autogen.tools.Tool], autogen.tools.Tool]

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.

Parameters:
NameDescription
namename of the function.

If None, the function name will be used (default: None).

Type: str | None

Default: None
descriptiondescription of the function (default: None).

It is mandatory for the initial decorator, but the following ones can omit it.

Type: str | None

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’
Returns:
TypeDescription
Callable[[~F | autogen.tools.Tool], autogen.tools.Tool]The decorator for registering a function to be used by an agent.

register_function

register_function(self, function_map: dict[str, Callable | None]) -> 

Register functions to the agent.

Parameters:
NameDescription
function_mapa 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 | None]

register_hook

register_hook(
    self,
    hookable_method: str,
    hook: Callable
) -> 

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.

Parameters:
NameDescription
hookable_methodA hookable method name implemented by ConversableAgent.

Type: str
hookA method implemented by a subclass of AgentCapability.

Type: Callable

register_model_client

register_model_client(
    self,
    model_client_cls: autogen.ModelClient,
    **kwargs
) -> 

Register a model client.

Parameters:
NameDescription
model_client_clsA custom client class that follows the Client interface

Type: autogen.ModelClient
**kwargsThe kwargs for the custom client class to be initialized with


register_nested_chats

register_nested_chats(
    self,
    chat_queue: list[dict[str, typing.Any]],
    trigger: type[autogen.Agent] | str | autogen.Agent | Callable[[autogen.Agent], bool] | list,
    reply_func_from_nested_chats: str | Callable = 'summary_from_nested_chats',
    position: int = 2,
    use_async: bool | None = None,
    **kwargs
) -> None

Register a nested chat reply function.

Parameters:
NameDescription
chat_queuea 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[dict[str, typing.Any]]
triggerrefer to register_reply for details.

Type: type[autogen.Agent] | str | autogen.Agent | Callable[[autogen.Agent], bool] | list
reply_func_from_nested_chatsthe 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.

```python def reply_func_from_nested_chats( chat_queue: List[Dict], recipient: ConversableAgent, messages: Optional[List[Dict]] = None, sender: Optional[Agent] = None, config: Optional[Any] = None,

Type: str | Callable

Default: ‘summary_from_nested_chats’
positionRef 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: int

Default: 2
use_asyncUses 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 | None

Default: None
**kwargs

register_reply

register_reply(
    self,
    trigger: type[autogen.Agent] | str | autogen.Agent | Callable[[autogen.Agent], bool] | list,
    reply_func: Callable,
    position: int = 0,
    config: Any | None = None,
    reset_config: Callable | None = None,
    *,
    ignore_async_in_sync_chat: bool = False,
    remove_other_reply_funcs: bool = 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.

Parameters:
NameDescription
triggerthe 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: type[autogen.Agent] | str | autogen.Agent | Callable[[autogen.Agent], bool] | list
reply_functhe 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.

python def reply_func( recipient: ConversableAgent, messages: Optional[List[Dict]] = None, sender: Optional[Agent] = None, config: Optional[Any] = None, ) -> Tuple[bool, Union[str, Dict, None]]:

Type: Callable
positionthe 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: int

Default: 0
configthe config to be passed to the reply function.

When an agent is reset, the config will be reset to the original value.

Type: Any | None

Default: None
reset_configthe function to reset the config.

The function returns None.

Signature: def reset_config(config: Any)

Type: Callable | None

Default: None
ignore_async_in_sync_chatwhether 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: bool

Default: False
remove_other_reply_funcswhether to remove other reply functions when registering this reply function.

Type: bool

Default: False

replace_reply_func

replace_reply_func(
    self,
    old_reply_func: Callable,
    new_reply_func: Callable
) -> 

Replace a registered reply function with a new one.

Parameters:
NameDescription
old_reply_functhe old reply function to be replaced.

Type: Callable
new_reply_functhe new reply function to replace the old one.

Type: Callable

reset

reset(self) -> 

Reset the agent.


reset_consecutive_auto_reply_counter

reset_consecutive_auto_reply_counter(self, sender: autogen.Agent | None = None) -> 

Reset the consecutive_auto_reply_counter of the sender.

Parameters:
NameDescription
senderType: autogen.Agent | None

Default: None

run

run(
    self,
    message: str,
    *,
    tools: autogen.tools.Tool | Iterable[autogen.tools.Tool] | None = None,
    executor_kwargs: dict[str, typing.Any] | None = None,
    max_turns: int | None = None,
    msg_to: Literal['agent', 'user'] = 'agent',
    clear_history: bool = False,
    user_input: bool = True
) -> autogen.ChatResult

Run a chat with the agent using the given message.

A second agent will be created to represent the user, this agent will by known by the name ‘user’.

The user can terminate the conversation when prompted or, if agent’s reply contains ‘TERMINATE’, it will terminate.

Parameters:
NameDescription
messagethe message to be processed.

Type: str
toolsthe tools to be used by the agent.

Type: autogen.tools.Tool | Iterable[autogen.tools.Tool] | None

Default: None
executor_kwargsthe keyword arguments for the executor.

Type: dict[str, typing.Any] | None

Default: None
max_turnsmaximum number of turns (a turn is equivalent to both agents having replied), defaults no None which means unlimited.

The original message is included.

Type: int | None

Default: None
msg_towhich agent is receiving the message and will be the first to reply, defaults to the agent.

Type: Literal['agent', 'user']

Default: ‘agent’
clear_historywhether to clear the chat history.

Type: bool

Default: False
user_inputthe user will be asked for input at their turn.

Type: bool

Default: True

run_code

run_code(
    self,
    code,
    **kwargs
) -> 

Run the code and return the result.

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

Parameters:
NameDescription
codethe code to be executed.

**kwargsother keyword arguments.


send

send(
    self,
    message: str | dict,
    recipient: autogen.Agent,
    request_reply: bool | None = None,
    silent: bool | None = False
) -> 

Send a message to another agent.

Parameters:
NameDescription
messagemessage 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: str | dict
recipientthe recipient of the message.

Type: autogen.Agent
request_replywhether to request a reply from the recipient.

Type: bool | None

Default: None
silent(Experimental) whether to print the message sent.

Type: bool | None

Default: False

set_context

set_context(
    self,
    key: str,
    value: Any
) -> None

Set a context variable.

Parameters:
NameDescription
keyThe key to set

Type: str
valueThe value to associate with the key

Type: Any

stop_reply_at_receive

stop_reply_at_receive(self, sender: autogen.Agent | None = None) -> 

Reset the reply_at_receive of the sender.

Parameters:
NameDescription
senderType: autogen.Agent | None

Default: None

update_agent_state_before_reply

update_agent_state_before_reply(self, messages: list[dict]) -> None

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

Parameters:
NameDescription
messagesType: list[dict]

update_context

update_context(self, context_variables: dict[str, typing.Any]) -> None

Update multiple context variables at once.

Parameters:
NameDescription
context_variablesDictionary of variables to update/add

Type: dict[str, typing.Any]

update_function_signature

update_function_signature(
    self,
    func_sig: str | dict,
    is_remove: None
) -> 

Update a function_signature in the LLM configuration for function_call.

Parameters:
NameDescription
func_sigdescription/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 | dict
is_removewhether removing the function from llm_config with name ‘func_sig’

Type: None

update_max_consecutive_auto_reply

update_max_consecutive_auto_reply(
    self,
    value: int,
    sender: autogen.Agent | None = None
) -> 

Update the maximum number of consecutive auto replies.

Parameters:
NameDescription
valuethe maximum number of consecutive auto replies.

Type: int
senderwhen the sender is provided, only update the max_consecutive_auto_reply for that sender.

Type: autogen.Agent | None

Default: None

update_system_message

update_system_message(self, system_message: str) -> None

Update the system message.

Parameters:
NameDescription
system_messagesystem message for the ChatCompletion inference.

Type: str

update_tool_signature

update_tool_signature(
    self,
    tool_sig: str | dict,
    is_remove: bool
) -> 

Update a tool_signature in the LLM configuration for tool_call.

Parameters:
NameDescription
tool_sigdescription/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 | dict
is_removewhether removing the tool from llm_config with name ‘tool_sig’

Type: bool