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 structured-output sample: it reads OPENAI_API_KEY and throws a plain Exception when missing, because OpenAIClient(apiKey) must authenticate the gpt-4o-mini client used with a JSON-schema structured output. Thrown by sample code before the JsonSchemaBuilder or the OpenAIChatAgent is constructed.

Source

Thrown at dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Structural_Output.cs:20

// Structural_Output.cs

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

namespace AutoGen.OpenAI.Sample;

public class Structural_Output
{
    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 schemaBuilder = new JsonSchemaBuilder().FromType<Person>();
        var schema = schemaBuilder.Build();
        var openAIClient = new OpenAIClient(apiKey);
        var openAIClientAgent = new OpenAIChatAgent(
            chatClient: openAIClient.GetChatClient(model),
            name: "assistant",
            systemMessage: "You are a helpful assistant")
            .RegisterMessageConnector()
            .RegisterPrintMessage();
        #endregion create_agent

        #region chat_with_agent
        var prompt = new TextMessage(Role.User, """
            My name is John, I am 25 years old, and I live in Seattle. I like to play soccer and read books.
            """);
        var reply = await openAIClientAgent.GenerateReplyAsync(

View on GitHub (pinned to 027ecf0a37)

Solutions

  1. Set OPENAI_API_KEY in the launching shell or IDE environment, then re-run.
  2. Verify the key can access gpt-4o-mini and JSON structured output features.
  3. Check for typos/whitespace in the variable value if you believe it's already set.
  4. Store the key in a secrets mechanism (user-secrets, CI secret variables) instead of source or command history.

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 before running Structural_Output.");
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 Structural_Output.");
    return;
}

Try / catch

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

Prevention

When it happens

Trigger: Calling Structural_Output.RunAsync() with OPENAI_API_KEY absent. Fails at startup; the schema build, agent creation, and the structured-output request never execute.

Common situations: Running the whole AutoGen.OpenAI.Sample project with missing credentials; CI without OpenAI secrets; key present only under Azure variable names.

Related errors


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