microsoft/autogen · error · Exception

Please set OPENAI_API_KEY environment variable.

Error message

Please set OPENAI_API_KEY environment variable.

What it means

This exception is thrown by the AutoGen OpenAI sample 'Use_Json_Mode' when the OPENAI_API_KEY environment variable is null. The sample deliberately fails fast instead of passing an empty key to the OpenAI SDK, because the OpenAIClient would otherwise fail later with a less clear auth error. It is a sample-app guard, not library logic.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Use_Json_Mode.cs:19

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

using System.Text.Json;
using System.Text.Json.Serialization;
using AutoGen.Core;
using AutoGen.OpenAI.Extension;
using FluentAssertions;
using OpenAI;
using OpenAI.Chat;

namespace AutoGen.OpenAI.Sample;

public class Use_Json_Mode
{
    public static async Task RunAsync()
    {
        #region create_agent
        var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
        var model = "gpt-4o-mini";

        var openAIClient = new OpenAIClient(apiKey);
        var openAIClientAgent = new OpenAIChatAgent(
            chatClient: openAIClient.GetChatClient(model),
            name: "assistant",
            systemMessage: "You are a helpful assistant designed to output JSON.",
            seed: 0, // explicitly set a seed to enable deterministic output
            responseFormat: ChatResponseFormat.CreateJsonObjectFormat()) // set response format to JSON object to enable JSON mode
            .RegisterMessageConnector()
            .RegisterPrintMessage();
        #endregion create_agent

        #region chat_with_agent
        var reply = await openAIClientAgent.SendAsync("My name is John, I am 25 years old, and I live in Seattle.");

        var person = JsonSerializer.Deserialize<Person>(reply.GetContent());
        Console.WriteLine($"Name: {person.Name}");

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Set the variable for the current session: export OPENAI_API_KEY=sk-... (bash) or $env:OPENAI_API_KEY='sk-...' (PowerShell), then rerun the sample.
  2. Or persist it: setx OPENAI_API_KEY sk-... (Windows) / add to ~/.bashrc or ~/.zshrc (Linux/macOS), then open a new terminal.
  3. Or, when running from Visual Studio / Rider, put it in dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Properties/launchSettings.json under environmentVariables.
  4. Never hardcode the key in the sample source; use dotnet user-secrets for shared machines.

Example fix

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

// after (fail fast with actionable hint, no code change required if env var is set in launchSettings.json)
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("Set OPENAI_API_KEY (e.g. `export OPENAI_API_KEY=sk-...`) before running this sample.");
Defensive patterns

Strategy: validation

Validate before calling

if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_API_KEY")))
{
    Console.Error.WriteLine("OPENAI_API_KEY is not set. Export it (bash: export OPENAI_API_KEY=sk-...) and rerun.");
    return; // or Environment.Exit(1)
}

Prevention

When it happens

Trigger: Running the AutoGen.OpenAI.Sample Use_Json_Mode.RunAsync() (e.g. 'dotnet run' on the sample project) in a shell/process where OPENAI_API_KEY is unset, null, or only set in a different user session.

Common situations: New clone of the AutoGen repo without reading the sample README; env var set in PowerShell but sample run from VS/WSL where it does not propagate; CI pipeline without seeded secrets; using 'set' (cmd, session-only) instead of 'setx' or launchSettings.json.

Related errors


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