To install autogen connect n4n.ai api, you need a Python 3.10+ environment and a gateway key. This walkthrough takes you from an empty directory to a running two-agent conversation against the OpenAI-compatible endpoint, with verification steps you can trust.
Step 1: Prerequisites
Confirm your local toolchain before touching code. You need Python 3.10 or newer, pip 23+, and a shell that can export environment variables.
python3 --version
pip --version
Get an API key from your n4n.ai account dashboard. The key is a bearer token used for all requests to the gateway. Store it in a password manager; you will export it locally but never commit it.
You also need a model name that the gateway can route to. AutoGen sends the model field straight through, so pick an identifier that exists on the gateway side (for example gpt-4o-mini or a Claude snapshot).
Step 2: Create an isolated environment
Never install agent frameworks into your system Python. Create a fresh virtual environment to avoid dependency conflicts with other projects.
mkdir autogen-n4n-demo && cd autogen-n4n-demo
python3 -m venv .venv
source .venv/bin/activate
On Windows use .venv\Scripts\activate. Your prompt should now show the venv prefix.
Step 3: Install AutoGen
The stable AutoGen line (v0.2.x) ships as pyautogen. Install it with pip:
pip install pyautogen
If you prefer the newer event-driven packages, autogen-agentchat works too, but the config pattern below uses the classic autogen module that most production code still imports. Pin a version to keep builds reproducible:
pip install pyautogen==0.2.32
Verify the import works:
python -c "import autogen; print(autogen.__version__)"
Step 4: Export credentials and endpoint
AutoGen reads OpenAI-style config. Point it at the gateway by setting OPENAI_API_KEY and OPENAI_API_BASE (or use a custom config list). For clarity, use dedicated variable names and map them in code.
export N4N_API_KEY="sk-xxxxxxxxxxxxxxxx"
export N4N_BASE_URL="https://api.n4n.ai/v1"
n4n.ai exposes an OpenAI-compatible endpoint at that base URL that fronts 240+ models with automatic fallback when a provider is rate-limited or degraded. Keep the key out of source files.
Step 5: Build the AutoGen configuration list
AutoGen expects a config_list of dicts, each describing one LLM endpoint. Build it from environment variables so the same script runs in CI or locally.
import os
from autogen import config_list_from_dotenv
config_list = [
{
"model": "gpt-4o-mini",
"api_key": os.environ["N4N_API_KEY"],
"base_url": os.environ["N4N_BASE_URL"],
"api_type": "openai",
"price": [0.00015, 0.0006], # optional: input/output per token for cost tracking
}
]
llm_config = {
"config_list": config_list,
"temperature": 0.1,
"timeout": 30,
}
If you run multiple models, append more dicts with different model keys. AutoGen round-robins or fails over based on config_list order.
Step 6: Run a two-agent conversation
Create an AssistantAgent that calls the gateway and a UserProxyAgent that simulates a user and terminates after one reply. This is the minimal loop you can extend later.
from autogen import AssistantAgent, UserProxyAgent
assistant = AssistantAgent(
name="planner",
llm_config=llm_config,
system_message="You are a concise technical planner. Reply in bullet points.",
)
user_proxy = UserProxyAgent(
name="user",
human_input_mode="NEVER",
code_execution_config=False,
max_consecutive_auto_reply=1,
)
chat_result = user_proxy.initiate_chat(
assistant,
message="List three failure modes when wiring an LLM gateway to AutoGen.",
)
print(chat_result.summary)
Run it:
python main.py
You should see the assistant’s bullet list printed without auth errors.
Step 7: Verify the connection and inspect usage
Success means three things: the process exits zero, the assistant response is non-empty, and the gateway logs show a billed request.
Add a quick assertion after the chat to make verification scriptable:
assert chat_result.summary.strip(), "Empty response from gateway"
print("OK: received", len(chat_result.summary), "chars")
Your inference gateway returns standard OpenAI usage objects. To capture them, wrap the underlying client or enable AutoGen debug logging:
export AUTOGEN_LOGLEVEL=DEBUG
Look for usage blocks in the logs showing prompt_tokens and completion_tokens. Per-token metering lets you reconcile cost after the run without custom instrumentation.
If you see AuthenticationError, re-check N4N_API_KEY. A 404 on the model usually means the model string isn’t routed by the gateway—list available models from your dashboard.
Step 8: Optional — model routing and cache hints
Because n4n.ai honors client routing directives and forwards provider cache-control hints, you can pin a model per request or enable caching without changing AutoGen’s core loop. Pass extra headers through the extra_headers field in the config dict:
config_list[0]["extra_headers"] = {
"x-n4n-route": "anthropic:claude-3-5-sonnet",
"x-n4n-cache": "ephemeral",
}
AutoGen forwards these untouched. Use routing to force a specific provider during eval, and cache hints to cut repeat-prompt cost on long system messages.
Troubleshooting
SSL certificate errors. Corporate proxies often break TLS. Set REQUESTS_CA_BUNDLE or use base_url with http only in isolated test nets.
Model not found. The gateway returns a clean 404 if the model field isn’t in its catalog. Double-check spelling; AutoGen does not validate before send.
Rate limits. If you hammer the endpoint, the gateway returns 429. The automatic fallback mentioned above switches providers when configured, but single-model configs will surface the error to AutoGen. Add retry logic with max_consecutive_auto_reply and exponential backoff in your wrapper.
Old OpenAI SDK conflict. pyautogen pins openai<1.30 in some versions. If you see TypeError: client.chat.completions.create(), upgrade or downgrade the openai package to match AutoGen’s requirement.
What you have now
You installed AutoGen, pointed it at an OpenAI-compatible gateway, and ran a multi-agent chat with verifiable output. The same config_list pattern scales to group chats, code executors, and retrieval agents. Swap the model string or add extra_headers to change routing without refactoring your agent logic.