microsoft/semantic-kernel · error · InvalidOperationException

OPENAI_API_KEY is not set.

Error message

OPENAI_API_KEY is not set.

What it means

The OpenAI Basics migration sample throws InvalidOperationException when OPENAI_API_KEY is null. This sample targets the direct OpenAI API (not Azure), comparing SK's ChatCompletionAgent with the Agent Framework's AIAgent. The API key constructs an OpenAIClient used to build the chat client. No Azure credentials or endpoints are needed.

Source

Thrown at dotnet/samples/AgentFrameworkMigration/OpenAI/Step01_Basics/Program.cs:10

// Copyright (c) Microsoft. All rights reserved.

using Microsoft.Agents.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using OpenAI;
using OpenAI.Chat;

var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
var model = System.Environment.GetEnvironmentVariable("OPENAI_MODEL") ?? "gpt-4o";
var userInput = "Tell me a joke about a pirate.";

Console.WriteLine($"User Input: {userInput}");

await SKAgentAsync();
await SKAgent_As_AFAgentAsync();
await AFAgentAsync();

// Example of Semantic Kernel Agent code
async Task SKAgentAsync()
{
    Console.WriteLine("\n=== SK Agent ===\n");

    var builder = Kernel.CreateBuilder().AddOpenAIChatClient(model, apiKey);

    var agent = new ChatCompletionAgent()
    {

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Set OPENAI_API_KEY to your OpenAI API key (starts with sk-)
  2. Optionally set OPENAI_MODEL (defaults to gpt-4o)
  3. On Windows: $env:OPENAI_API_KEY = 'sk-...'; on bash/macOS: export OPENAI_API_KEY='sk-...'
  4. Verify the key is valid at platform.openai.com/api-keys

Example fix

// before
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");

// after
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
    throw new InvalidOperationException(
        "OPENAI_API_KEY is not set. Get a key at https://platform.openai.com/api-keys");
Defensive patterns

Strategy: validation

Validate before calling

var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
    Console.Error.WriteLine("OPENAI_API_KEY is not set.");
    Console.Error.WriteLine("Get a key at https://platform.openai.com/api-keys");
    return;
}

Type guard

static bool IsOpenAIKeyConfigured() =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));

Try / catch

try
{
    var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
        ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
}
catch (InvalidOperationException ex) when (ex.Message.Contains("OPENAI_API_KEY"))
{
    Console.Error.WriteLine(ex.Message);
    Console.Error.WriteLine("Get a key at https://platform.openai.com/api-keys");
    return;
}

Prevention

When it happens

Trigger: Running OpenAI/Step01_Basics without OPENAI_API_KEY in the environment. The throw at line 10 fires before SKAgentAsync, SKAgent_As_AFAgentAsync, or AFAgentAsync execute.

Common situations: Running OpenAI samples with Azure env vars set instead (wrong variable); the API key expired or was rotated; using an organization-scoped key without the org header; OPENAI_API_KEY set in .env but not loaded by the console host.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/6fdef284c9fbb71c. Report an issue: GitHub.