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

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

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

pip install git+https://github.com/ag2ai/ag2.git

Once installed, you can verify it works:

ag2 --version

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?")

2. Run your agent

python basic_agent.py

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?")

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

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
why-type-is-the-better-choice-in-react-+-typescript

Why Type Is the Better Choice in React + TypeScript

Next Post
ai-in-quality-management:-how-to-move-beyond-the-hype-and-add-real-value

AI in Quality Management: How to Move Beyond the Hype and Add Real Value

Related Posts