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 ReAct agent sample: it reads OPENAI_API_KEY and throws when missing, because OpenAIClient(openAIKey) requires the key to call gpt-4-turbo for reasoning, tool use, and execution. Thrown by sample code at the top of RunAsync, before OpenAIReActAgent or any tool middleware is created.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example17_ReActAgent.cs:162

    {
        return $"Paris";
    }

    /// <summary>
    /// Get current date as DD/MM/YYYY
    /// </summary>
    [Function]
    public async Task<string> GetDateToday(string dummy)
    {
        return $"27/05/2024";
    }
}

public class Example17_ReActAgent
{
    public static async Task RunAsync()
    {
        var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
        var modelName = "gpt-4-turbo";
        var tools = new Tools();
        var openAIClient = new OpenAIClient(openAIKey);
        var gpt4o = LLMConfiguration.GetOpenAIGPT4o_mini();
        var reactAgent = new OpenAIReActAgent(
            client: openAIClient.GetChatClient(modelName),
            name: "react-agent",
            tools: [tools.GetLocalizationFunctionContract, tools.GetDateTodayFunctionContract, tools.WeatherReportFunctionContract],
            toolExecutors: new Dictionary<string, Func<string, Task<string>>>
            {
                { tools.GetLocalizationFunctionContract.Name, tools.GetLocalizationWrapper },
                { tools.GetDateTodayFunctionContract.Name, tools.GetDateTodayWrapper },
                { tools.WeatherReportFunctionContract.Name, tools.WeatherReportWrapper },
            }
            )
            .RegisterPrintMessage();

        var message = new TextMessage(Role.User, "What is the weather here", from: "user");

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Export OPENAI_API_KEY in the shell/IDE that launches the sample, then re-run.
  2. Set it in launchSettings.json (environmentVariables) when debugging from Visual Studio/Rider so the sample process sees it.
  3. Sanity-check with a trivial curl or SDK call that the key is valid for gpt-4-turbo, since this sample uses a heavyweight model.
  4. Note the sample also uses LLMConfiguration.GetOpenAIGPT4o_mini() — the same OPENAI_API_KEY must be present for that call too.

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 (bash: export OPENAI_API_KEY=sk-...) and re-run.");
Defensive patterns

Strategy: validation

Validate before calling

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

Try / catch

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

Prevention

When it happens

Trigger: Calling Example17_ReActAgent.RunAsync() with OPENAI_API_KEY unset in the process. Fails immediately at OpenAIClient construction time — no ReAct loop, tool call, or streaming happens.

Common situations: Running the sample project's full example list with only non-OpenAI keys set; IDE sessions that don't inherit shell exports; expired or mistyped key set under the right name (that fails later at the API, not here).

Related errors


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