{"record":{"id":"f84b70b714b3bb14","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-f84b70","errorCode":null,"errorMessage":"Please set OPENAI_API_KEY environment variable.","messagePattern":"Please set OPENAI_API_KEY environment variable\\.","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Dynamic_Group_Chat.cs","lineNumber":18,"sourceCode":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Dynamic_Group_Chat.cs\n\nusing AutoGen.Core;\nusing AutoGen.OpenAI;\nusing AutoGen.OpenAI.Extension;\nusing AutoGen.SemanticKernel;\nusing AutoGen.SemanticKernel.Extension;\nusing Microsoft.SemanticKernel;\nusing OpenAI;\n\nnamespace AutoGen.Basic.Sample;\n\npublic class Dynamic_Group_Chat\n{\n    public static async Task RunAsync()\n    {\n        var apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n        var model = \"gpt-4o-mini\";\n\n        #region Create_Coder\n        var openaiClient = new OpenAIClient(apiKey);\n        var coder = new OpenAIChatAgent(\n            chatClient: openaiClient.GetChatClient(model),\n            name: \"coder\",\n            systemMessage: \"You are a C# coder, when writing csharp code, please put the code between ```csharp and ```\")\n            .RegisterMessageConnector() // convert OpenAI message to AutoGen message\n            .RegisterPrintMessage(); // print the message content\n        #endregion Create_Coder\n\n        #region Create_Commenter\n        var kernel = Kernel\n            .CreateBuilder()\n            .AddOpenAIChatCompletion(modelId: model, apiKey: apiKey)\n            .Build();\n        var commenter = new SemanticKernelAgent(","sourceCodeStart":1,"sourceCodeEnd":36,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Dynamic_Group_Chat.cs#L1-L36","documentation":"Startup guard in the Dynamic Group Chat getting-started sample: RunAsync reads OPENAI_API_KEY and throws a plain Exception when absent, because OpenAIClient(apiKey) cannot be constructed for the coder/other chat agents without it. The throw is sample-authored and fires before any agent or group-chat scaffolding is built.","triggerScenarios":"Invoking Dynamic_Group_Chat.RunAsync() with OPENAI_API_KEY unset or empty in the launching process. It fails at the first line, before the coder OpenAIChatAgent is created.","commonSituations":"New users following the getting-started docs but skipping the API-key setup step; running samples in CI without OpenAI secrets; the variable set in a parent shell but the sample launched from a fresh terminal or IDE.","solutions":["Set OPENAI_API_KEY (export on bash, $env:/setx on Windows) in the environment that launches the sample.","Add the key to your IDE's debug environment profile if you run the sample from Visual Studio/Rider.","Verify the process actually sees the variable (quick console print) — dotnet does not load .env automatically.","Ensure the key has gpt-4o-mini access, since the sample hard-codes that model."],"exampleFix":"// before\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n\n// after\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n    ?? throw new InvalidOperationException(\"OPENAI_API_KEY is not set. Export it before running Dynamic_Group_Chat.\");","handlingStrategy":"validation","validationCode":"var apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(apiKey))\n{\n    Console.Error.WriteLine(\"Set OPENAI_API_KEY before running Dynamic_Group_Chat.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Dynamic_Group_Chat.RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Configuration error: {ex.Message}\");\n}","preventionTips":["Follow the getting-started setup step that exports the API key before running samples.","Set keys in the IDE profile when launching from Visual Studio/Rider so they survive across sessions.","dotnet run does not read .env files — export variables explicitly or load them in code."],"tags":["configuration","environment-variables","openai","group-chat","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}