{"record":{"id":"5d8142018ad342b6","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-5d8142","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/Example10_SemanticKernel.cs","lineNumber":41,"sourceCode":"    public string ChangeState(bool newState)\n    {\n        this.IsOn = newState;\n        var state = this.GetState();\n\n        // Print the state to the console\n        Console.ForegroundColor = ConsoleColor.DarkBlue;\n        Console.WriteLine($\"[Light is now {state}]\");\n        Console.ResetColor();\n\n        return state;\n    }\n}\n\npublic class Example10_SemanticKernel\n{\n    public static async Task RunAsync()\n    {\n        var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n        var modelId = \"gpt-4o-mini\";\n        var builder = Kernel.CreateBuilder()\n            .AddOpenAIChatCompletion(modelId: modelId, apiKey: openAIKey);\n        var kernel = builder.Build();\n        var settings = new OpenAIPromptExecutionSettings\n        {\n            ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions,\n        };\n\n        kernel.Plugins.AddFromObject(new LightPlugin());\n        var skAgent = kernel\n            .ToSemanticKernelAgent(name: \"assistant\", systemMessage: \"You control the light\", settings: settings);\n\n        // Send a message to the skAgent, the skAgent supports the following message types:\n        // - IMessage<ChatMessageContent>\n        // - (streaming) IMessage<StreamingChatMessageContent>\n        // You can create an IMessage<ChatMessageContent> using MessageEnvelope.Create\n        var chatMessageContent = MessageEnvelope.Create(new ChatMessageContent(AuthorRole.User, \"Toggle the light\"));","sourceCodeStart":23,"sourceCodeEnd":59,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example10_SemanticKernel.cs#L23-L59","documentation":"Startup guard in Example10_SemanticKernel.RunAsync: the sample reads OPENAI_API_KEY and throws a plain Exception when it is missing, because Kernel.CreateBuilder().AddOpenAIChatCompletion(modelId, apiKey) cannot authenticate without it. The exception is thrown by the sample before the kernel or the SemanticKernelAgent is built; AutoGen and Semantic Kernel never see the missing key.","triggerScenarios":"Calling Example10_SemanticKernel.RunAsync() when OPENAI_API_KEY is unset in the process environment. Fails immediately, before LightPlugin is registered or any chat/streaming call happens.","commonSituations":"Running the sample from a fresh shell or IDE session without exporting the key; CI pipelines that don't inject OpenAI secrets; the key being set under a different name (e.g. AZURE_OPENAI_API_KEY) when the sample expects the public OpenAI endpoint.","solutions":["Set OPENAI_API_KEY in the environment that launches the sample (export on bash/macOS, setx or $env: on Windows), then re-run.","Add the variable to launchSettings.json / IDE debug environment when running from Visual Studio or Rider.","Double-check you are not pointing this sample at Azure — it uses the public OpenAI endpoint; Azure samples need AZURE_* variables instead.","Confirm the key is valid and has quota for gpt-4o-mini to avoid trading this error for a 401/429 next."],"exampleFix":"// before\nvar openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n\n// after\nvar openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n    ?? throw new InvalidOperationException(\"OPENAI_API_KEY is not set; export it or configure it in your IDE run profile.\");","handlingStrategy":"validation","validationCode":"var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(openAIKey))\n{\n    Console.Error.WriteLine(\"Set OPENAI_API_KEY before running Example10_SemanticKernel.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Example10_SemanticKernel.RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Configuration error: {ex.Message}\");\n}","preventionTips":["Keep a single env-validation step at app startup covering every key the entry point needs.","Use IDE run profiles or user-secrets for keys rather than relying on shell state.","Distinguish public-OpenAI samples (OPENAI_API_KEY) from Azure samples (AZURE_*) when configuring."],"tags":["configuration","environment-variables","openai","semantic-kernel","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}