DEV Community

Cover image for AG-2 in Practice #2 – Setting Up AG-2 and Creating Your First Agent
Daniel Azevedo
Daniel Azevedo

Posted on

AG-2 in Practice #2 – Setting Up AG-2 and Creating Your First Agent

Welcome back!

In the first post of this series, we explored what AG-2 is and how it works under the hood. Now it’s time to get hands-on: we’re going to install AG-2 locally and build your first functional agent — a small but powerful assistant that can answer questions using a tool.


Step 1: Prerequisites

To follow along, you’ll need:

  • Python 3.10+
  • pip
  • Basic terminal/command line knowledge
  • An OpenAI API key (for using LLMs)

Optional (but recommended):

  • A virtual environment (e.g., venv, conda)

Step 2: Installing AG-2

Let’s get AG-2 up and running. In your terminal:

pip install ag2
Enter fullscreen mode Exit fullscreen mode

Or, if you prefer to use the latest development version:

pip install git+https://github.com/ag2ai/ag2.git
Enter fullscreen mode Exit fullscreen mode

Once installed, you can verify it works:

ag2 --version
Enter fullscreen mode Exit fullscreen mode

Step 3: Setting Up Your First Agent

Now let’s create a simple question-answering agent.

1. Create a Python file

Create a file called basic_agent.py:

from ag2 import Agent, Orchestrator, Conversation, Tool
import os

# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = "your-api-key-here"

# Define a basic agent
qa_agent = Agent(
    name="qa_agent",
    llm="openai/gpt-4",
    system_message="You are a helpful assistant that answers questions clearly.",
)

# Start a conversation
conv = Conversation(agents=[qa_agent])
conv.send("What is the capital of France?")
Enter fullscreen mode Exit fullscreen mode

2. Run your agent

python basic_agent.py
Enter fullscreen mode Exit fullscreen mode

You should see an answer like:
"The capital of France is Paris."

Congrats — you just ran your first AG-2 agent!


Step 4: Adding a Tool

Let’s make your agent smarter by giving it a tool.

from ag2 import Tool

# Create a simple calculator tool
def add_numbers(a: int, b: int) -> int:
    return a + b

calculator = Tool(
    name="calculator",
    description="Adds two numbers.",
    func=add_numbers,
)

# Attach the tool to the agent
qa_agent.tools = [calculator]

# New conversation
conv = Conversation(agents=[qa_agent])
conv.send("What is 3 + 4?")
Enter fullscreen mode Exit fullscreen mode

Now, the agent can use the calculator tool instead of relying only on LLM guesswork!


What’s Next?

In the next post, we’ll:

  • Create multiple agents with different roles
  • Make them collaborate in a workflow (e.g., researcher + writer + reviewer)
  • Explore patterns for multi-agent orchestration

Keep coding

Top comments (0)