AutoGen’s multi-agent framework works best when you isolate its dependencies and point it at a reliable model gateway. This guide walks through creating a reproducible Python environment, configuring n4n.ai as the OpenAI-compatible endpoint, and verifying everything with a minimal two-agent conversation. You’ll end up with a setup you can commit to version control and share across a team.
Step 1: Choose a python version and create a virtual environment
AutoGen supports Python 3.10 through 3.12. Pick the version your CI/CD pipeline already uses to avoid surprises. If you manage multiple projects, pyenv or uv makes switching painless.
# Using uv (fast, rust-based, handles python installs)
uv venv --python 3.11 .venv
source .venv/bin/activate
# Or with the standard library
python3.11 -m venv .venv
source .venv/bin/activate
Verify the interpreter resolves correctly:
which python
# /path/to/project/.venv/bin/python
python --version
# Python 3.11.x
Step 2: Install autogen and its core dependencies
Install the autogen-agentchat package (the v0.4+ API) plus openai for the client wrapper. Pin versions in a requirements.txt so the environment is reproducible.
cat > requirements.txt << 'EOF'
autogen-agentchat==0.4.0
openai==1.40.0
python-dotenv==1.0.1
EOF
pip install -r requirements.txt
If you need code execution inside agents, add autogen-ext[code-executor] — but skip it for now to keep the environment minimal.
Step 3: Configure n4n.ai credentials and endpoint
n4n.ai exposes an OpenAI-compatible endpoint at https://api.n4n.ai/v1. Store the base URL and your API key in a .env file so they stay out of source control.
cat > .env << 'EOF'
N4N_API_KEY=sk-your-key-here
N4N_BASE_URL=https://api.n4n.ai/v1
EOF
Load these values in Python with python-dotenv:
# config.py
import os
from dotenv import load_dotenv
load_dotenv()
N4N_API_KEY = os.getenv("N4N_API_KEY")
N4N_BASE_URL = os.getenv("N4N_BASE_URL", "https://api.n4n.ai/v1")
if not N4N_API_KEY:
raise RuntimeError("N4N_API_KEY not set. Check .env file.")
Step 4: Create a minimal autogen client wrapper
AutoGen’s AssistantAgent expects an OpenAI client instance. Point it at the n4n.ai base URL and pass the key. This single wrapper lets you swap models via routing headers later without changing agent code.
# client.py
from openai import OpenAI
from config import N4N_API_KEY, N4N_BASE_URL
def get_client() -> OpenAI:
return OpenAI(
api_key=N4N_API_KEY,
base_url=N4N_BASE_URL,
)
Step 5: Define a two-agent conversation script
Create a run_agents.py that spins up a UserProxyAgent (simulates the human) and an AssistantAgent backed by n4n.ai. Use a simple termination condition so the script exits cleanly.
# run_agents.py
import asyncio
from autogen_agentchat.agents import AssistantAgent, UserProxyAgent
from autogen_agentchat.conditions import MaxMessageTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.messages import TextMessage
from client import get_client
async def main():
client = get_client()
assistant = AssistantAgent(
name="planner",
model_client=client,
model="gpt-4o-mini", # routed by n4n.ai
system_message="You are a concise planning assistant. Reply with a numbered list of steps.",
)
user_proxy = UserProxyAgent(
name="user",
input_func=lambda _: "Plan a weekend trip to Portland, OR for two people.",
)
team = RoundRobinGroupChat(
[user_proxy, assistant],
termination_condition=MaxMessageTermination(max_messages=4),
)
async for msg in team.run_stream():
if isinstance(msg, TextMessage):
print(f"[{msg.source}] {msg.content}")
if __name__ == "__main__":
asyncio.run(main())
Step 6: Run and verify the conversation
Execute the script. You should see the user prompt followed by a numbered plan from the assistant.
python run_agents.py
Expected output (content will vary by model):
[user] Plan a weekend trip to Portland, OR for two people.
[planner] 1. Book accommodation in Pearl District or Alberta Arts District.
2. Friday dinner at Le Pigeon, Saturday brunch at Tasty's.
3. Saturday: Powell's Books, food carts at Cartopia, evening at Mississippi Studios.
4. Sunday: Columbia River Gorge day trip (Multnomah Falls, Hood River).
5. Reserve return travel Sunday evening.
If you see an authentication error, double-check N4N_API_KEY in .env. If the request times out, confirm N4N_BASE_URL is exactly https://api.n4n.ai/v1 with no trailing slash.
Step 7: Add model routing directives (optional)
n4n.ai honors x-n4n-model and x-n4n-fallback headers. Pass them through the model parameter or via extra_headers on the client for per-request control.
# client.py (extended)
from openai import OpenAI
from config import N4N_API_KEY, N4N_BASE_URL
def get_client(model: str = "gpt-4o-mini", fallback: str | None = None) -> OpenAI:
headers = {"x-n4n-model": model}
if fallback:
headers["x-n4n-fallback"] = fallback
return OpenAI(
api_key=N4N_API_KEY,
base_url=N4N_BASE_URL,
default_headers=headers,
)
Now get_client("claude-3-5-sonnet", fallback="gpt-4o") routes first to Claude, then falls back to GPT-4o automatically if the primary provider is degraded.
Step 8: Freeze the environment for ci/cd
Generate a lock file so every developer and CI runner gets identical transitive dependencies.
pip freeze > requirements.lock.txt
Commit requirements.txt, requirements.lock.txt, .env.example (with placeholder values), and the Python modules. Add .env and .venv/ to .gitignore.
# .gitignore
.venv/
.env
__pycache__/
*.pyc
Step 9: Verify in a clean container (smoke test)
Run the same steps in a throwaway container to prove the environment is self-contained.
# Dockerfile.test
FROM python:3.11-slim
WORKDIR /app
COPY requirements.lock.txt .
RUN pip install --no-cache-dir -r requirements.lock.txt
COPY . .
RUN python run_agents.py
docker build -f Dockerfile.test -t autogen-n4n-test .
docker run --rm --env-file .env autogen-n4n-test
The container should print the same two-agent exchange. If it does, your setup is portable.
Step 10: Common pitfalls and fixes
| Symptom | Cause | Fix |
|---|---|---|
ModuleNotFoundError: autogen_agentchat |
Installed legacy pyautogen instead of autogen-agentchat |
pip uninstall pyautogen && pip install autogen-agentchat==0.4.0 |
AuthenticationError: Invalid API key |
Key missing or has whitespace | cat .env — ensure no quotes or newlines around the value |
ConnectionError: api.n4n.ai |
DNS or firewall block | curl -I https://api.n4n.ai/v1/models from the same network |
| Agent loops forever | Termination condition too loose | Use MaxMessageTermination or a custom TerminationCondition |
Next steps
You now have a minimal, version-controlled AutoGen environment routed through n4n.ai. From here you can:
- Swap
RoundRobinGroupChatforSelectorGroupChatto let an LLM choose the next speaker. - Add
autogen-ext[code-executor]and aDockerCommandLineCodeExecutorfor agents that write and run code. - Instrument the client with
n4n.aiusage headers (x-n4n-user-id,x-n4n-session-id) to correlate costs per workflow.
The pattern stays the same: isolate dependencies, configure the gateway once, and let agents focus on logic.