microsoft/autogen · error · Exception

Please set OPENAI_API_KEY environment variable.

Error message

Please set OPENAI_API_KEY environment variable.

What it means

Startup guard in Example10_SemanticKernel.RunAsync: the sample reads OPENAI_API_KEY and throws a plain Exception when it is missing, because Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId, apiKey) cannot authenticate without it. The exception is thrown by the sample before the kernel or the SemanticKernelAgent is built; AutoGen and Semantic Kernel never see the missing key.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example10_SemanticKernel.cs:41

    public string ChangeState(bool newState)
    {
        this.IsOn = newState;
        var state = this.GetState();

        // Print the state to the console
        Console.ForegroundColor = ConsoleColor.DarkBlue;
        Console.WriteLine($"[Light is now {state}]");
        Console.ResetColor();

        return state;
    }
}

public class Example10_SemanticKernel
{
    public static async Task RunAsync()
    {
        var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
        var modelId = "gpt-4o-mini";
        var builder = Kernel.CreateBuilder()
            .AddOpenAIChatCompletion(modelId: modelId, apiKey: openAIKey);
        var kernel = builder.Build();
        var settings = new OpenAIPromptExecutionSettings
        {
            ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,
        };

        kernel.Plugins.AddFromObject(new LightPlugin());
        var skAgent = kernel
            .ToSemanticKernelAgent(name: "assistant", systemMessage: "You control the light", settings: settings);

        // Send a message to the skAgent, the skAgent supports the following message types:
        // - IMessage<ChatMessageContent>
        // - (streaming) IMessage<StreamingChatMessageContent>
        // You can create an IMessage<ChatMessageContent> using MessageEnvelope.Create
        var chatMessageContent = MessageEnvelope.Create(new ChatMessageContent(AuthorRole.User, "Toggle the light"));

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Set OPENAI_API_KEY in the environment that launches the sample (export on bash/macOS, setx or $env: on Windows), then re-run.
  2. Add the variable to launchSettings.json / IDE debug environment when running from Visual Studio or Rider.
  3. Double-check you are not pointing this sample at Azure — it uses the public OpenAI endpoint; Azure samples need AZURE_* variables instead.
  4. Confirm the key is valid and has quota for gpt-4o-mini to avoid trading this error for a 401/429 next.

Example fix

// before
var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");

// after
var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not set; export it or configure it in your IDE run profile.");
Defensive patterns

Strategy: validation

Validate before calling

var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(openAIKey))
{
    Console.Error.WriteLine("Set OPENAI_API_KEY before running Example10_SemanticKernel.");
    return;
}

Try / catch

try
{
    await Example10_SemanticKernel.RunAsync();
}
catch (Exception ex) when (ex.Message.Contains("OPENAI_API_KEY"))
{
    Console.Error.WriteLine($"Configuration error: {ex.Message}");
}

Prevention

When it happens

Trigger: Calling Example10_SemanticKernel.RunAsync() when OPENAI_API_KEY is unset in the process environment. Fails immediately, before LightPlugin is registered or any chat/streaming call happens.

Common situations: Running the sample from a fresh shell or IDE session without exporting the key; CI pipelines that don't inject OpenAI secrets; the key being set under a different name (e.g. AZURE_OPENAI_API_KEY) when the sample expects the public OpenAI endpoint.

Related errors


AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15). Data as JSON: /api/errors/5d8142018ad342b6. Report an issue: GitHub.