Article
multi-agentagentic-workflowspythoncode-generationmicrosoft-autogenorchestrationllm-collaboration
Build a Coder Agent Team with AutoGen
Use Microsoft's AutoGen to create a two-agent team. An AssistantAgent writes Python code to solve a task, and a UserProxyAgent executes the code, requests revisions, and confirms the solution. This demonstrates automated, collaborative problem-solving.
intermediate30 min4 steps
The play
- Install AutoGen and DependenciesInstall the `pyautogen` library using pip. For this example, we'll also install libraries for data fetching and plotting. AutoGen uses an LLM, so you must have an API key (e.g., from OpenAI) set as an environment variable.
- Configure the LLM ConnectionIn your Python script, define a configuration list that tells AutoGen which LLM to use. This example uses GPT-4 and reads the API key from the environment variable you just set.
- Define the Assistant and User Proxy AgentsCreate two agents. The `AssistantAgent` is the AI worker that writes code. The `UserProxyAgent` acts on your behalf to execute code and provide feedback. Setting `human_input_mode` to `TERMINATE` allows the process to end automatically on success.
- Initiate the TaskStart the conversation between the agents by giving the `UserProxyAgent` a task. The agents will now collaborate: the Coder will write Python code, and the UserProxy will execute it, until the final file is created.
Starter code
import os
import autogen
# Ensure you have an OPENAI_API_KEY set in your environment variables
if not os.environ.get("OPENAI_API_KEY"):
raise ValueError("OPENAI_API_KEY environment variable not set.")
# 1. Define the LLM configuration
config_list = [
{
'model': 'gpt-4',
'api_key': os.environ.get('OPENAI_API_KEY'),
}
]
# 2. Create the agent team
# The assistant agent (the coder)
assistant = autogen.AssistantAgent(
name="Coder",
llm_config={'config_list': config_list}
)
# The user proxy agent (executes code and acts as the user)
user_proxy = autogen.UserProxyAgent(
name="UserProxy",
human_input_mode="TERMINATE", # End conversation once task is done
max_consecutive_auto_reply=10,
is_termination_msg=lambda x: x.get("content", "").rstrip().endswith("TERMINATE"),
code_execution_config={
"work_dir": "coding", # Directory to save code and files
"use_docker": False, # Set to True to run code in a Docker container
},
llm_config={'config_list': config_list}
)
# 3. Start the task
user_proxy.initiate_chat(
assistant,
message="""Plot a chart of NVDA and TSLA stock price change YTD. Save the chart to a file named 'stock_ytd_chart.png'."""
)
print("\nTask complete. Check the 'coding' directory for 'stock_ytd_chart.png'.")