microsoft/autogen · error · Exception

Please set OPENAI_API_KEY environment variable.

Error message

Please set OPENAI_API_KEY environment variable.

What it means

Fail-fast guard in the DALL-E + GPT-4V sample: before constructing OpenAIClient, the sample reads OPENAI_API_KEY and throws a plain Exception if it is missing, because every OpenAI API call (image generation with DALL-E and GPT-4V vision feedback) needs that key. The throw comes from the sample's RunAsync, not from AutoGen or the OpenAI .NET SDK.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example05_Dalle_And_GPT4V.cs:55

        var imageResponse = await openAIClient.GetImageClient("dall-e-3").GenerateImageAsync(prompt, option);
        var imageUrl = imageResponse.Value.ImageUri.OriginalString;

        return $@"// ignore this line [IMAGE_GENERATION]
The image is generated from prompt {prompt}

{imageUrl}";
    }

    public static async Task RunAsync()
    {
        // This example shows how to use DALL-E and GPT-4V to generate image from prompt and feedback.
        // The DALL-E agent will generate image from prompt.
        // The GPT-4V agent will provide feedback to DALL-E agent to help it generate better image.
        // The conversation will be terminated when the image satisfies the condition.
        // The image will be saved to image.jpg in current directory.

        // get OpenAI Key and create config
        var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
        var openAIClient = new OpenAIClient(openAIKey);
        var instance = new Example05_Dalle_And_GPT4V(openAIClient);
        var imagePath = Path.Combine("resource", "images", "background.png");
        if (File.Exists(imagePath))
        {
            File.Delete(imagePath);
        }

        var generateImageFunctionMiddleware = new FunctionCallMiddleware(
            functions: [instance.GenerateImageFunctionContract],
            functionMap: new Dictionary<string, Func<string, Task<string>>>
            {
                { nameof(GenerateImage), instance.GenerateImageWrapper },
            });
        var dalleAgent = new OpenAIChatAgent(
            chatClient: openAIClient.GetChatClient("gpt-4o-mini"),
            name: "dalle",
            systemMessage: "You are a DALL-E agent that generate image from prompt, when conversation is terminated, return the most recent image url")

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Export the key in the launching shell: export OPENAI_API_KEY=sk-... (or setx / $env: on Windows), then re-run RunAsync.
  2. Configure the key in the IDE's run profile (launchSettings.json environmentVariables) if you start the sample from Visual Studio/Rider.
  3. Confirm the variable reaches the process (dotnet does not read .env files automatically — load it explicitly or set it in the environment).
  4. Note this example also incurs image-generation costs; verify the key has DALL-E access before running.

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 your run configuration before running this sample.");
Defensive patterns

Strategy: validation

Validate before calling

var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(openAIKey))
{
    Console.Error.WriteLine("OPENAI_API_KEY is required for the DALL-E + GPT-4V sample.");
    return;
}

Try / catch

try
{
    await Example05_Dalle_And_GPT4V.RunAsync();
}
catch (Exception ex) when (ex.Message.Contains("OPENAI_API_KEY"))
{
    Console.Error.WriteLine($"Missing credential: {ex.Message}");
}

Prevention

When it happens

Trigger: Invoking Example05_Dalle_And_GPT4V.RunAsync() in a process where OPENAI_API_KEY is unset/empty. The throw happens immediately at startup, before any image generation or GPT-4V call is attempted.

Common situations: Running the sample suite (many AutoGen.Basic.Sample examples) with only some API keys configured; CI runs without OpenAI secrets; launching from an IDE whose process does not inherit the shell-exported variable; key stored only in a .env file that the sample does not load.

Related errors


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