AutoGen Tutorial (TypeScript): adding authentication for beginners
This tutorial shows how to add authentication to an AutoGen TypeScript agent so it can call a protected API using a bearer token. You need this when your agent talks to internal services, customer data APIs, or any endpoint that rejects unauthenticated requests.
What You'll Need
- •Node.js 18+ installed
- •A TypeScript project with
ts-nodeortsx - •AutoGen installed:
npm install @autogenai/autogen - •
axiosfor HTTP calls:npm install axios - •An API key for your LLM provider, such as:
- •
OPENAI_API_KEY
- •
- •A protected API that accepts
Authorization: Bearer <token> - •Basic familiarity with AutoGen agents and tools
Step-by-Step
- •Start by creating a small TypeScript project and loading your environment variables. The key point is to keep secrets out of code and read them at runtime.
import "dotenv/config";
const openaiApiKey = process.env.OPENAI_API_KEY;
const serviceToken = process.env.SERVICE_TOKEN;
if (!openaiApiKey) {
throw new Error("Missing OPENAI_API_KEY");
}
if (!serviceToken) {
throw new Error("Missing SERVICE_TOKEN");
}
console.log("Environment loaded");
- •Next, create an authenticated tool function. This is the part your AutoGen agent will call, and it attaches the bearer token in the request header.
import axios from "axios";
export async function getCustomerProfile(customerId: string): Promise<string> {
const serviceToken = process.env.SERVICE_TOKEN;
if (!serviceToken) throw new Error("Missing SERVICE_TOKEN");
const response = await axios.get(
`https://api.example.com/customers/${customerId}`,
{
headers: {
Authorization: `Bearer ${serviceToken}`,
"Content-Type": "application/json",
},
}
);
return JSON.stringify(response.data);
}
- •Now wire that tool into an AutoGen assistant agent. The agent can decide when to call the tool, but the auth logic stays inside the tool where it belongs.
import { AssistantAgent } from "@autogenai/autogen";
import { getCustomerProfile } from "./getCustomerProfile";
const assistant = new AssistantAgent({
name: "support_agent",
modelClient: {
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
},
systemMessage:
"You are a support agent. Use the customer profile tool when asked about customer data.",
tools: [
{
name: "get_customer_profile",
description: "Fetch a customer profile by ID",
parameters: {
type: "object",
properties: {
customerId: { type: "string" },
},
required: ["customerId"],
},
execute: async ({ customerId }: { customerId: string }) =>
getCustomerProfile(customerId),
},
],
});
- •Add a small runner so you can send a prompt and see the authenticated tool in action. This keeps the example practical and easy to test locally.
import { UserProxyAgent } from "@autogenai/autogen";
const user = new UserProxyAgent({ name: "user" });
async function main() {
const result = await assistant.run(
[
{
role: "user",
content: "Get the profile for customer ID 12345.",
},
],
{ maxTurns: 2 }
);
console.log(result);
}
main().catch(console.error);
- •If your API uses short-lived tokens, refresh them before each request instead of hardcoding one value at startup. In production, this usually means pulling from a vault or calling an auth service before executing the tool.
import axios from "axios";
async function fetchServiceToken(): Promise<string> {
const response = await axios.post("https://auth.example.com/token", {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
audience: "customer-api",
});
return response.data.access_token as string;
}
export async function getSecureData(resourceId: string): Promise<string> {
const token = await fetchServiceToken();
const response = await axios.get(`https://api.example.com/resources/${resourceId}`, {
headers: { Authorization: `Bearer ${token}` },
});
return JSON.stringify(response.data);
}
Testing It
Run the script with valid environment variables set and confirm that the tool returns data instead of a 401 Unauthorized error. If you want to verify the auth header is being sent, point the tool at a mock server like WireMock or httpbin and inspect incoming headers.
A good local check is to temporarily use an invalid token and confirm the request fails cleanly. Then restore the correct token and make sure the agent can complete its turn without manual intervention.
If you are using short-lived tokens, test token expiry by waiting for expiration and running another request. Your refresh flow should recover without changing any agent code.
Next Steps
- •Add role-based access control so different tools use different credentials
- •Move secrets into AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault
- •Wrap authenticated tools with retry logic for
401and token refresh failures
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
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