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 the use-tools getting-started sample: it reads OPENAI_API_KEY and throws a plain Exception when missing, because OpenAIClient(apiKey) must authenticate the gpt-4o-mini chat client used for both auto-invoke and no-invoke tool scenarios. Thrown by sample code before any agent or FunctionCallMiddleware executes.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Use_Tools_With_Agent.cs:52

        var tools = new Tools();
        #endregion Create_tools

        #region Create_auto_invoke_middleware
        var autoInvokeMiddleware = new FunctionCallMiddleware(
            functions: [tools.GetWeatherFunctionContract],
            functionMap: new Dictionary<string, Func<string, Task<string>>>()
            {
                { tools.GetWeatherFunctionContract.Name!, tools.GetWeatherWrapper },
            });
        #endregion Create_auto_invoke_middleware

        #region Create_no_invoke_middleware
        var noInvokeMiddleware = new FunctionCallMiddleware(
            functions: [tools.GetWeatherFunctionContract]);
        #endregion Create_no_invoke_middleware

        #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 agent = new OpenAIChatAgent(
            chatClient: openaiClient.GetChatClient(model),
            name: "agent",
            systemMessage: "You are a helpful AI assistant")
            .RegisterMessageConnector(); // convert OpenAI message to AutoGen message
        #endregion Create_Agent

        #region Single_Turn_Auto_Invoke
        var autoInvokeAgent = agent
            .RegisterMiddleware(autoInvokeMiddleware) // pass function definition to agent.
            .RegisterPrintMessage(); // print the message content
        var question = new TextMessage(Role.User, "What is the weather in Seattle?");
        var reply = await autoInvokeAgent.SendAsync(question);
        reply.Should().BeOfType<ToolCallAggregateMessage>();
        #endregion Single_Turn_Auto_Invoke

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Export OPENAI_API_KEY (bash: export OPENAI_API_KEY=sk-...; PowerShell: $env:OPENAI_API_KEY='sk-...') and re-run.
  2. Put the key in launchSettings.json or the IDE debug profile when launching from Visual Studio/Rider.
  3. Check the variable name and value (no whitespace) if you believe it is set.
  4. Ensure the key supports gpt-4o-mini tool calls for the auto-invoke scenario to work after startup.

Example fix

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

// after
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
    ?? throw new InvalidOperationException("OPENAI_API_KEY is not set; export it or add it to your IDE run configuration.");
Defensive patterns

Strategy: validation

Validate before calling

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

Try / catch

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

Prevention

When it happens

Trigger: Running the sample with OPENAI_API_KEY absent from the process environment. The exception occurs at the Create_Agent stage, before the Single_Turn_Auto_Invoke / No_Invoke demonstrations.

Common situations: First-run of the samples without credential setup; IDE sessions missing shell exports; CI pipelines without OpenAI secrets; the key configured only for Azure deployments.

Related errors


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