microsoft/autogen · error · Exception

Please set OPENAI_API_KEY environment variable.

Error message

Please set OPENAI_API_KEY environment variable.

What it means

Thrown by the SemanticKernel sample 'Create_Semantic_Kernel_Agent' when OPENAI_API_KEY is not present in the environment. The key is required because the sample builds a Kernel with AddOpenAIChatCompletion(modelId, apiKey) directly against the public OpenAI endpoint. Failing here prevents a confusing 401 from the OpenAI API later.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.SemanticKernel.Sample/Create_Semantic_Kernel_Agent.cs:14

// Copyright (c) Microsoft Corporation. All rights reserved.
// Create_Semantic_Kernel_Agent.cs

using AutoGen.Core;
using AutoGen.SemanticKernel.Extension;
using Microsoft.SemanticKernel;

namespace AutoGen.SemanticKernel.Sample;

public class Create_Semantic_Kernel_Agent
{
    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-3.5-turbo";
        var kernel = Kernel.CreateBuilder()
            .AddOpenAIChatCompletion(modelId: modelId, apiKey: openAIKey)
            .Build();

        var skAgent = new SemanticKernelAgent(
            kernel: kernel,
            name: "assistant",
            systemMessage: "You are a helpful AI assistant")
            .RegisterMessageConnector() // register message connector so it support AutoGen built-in message types like TextMessage.
            .RegisterPrintMessage(); // pretty print the message to the console

        await skAgent.SendAsync("Hey tell me a long tedious joke");
    }
}

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Export/set OPENAI_API_KEY in the shell that launches the sample: export OPENAI_API_KEY=sk-... (bash) / $env:OPENAI_API_KEY='sk-...' (PowerShell).
  2. Persist via setx (Windows) or shell profile (macOS/Linux) and restart the terminal/IDE.
  3. Add the variable to the sample project's launchSettings.json environmentVariables section when debugging from an IDE.
  4. If you want Azure instead, replace AddOpenAIChatCompletion with AddAzureOpenAIChatCompletion and set the Azure-specific env vars.

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 add it to launchSettings.json / user-secrets.");
Defensive patterns

Strategy: validation

Validate before calling

var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(openAIKey))
{
    Console.Error.WriteLine("Missing OPENAI_API_KEY. Set it and rerun (see sample README).");
    return;
}

Prevention

When it happens

Trigger: Invoking Create_Semantic_Kernel_Agent.RunAsync() without OPENAI_API_KEY defined in the process environment; the Kernel.CreateBuilder().AddOpenAIChatCompletion(...) call needs it immediately.

Common situations: Developer cloned AutoGen and ran samples before configuring keys; key stored only in appsettings/user-secrets but sample reads only the environment; running in a container or CI agent without the secret injected.

Related errors


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