AutoGen offers conversable agents powered by LLM, tool, or human, which can be used to perform tasks collectively via automated chat. This framework allows tool use and human participation through multi-agent conversation. Please find documentation about this feature here.
In this notebook, we demonstrate how to use AssistantAgent
and UserProxyAgent
to make function calls with the new feature of OpenAI models (in model version 0613). A specified prompt and function configs must be passed to AssistantAgent
to initialize the agent. The corresponding functions must be passed to UserProxyAgent
, which will execute any function calls made by AssistantAgent
. Besides this requirement of matching descriptions with functions, we recommend checking the system message in the AssistantAgent
to ensure the instructions align with the function call descriptions.
AutoGen requires Python>=3.8
. To run this notebook example, please install pyautogen
:
pip install pyautogen
# %pip install "pyautogen>=0.2.3"
The config_list_from_json
function loads a list of configurations from an environment variable or a json file.
from IPython import get_ipython
from typing_extensions import Annotated
import autogen
config_list = autogen.config_list_from_json(
"OAI_CONFIG_LIST",
filter_dict={
"model": ["gpt-4", "gpt-3.5-turbo", "gpt-3.5-turbo-16k"],
},
)
It first looks for environment variable "OAI_CONFIG_LIST" which needs to be a valid json string. If that variable is not found, it then looks for a json file named "OAI_CONFIG_LIST". It filters the configs by models (you can filter by other keys as well). Only the models with matching names are kept in the list based on the filter condition.
The config list looks like the following:
config_list = [
{
'model': 'gpt-4',
'api_key': '<your OpenAI API key here>',
},
{
'model': 'gpt-3.5-turbo',
'api_key': '<your Azure OpenAI API key here>',
'base_url': '<your Azure OpenAI API base here>',
'api_type': 'azure',
'api_version': '2023-08-01-preview',
},
{
'model': 'gpt-3.5-turbo-16k',
'api_key': '<your Azure OpenAI API key here>',
'base_url': '<your Azure OpenAI API base here>',
'api_type': 'azure',
'api_version': '2023-08-01-preview',
},
]
You can set the value of config_list in any way you prefer. Please refer to this notebook for full code examples of the different methods.
In this example, we demonstrate function call execution with AssistantAgent
and UserProxyAgent
. With the default system prompt of AssistantAgent
, we allow the LLM assistant to perform tasks with code, and the UserProxyAgent
would extract code blocks from the LLM response and execute them. With the new "function_call" feature, we define functions and specify the description of the function in the OpenAI config for the AssistantAgent
. Then we register the functions in UserProxyAgent
.
llm_config = {
"config_list": config_list,
"timeout": 120,
}
chatbot = autogen.AssistantAgent(
name="chatbot",
system_message="For coding tasks, only use the functions you have been provided with. Reply TERMINATE when the task is done.",
llm_config=llm_config,
)
# create a UserProxyAgent instance named "user_proxy"
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
is_termination_msg=lambda x: x.get("content", "") and x.get("content", "").rstrip().endswith("TERMINATE"),
human_input_mode="NEVER",
max_consecutive_auto_reply=10,
code_execution_config={"work_dir": "coding"},
)
# define functions according to the function description
@user_proxy.register_for.execution()
@chatbot.register_for.llm(name="python", description="run cell in ipython and return the execution result.")
def exec_python(cell: Annotated[str, "Valid Python cell to execute."]) -> str:
ipython = get_ipython()
result = ipython.run_cell(cell)
log = str(result.result)
if result.error_before_exec is not None:
log += f"\n{result.error_before_exec}"
if result.error_in_exec is not None:
log += f"\n{result.error_in_exec}"
return log
@user_proxy.register_for.execution()
@chatbot.register_for.llm(name="sh", description="run a shell script and return the execution result.")
def exec_sh(script: Annotated[str, "Valid Python cell to execute."]) -> str:
return user_proxy.execute_code_blocks([("sh", script)])
# start the conversation
user_proxy.initiate_chat(
chatbot,
message="Draw two agents chatting with each other with an example dialog. Don't add plt.show().",
)
user_proxy (to chatbot): Draw two agents chatting with each other with an example dialog. Don't add plt.show(). -------------------------------------------------------------------------------- chatbot (to user_proxy): ***** Suggested function Call: python ***** Arguments: { "cell": "import matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\n# Create a figure to draw\nfig, ax = plt.subplots(figsize=(8, 5))\n\n# Set plot limits to avoid text spilling over\nax.set_xlim(0, 2)\nax.set_ylim(0, 2)\n\n# Hide axes\nax.axis('off')\n\n# Draw two agents\nhead_radius = 0.1\n\n# Agent A\nax.add_patch(patches.Circle((0.5, 1.5), head_radius, color='blue'))\n# Agent B\nax.add_patch(patches.Circle((1.5, 1.5), head_radius, color='green'))\n\n# Example dialog\nbbox_props = dict(boxstyle=\"round,pad=0.3\", ec=\"black\", lw=1, fc=\"white\")\nax.text(0.5, 1.3, \"Hello, how are you?\", ha=\"center\", va=\"center\", size=8, bbox=bbox_props)\nax.text(1.5, 1.3, \"I'm fine, thanks!\", ha=\"center\", va=\"center\", size=8, bbox=bbox_props)\n" } ******************************************* -------------------------------------------------------------------------------- >>>>>>>> EXECUTING FUNCTION python...
Text(1.5, 1.3, "I'm fine, thanks!")
user_proxy (to chatbot): ***** Response from calling function "python" ***** Text(1.5, 1.3, "I'm fine, thanks!") *************************************************** -------------------------------------------------------------------------------- chatbot (to user_proxy): The drawing of two agents with example dialog has been executed, but as instructed, `plt.show()` has not been added, so the image will not be displayed here. However, the script created a matplotlib figure with two agents represented by circles, one blue and one green, along with example dialog text in speech bubbles. -------------------------------------------------------------------------------- user_proxy (to chatbot): -------------------------------------------------------------------------------- chatbot (to user_proxy): TERMINATE --------------------------------------------------------------------------------