microsoft/autogen · error · Exception

Please set OPENAI_API_KEY environment variable.

Error message

Please set OPENAI_API_KEY environment variable.

What it means

Guard in the AssistantAgent code snippet: OPENAI_API_KEY is null, so it throws before creating OpenAIConfig. It exists so the documented snippet (used in docs via #region extraction) fails with an actionable message rather than an opaque OpenAI auth 401 later.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/CodeSnippet/CreateAnAgent.cs:17

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

using AutoGen;
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
using FluentAssertions;
using OpenAI;

public partial class AssistantCodeSnippet
{
    public void CodeSnippet1()
    {
        #region code_snippet_1
        // get OpenAI Key and create config
        var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
        var llmConfig = new OpenAIConfig(openAIKey, "gpt-3.5-turbo");

        // create assistant agent
        var assistantAgent = new AssistantAgent(
            name: "assistant",
            systemMessage: "You are an assistant that help user to do some tasks.",
            llmConfig: new ConversableAgentConfig
            {
                Temperature = 0,
                ConfigList = new[] { llmConfig },
            });
        #endregion code_snippet_1

    }

    public void CodeSnippet2()
    {
        #region code_snippet_2

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Set OPENAI_API_KEY in the shell/CI environment before running samples or tests.
  2. Skip live-key snippet tests locally if the repo marks them as requiring credentials.
  3. Use a .env loader (e.g. DotNetEnv.Env.Load()) at sample startup.
  4. For docs builds, ensure the pipeline secret is mapped to the environment variable name.
Defensive patterns

Strategy: validation

Validate before calling

var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(openAIKey))
{
    Console.Error.WriteLine("Please set OPENAI_API_KEY environment variable.");
    return;
}

Prevention

When it happens

Trigger: Invoking AssistantCodeSnippet.CodeSnippet1 (often via the test suite or a doc build that executes snippets) without OPENAI_API_KEY.

Common situations: Running the AutoGen.Basic.Sample tests on a machine without the key; doc-generation pipelines that execute snippets; new contributors running samples before configuring secrets.

Related errors


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