How to Fix 'invalid API key in production' in AutoGen (TypeScript)
When AutoGen throws invalid API key in production, it usually means the runtime that is actually executing your agent does not have the API key you think it has. In TypeScript projects, this often shows up only after deployment because local .env loading worked, but the production process never received OPENAI_API_KEY or the wrong client was initialized.
The key detail: this is almost always a configuration issue, not an AutoGen bug. The failure typically happens when AssistantAgent, OpenAIChatCompletionClient, or your model client is created before environment variables are loaded, or when the deployed environment uses a different variable name than your local machine.
The Most Common Cause
The #1 cause is initializing AutoGen with an API key from process.env before that variable exists in production.
This pattern breaks when:
- •
.envis loaded too late - •the deployment platform uses a different secret name
- •the code runs in a serverless edge/runtime that strips env access
- •you hardcode local-only config and assume it will work everywhere
Broken vs fixed
| Broken pattern | Fixed pattern |
|---|---|
| Reads env too early | Loads env before agent/client creation |
Assumes .env exists in prod | Uses platform secrets/config |
| No validation | Fails fast if key is missing |
// broken.ts
import { AssistantAgent } from "@autogen/agent";
import { OpenAIChatCompletionClient } from "@autogen/openai";
// process.env may be undefined here in production
const client = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY,
});
export const agent = new AssistantAgent({
name: "support-agent",
modelClient: client,
});
// fixed.ts
import "dotenv/config";
import { AssistantAgent } from "@autogen/agent";
import { OpenAIChatCompletionClient } from "@autogen/openai";
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("Missing OPENAI_API_KEY in production");
}
const client = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
apiKey,
});
export const agent = new AssistantAgent({
name: "support-agent",
modelClient: client,
});
If you are using a framework like Next.js, NestJS, or Express with a separate bootstrap file, make sure env loading happens before any module imports that create agents. Module-level initialization is where this usually goes wrong.
Other Possible Causes
1) Wrong environment variable name
A lot of teams set OPENAI_KEY, API_KEY, or AUTOGEN_API_KEY in production and forget AutoGen/OpenAI expects OPENAI_API_KEY.
// broken
process.env.OPENAI_KEY;
// fixed
process.env.OPENAI_API_KEY;
If you are using a secret manager, confirm the exact mapping:
OPENAI_API_KEY=sk-prod-...
2) You’re running in a serverless or edge runtime
Some runtimes do not behave like Node.js. If your deployment targets Edge Runtime, Cloudflare Workers, or a restricted serverless environment, process.env access and Node-only packages can fail or behave differently.
// bad for edge runtimes if your stack depends on Node APIs
export const runtime = "edge";
Use a Node runtime for AutoGen agents:
export const runtime = "nodejs";
If you must run in serverless, initialize the client inside the handler so it picks up runtime secrets correctly:
export async function POST(req: Request) {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) throw new Error("OPENAI_API_KEY missing");
// create client here, not at module scope
}
3) The key is present locally but not in CI/CD or hosting config
Your local .env file does not get deployed automatically. Vercel, Render, Fly.io, Azure App Service, GitHub Actions, and Docker all need explicit secret injection.
# example docker-compose.yml
services:
app:
environment:
OPENAI_API_KEY: ${OPENAI_API_KEY}
In CI/CD pipelines:
echo "$OPENAI_API_KEY" | wc -c
If that prints 0, your pipeline never received the secret.
4) You’re mixing up OpenAI SDK config with AutoGen config
AutoGen TypeScript wrappers still depend on the underlying model client. If you pass credentials to the wrong layer, you can get misleading auth errors.
// broken: passing config where the library doesn't read it
new AssistantAgent({
name: "agent",
modelClient: {
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4o-mini",
} as any,
});
Use the actual AutoGen/OpenAI client class expected by your version of AutoGen:
const client = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
apiKey: process.env.OPENAI_API_KEY!,
});
How to Debug It
- •Log whether the key exists at startup
- •Do not print the full key.
- •Print length or last 4 characters only.
console.log("OPENAI_API_KEY present:", !!process.env.OPENAI_API_KEY);
console.log(
"OPENAI_API_KEY suffix:",
process.env.OPENAI_API_KEY?.slice(-4)
);
- •
Confirm where the error is thrown
- •If it fails during import time, you are probably creating
AssistantAgentorOpenAIChatCompletionClientat module scope. - •Move initialization into a function or request handler.
- •If it fails during import time, you are probably creating
- •
Check deployment secrets directly
- •Verify the secret exists in your cloud console.
- •Verify it is attached to the correct service/environment.
- •Verify staging and production do not use different names.
- •
Reproduce with a minimal script
- •Strip everything down to one file.
- •Create only one client and one agent.
- •If that works locally but fails in prod, the problem is environment injection.
import "dotenv/config";
import { OpenAIChatCompletionClient } from "@autogen/openai";
async function main() {
const apiKey = process.env.OPENAI_API_KEY;
console.log("key?", !!apiKey);
const client = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
apiKey,
});
console.log(await client.create([{ role: "user", content: "ping" }]));
}
main();
Prevention
- •Validate required env vars at startup with a hard failure:
if (!process.env.OPENAI_API_KEY) {
throw new Error("Missing OPENAI_API_KEY");
}
- •Avoid module-level agent/client creation unless your env loading order is guaranteed.
- •Keep one canonical secret name across local dev, CI/CD, and production:
OPENAI_API_KEY.
If you see invalid API key in production from AutoGen TypeScript, treat it as an environment wiring problem first. In most cases, fixing secret injection and initialization order resolves it without touching your agent logic.
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