microsoft/semantic-kernel · error · InvalidOperationException
OPENAI_API_KEY is not set.
Error message
OPENAI_API_KEY is not set.
What it means
The OpenAI DependencyInjection migration sample throws InvalidOperationException when OPENAI_API_KEY is null. This sample shows DI-based agent registration against the direct OpenAI API, comparing SK's Kernel-dependent ChatCompletionAgent with AF's keyed-singleton AIAgent. The key is needed at composition time to build the chat client registered in the container.
Source
Thrown at dotnet/samples/AgentFrameworkMigration/OpenAI/Step03_DependencyInjection/Program.cs:10
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.Agents.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
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();
async Task SKAgentAsync()
{
Console.WriteLine("\n=== SK Agent ===\n");
var serviceCollection = new ServiceCollection();
serviceCollection.AddKernel().AddOpenAIChatClient(model, apiKey);
serviceCollection.AddTransient((sp) => new ChatCompletionAgent()
{
Kernel = sp.GetRequiredService<Kernel>(),View on GitHub (pinned to c028a0c7dc)
Solutions
- Set OPENAI_API_KEY to your OpenAI API key
- Optionally set OPENAI_MODEL (defaults to gpt-4o)
- If using VS, add the variable to Properties/launchSettings.json
- Consider using .NET user secrets for local dev: dotnet user-secrets set OPENAI_API_KEY 'sk-...'
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. See README.md Environment Variables section."); 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. Required for DI samples.");
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);
return;
} Prevention
- DI samples read env vars directly — use user secrets (dotnet user-secrets) or launchSettings.json
- Do not assume IConfiguration or appsettings.json provides the key
- Validate the key at the top of Program.cs before building the DI container
- Never commit API keys to source control — use .gitignore for .env files
When it happens
Trigger: Running OpenAI/Step03_DependencyInjection without OPENAI_API_KEY. The throw at line 10 fires before any ServiceCollection is built or agents registered.
Common situations: DI samples read env vars directly rather than user secrets or IConfiguration; the key is in a .env file that the console host doesn't auto-load; running from VS without the env var in launchSettings.json.
Related errors
- AZURE_OPENAI_ENDPOINT is not set.
- AZURE_OPENAI_ENDPOINT is not set.
- OPENAI_API_KEY is not set.
- OPENAI_API_KEY is not set.
- OPENAI_API_KEY is not set.
AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13).
Data as JSON: /api/errors/bd2d1daa6e7caee1.
Report an issue: GitHub.