AutoGen Tutorial (Python): adding authentication for intermediate developers

By Cyprian AaronsUpdated 2026-04-21
autogenadding-authentication-for-intermediate-developerspython

This tutorial shows how to add authentication to an AutoGen Python setup so your agents can call protected APIs without hardcoding secrets or leaking credentials. You’ll wire API keys from environment variables into an authenticated tool, then let AutoGen use that tool in a normal multi-agent flow.

What You'll Need

  • Python 3.10+
  • autogen-agentchat
  • autogen-ext
  • python-dotenv
  • An OpenAI API key for the model client
  • A second API key for the protected service you want to call
  • Basic familiarity with AutoGen agents, tools, and async Python

Install the packages first:

pip install autogen-agentchat autogen-ext python-dotenv

Step-by-Step

  1. Start by loading credentials from environment variables.
    This keeps authentication out of source code and makes the same app work across local dev, CI, and production.
import os
from dotenv import load_dotenv

load_dotenv()

OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
PAYMENTS_API_KEY = os.environ["PAYMENTS_API_KEY"]
  1. Create an authenticated client for your model and a tool that calls a protected API.
    In real systems, this tool is where you enforce service-to-service auth, not inside the agent prompt.
import httpx
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(
    model="gpt-4o-mini",
    api_key=OPENAI_API_KEY,
)

def get_account_balance(account_id: str) -> str:
    headers = {"Authorization": f"Bearer {PAYMENTS_API_KEY}"}
    url = f"https://api.example.com/accounts/{account_id}/balance"
    response = httpx.get(url, headers=headers, timeout=10)
    response.raise_for_status()
    return response.text
  1. Register the tool with AutoGen so the assistant can call it when needed.
    The important part is that the function already contains auth logic, so the agent never sees the secret.
import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_core.tools import FunctionTool

balance_tool = FunctionTool(
    get_account_balance,
    name="get_account_balance",
    description="Fetches the current balance for a customer account using authenticated API access.",
)

assistant = AssistantAgent(
    name="assistant",
    model_client=model_client,
    tools=[balance_tool],
)
  1. Add a user-facing agent and run a short conversation.
    This gives you a clean entry point for testing whether the assistant can use the authenticated tool correctly.
from autogen_agentchat.agents import UserProxyAgent

user_proxy = UserProxyAgent(name="user")

async def main() -> None:
    result = await user_proxy.run(
        assistant,
        task="Check balance for account 12345 and summarize it in one sentence.",
    )
    print(result.messages[-1].content)

if __name__ == "__main__":
    asyncio.run(main())
  1. If your protected API uses session tokens instead of static keys, refresh them before each request.
    That pattern matters in banking and insurance integrations where short-lived tokens are standard.
def build_auth_headers() -> dict[str, str]:
    token = os.environ["PAYMENTS_API_TOKEN"]
    return {
        "Authorization": f"Bearer {token}",
        "X-Client-Id": os.environ["PAYMENTS_CLIENT_ID"],
    }

def get_account_balance_v2(account_id: str) -> str:
    url = f"https://api.example.com/accounts/{account_id}/balance"
    response = httpx.get(url, headers=build_auth_headers(), timeout=10)
    response.raise_for_status()
    return response.text

Testing It

Run the script with valid values for OPENAI_API_KEY and PAYMENTS_API_KEY in your environment. If the auth is wired correctly, the tool call should succeed and return data from the protected endpoint instead of failing with 401 Unauthorized.

If you want to verify failure handling, temporarily set PAYMENTS_API_KEY to an invalid value and rerun it. You should see the upstream API reject the request, which confirms your agent is not bypassing authentication.

For local debugging, log only metadata like status codes and request IDs. Do not print headers or raw tokens; that’s how secrets end up in logs.

Next Steps

  • Add retry logic with backoff around authenticated HTTP calls using httpx or tenacity
  • Move from API keys to OAuth2 client credentials for enterprise integrations
  • Wrap multiple authenticated tools behind one assistant and route requests based on policy

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides