Setting API key in the Agent SDK (TS)

I’m using the Agent SDK (TypeScript library) and would like to set the OPENAI_KEY. I can’t find a way to pass it to my instance of the Agent. The only documented methods are to set the environment variable or call the system-wide “setDefaultOpenAIKey”. Neither of these options works for me because I need to set the key on a function basis.

Do you have any suggestions on how I can pass the key, similar to how the OpenAI class allows instantiation by passing the “apiKey” parameter?

1 Like

If anyone are still using this forum then the solution is this:

import { Agent, run, OpenAIResponsesModel } from '@openai/agents';
import { OpenAI } from 'openai';

const agent1 = new Agent({
  name: 'Agent 1',
  instructions: 'You are a helpful agent',
  model: new OpenAIResponsesModel(new OpenAI({
    // API key 1
    apiKey: process.env.OPENAI_API_KEY_1!,
  }), 'gpt-5-mini'),
});

Found in the Set different APIKeys for different `run` · Issue #623 · openai/openai-agents-js · GitHub thread

1 Like