AutoGen Tutorial: A Guide to Building AI Agents
In today’s fast-paced AI landscape, building intelligent and interactive agents has never been more accessible. With AutoGen, we now have a powerful and flexible framework that enables developers and enthusiasts to create multi-agent AI systems with ease.
Whether you’re a complete beginner or just exploring advanced AI tools, this AutoGen tutorial will guide you through the essential components, practical use cases, and hands-on steps to build your very first AI agent.
Let’s start the discussion with a brief overview of AutoGen.
What is AutoGen?
AutoGen is an open-source Python framework developed by Microsoft that allows us to build conversational multi-agent systems. Unlike traditional single-agent solutions, AutoGen provides an intuitive way to define and manage multiple AI agents that can collaborate, reason, and execute tasks in a structured dialogue format.
At its core, AutoGen is designed to maximize modularity, customization, and control, giving us the ability to configure how agents interact with each other and external tools or APIs. It leverages LLMs (Large Language Models) like GPT, enabling the development of both autonomous and human-in-the-loop systems.
Now that we understand what AutoGen is, let’s explore the core components that make this framework so versatile.
Key components of AutoGen
AutoGen is built around four main pillars. Understanding these will help us design, customize, and deploy AI agents more effectively.
1. AutoGen Studio
AutoGen Studio is the visual workspace where we can create, configure, and test AI agents without needing to write a single line of code at first. It is perfect for rapid prototyping and for showcasing ideas to stakeholders before committing to a fully coded solution.
AutoGen Studio uses a drag-and-drop interface for designing workflows, setting agent roles, and connecting them to data sources or APIs. We can tweak parameters, monitor live agent interactions, and even test multiple scenarios — all from one interface. This makes AutoGen Studio a natural starting point for beginners and a time-saver for experienced developers.
To install AutoGen Studio, we can run this command in the terminal:
pip install -U AutoGenstudio
2. AutoGen AgentChat
AutoGen AgentChat is the conversational backbone of the framework. It handles how multiple AI agents — and even humans — communicate in structured, multi-turn dialogues.
With AgentChat, we can assign specialized roles to each agent, set up rules for interaction, and allow agents to share knowledge or divide tasks. This isn’t just basic chat — it’s intelligent coordination where one agent might plan an itinerary, another checks weather conditions, and a third books accommodations. By enabling collaborative conversations, AutoGen AgentChat unlocks far more complex and realistic agent behavior.
To install AutoGen AgentChat, we can run this command in the terminal:
pip install -U "AutoGen-agentchat" "AutoGen-ext[openai]"
3. AutoGen Core
AutoGen Core is the engine that powers everything under the hood. It’s a Python-based framework responsible for task orchestration, state management, and integration with external systems. Whether we’re building in AutoGen Studio or coding from scratch, this component executes the logic that drives agent behavior.
AutoGen Core also supports advanced features like function calls, memory retention, and asynchronous workflows. In short, AutoGen Core is the reason our agents can move from “just talking” to actually doing things.
To install AutoGen Core, we can run this command in the terminal:
pip install "autogen-core"
4. AutoGen Extensions
AutoGen Extensions expand the framework’s capabilities beyond its default functions. They let us integrate third-party APIs, domain-specific datasets, and custom-built Python functions into our agents’ workflows.
For example, we could connect a travel planning agent to a live flight API, integrate financial data for investment assistants, or plug in custom-trained machine learning models for specialized industries. These extensions give AutoGen the flexibility to adapt to any project, from small-scale personal tools to enterprise-grade automation systems.
To install AutoGen Extensions, we can run this command in the terminal:
playwright install
With this knowledge, let’s put theory into practice by building a simple AI agent using AutoGen AgentChat.
Build a travel planning agent using AutoGen
Let’s walk through a step-by-step AutoGen tutorial to create a travel planning agent.
Step 1: Import the necessary modules
First, create a new Python file named agent.py:
touch agent.py
Next, open the file and import the necessary modules:
import osimport asynciofrom autogen_agentchat.agents import AssistantAgentfrom autogen_agentchat.conditions import TextMentionTerminationfrom autogen_agentchat.teams import RoundRobinGroupChatfrom autogen_agentchat.ui import Consolefrom autogen_ext.models.openai import OpenAIChatCompletionClient
Then, set your OpenAI API key as an environment variable by assigning it to the OPENAI_API_KEY variable. This way, the agent can access the model without requiring us to enter the OpenAI API key every time we run it. If you don’t have an OpenAI API key, create one by navigating to the official website:
os.environ["OPENAI_API_KEY"] = "<OPENAI_API_KEY>"
Step 2: Create a planner agent
Start by creating an asynchronous main() function that initializes the OpenAI model client. Here, we’re using the gpt-4o-mini model:
async def main():model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")asyncio.run(main())
Next, define the planner agent with a name, description, and system message that guides its behavior. This agent will generate a personalized travel plan for the user:
planner_agent = AssistantAgent(name="planner_agent",model_client=model_client,description="A helpful assistant that can create personalized travel plans.",system_message="You are a helpful assistant that suggests a detailed travel plan for a user based on their destination, budget, and preferences.")
Step 3: Define the prompt
Primarily, define a termination condition so that the chat ends when a specific keyword ("TERMINATE" in this case) is mentioned:
termination = TextMentionTermination("TERMINATE")
Then, create a group chat with the planner agent and the termination condition:
group_chat = RoundRobinGroupChat([planner_agent], termination_condition=termination)
Next, define the prompt and close the model client once the conversation ends to free up resources:
await Console(group_chat.run_stream(task="I want a 5-day vacation to Japan under $2500."))await model_client.close()
Step 4: Run the agent
Finally, it’s time to run the agent:
python agent.py
Here is the output:
---------- TextMessage (planner_agent) ----------That sounds like a fantastic trip! Here’s a detailed 5-day itinerary for Japan focused on culture, nature, and local experiences, all while keeping you within a budget of $2500.### Day 1: Arrival in Tokyo**Morning:**- Flight arrival at Narita or Haneda Airport.- Airport transfer to your accommodation (consider staying in a budget-friendly capsule hotel or a traditional ryokan for an authentic experience).**Afternoon:**- Head to Asakusa to visit the iconic Senso-ji Temple. Explore the charming streets of Nakamise for traditional snacks and souvenirs.- Lunch at a local restaurant (try some tempura or soba).**Evening:**- Take a walk through Ueno Park and visit some local museums (like the Tokyo National Museum or Ueno Zoo).- Dinner at a local izakaya in the Ueno area (budget around $30).### Day 2: Nikko Day Trip**Morning:**- Take an early train from Tokyo to Nikko (approx. 2 hours; round-trip ticket ~$30).- Visit the UNESCO World Heritage sites, including Toshogu Shrine and the beautiful national parks.**Afternoon:**- Have lunch at a local café in Nikko.- Explore Kegon Falls and Lake Chuzenji for breathtaking natural scenery.**Evening:**- Return to Tokyo.- Dinner in Shinjuku, exploring the vibrant nightlife (try local ramen; budget around $15).### Day 3: Kyoto**Morning:**- Take the shinkansen (bullet train) from Tokyo to Kyoto (1 hour and 30 minutes; reserve a round trip ticket for about $150).- Check into your accommodation (consider a guesthouse or ryokan).**Afternoon:**- Visit Kinkaku-ji (Golden Pavilion), a stunning Zen Buddhist temple surrounded by beautiful gardens.- Lunch nearby at a local restaurant (try yudofu, a tofu dish).**Evening:**- Stroll through the Arashiyama Bamboo Grove and visit the Iwatayama Monkey Park.- Dinner in the Gion district, known for traditional tea houses (budget around $35).### Day 4: Kyoto Cultural Immersion**Morning:**- Participate in a traditional tea ceremony in Kyoto; many teahouses offer this experience for around $40.**Afternoon:**- Visit Fushimi Inari Taisha, famous for its thousands of red torii gates. Take your time to hike up the mountain for beautiful views.- Lunch at a local eatery near Fushimi Inari.**Evening:**- Enjoy a quiet evening by the Kamo River or visit the Philosopher's Path, especially beautiful if Sakura (cherry blossoms) are in bloom.- Dinner at a local kaiseki restaurant; it can be higher-end, but you can find reasonably priced options (around $50).### Day 5: Osaka and Departure**Morning:**- Take a quick train ride to Osaka (30 minutes; ticket ~$10).- Visit Osaka Castle and the surrounding park to appreciate the history and nature.**Afternoon:**- Explore the Dotonbori area for last-minute shopping and tasting local street foods (like takoyaki and okonomiyaki). Budget around $25 for lunch.**Evening:**- Depending on your flight time, rest and prepare for your journey back.- Airport transfer to either Kyoto/Osaka for your flight home.**Estimated Budget Breakdown:**- Flights (round trip to Japan): ~$1200 (very rough estimate; varies greatly)- Accommodation: ~$400 (average $80 per night)- Trains and local transport: ~$250 (including shinkansen and day trips)- Food: ~$350 ($70 per day)- Activities (museums, tea ceremonies, local experiences): ~$200- Miscellaneous and souvenirs: ~$100### Total Estimated Cost: ~$2500This itinerary offers a wonderful blend of cultural experiences, nature, and local life while maintaining your budget. Make sure to check for any necessary reservations or passes in advance, especially for popular attractions. Safe travels!
While this is a basic example, AutoGen can scale to much more complex applications. But why should we choose AutoGen over other frameworks?
Why use AutoGen?
- Multi-agent coordination: AutoGen excels at orchestrating multiple AI agents that collaborate toward a shared goal.
- Flexible design: With both code-based and GUI-based options via AutoGen Studio, it supports rapid prototyping and deployment.
- Human-in-the-loop integration: We can integrate human input when necessary to ensure safety and reliability.
- Function integration: AutoGen allows agents to call Python functions, APIs, or even control external applications.
So, where can we apply this powerful tool in real-world scenarios?
AutoGen use cases
- Customer support bots: Multi-agent bots can triage, answer FAQs, and escalate tickets to human agents.
- Business automation: Automate report generation, summarization, and document workflows using coordinated AI agents.
- Educational tools: Tutors, quiz generators, and feedback assistants can work together to enhance learning.
- Travel and itinerary planning: Agents gather preferences, suggest destinations, and even provide book services.
To make the most out of AutoGen, we need to follow some best practices.
Best practices for using AutoGen
To ensure your AI agents are reliable and efficient, consider these best practices:
- Clearly define agent roles: Assign specific goals and avoid overlapping responsibilities.
- Limit agent count: Start small to keep the system manageable and avoid unnecessary complexity.
- Use guardrails: Implement human-in-the-loop mechanisms for critical or sensitive tasks.
- Monitor performance: Log interactions, track errors, and fine-tune based on usage patterns.
As we conclude this tutorial, let’s summarize what we’ve learned and reflect on the power of AutoGen.
Conclusion
In this tutorial, we discussed how to build a simple travel planning AI agent using AutoGen. We covered what it is, how it works, its key components, and the reasons for using it. We also explored its use cases and went through some best practices for using AutoGen effectively.
AutoGen represents a significant leap in AI agent development, empowering us to build dynamic, intelligent systems that can simulate teamwork and collaborative problem-solving. Whether you’re creating chatbots or autonomous task agents, AutoGen Studio and its Python toolkit offer the flexibility and scalability needed for the future of AI.
If you want to learn more about building AI agents, check out the Learn How to Build AI Agents course on Codecademy.
Frequently asked questions
1. What is AutoGen used for?
AutoGen is used to build multi-agent AI systems that perform complex tasks through collaboration. Applications include customer service bots, planning tools, educational apps, and more.
2. Is AutoGen better than LangGraph?
AutoGen and LangGraph serve different purposes. AutoGen is focused on multi-agent dialogue systems, while LangGraph is more graph-based and modular in execution flow. Depending on your project needs, either could be better.
3. What is the difference between AutoGen and LangChain?
LangChain is focused on creating tool-using, prompt-based AI workflows, whereas AutoGen emphasizes agent-based collaboration and conversational task execution. LangChain is more mature in the tooling ecosystem, while AutoGen shines in multi-agent orchestration.
4. What is the difference between AutoGen and AutoGPT?
AutoGPT is an autonomous agent built on top of LLMs, aimed at achieving goals with minimal user input. AutoGen, on the other hand, provides the infrastructure to build multiple agents that can communicate and collaborate, offering more control and modularity.
5. Is AutoGen free to use?
Yes, AutoGen is open-source and free to use. However, you may incur costs when using it with paid LLM APIs like OpenAI’s GPT-4.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Top AI Agent Frameworks in 2025
Discover the top AI agent frameworks in 2025. Compare LangChain, AutoGen, CrewAI & more to choose the best agentic AI framework for your project. - Article
ChatGPT Agents: 3 Powerful Ways to Automate Tasks with AI
Learn ChatGPT agents with 3 practical examples. Automate tasks, boost productivity, and build your own AI agent. - Article
How to Build Agents with Vertex AI Builder
Build AI agents with Vertex AI Agent Builder. Learn to use Agent Garden, ADK, and Agent Engine to deploy custom agents.
Learn more on Codecademy
- Learn to build autonomous AI agents that use tools, make decisions, and accomplish complex tasks using LangChain and agentic design patterns.
- Includes 6 Courses
- With Certificate
- Intermediate.6 hours
- Understand AI agents from the ground up in this beginner-friendly course covering autonomous systems and agentic workflows.
- Beginner Friendly.< 1 hour
- Learn to build stateful AI agents with persistent memory using Letta's MemGPT architecture—designed for developers and ML engineers.
- Beginner Friendly.1 hour