{"record":{"id":"3a388c07100e0527","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-3a388c","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.SemanticKernel.Sample/Create_Semantic_Kernel_Agent.cs","lineNumber":14,"sourceCode":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Create_Semantic_Kernel_Agent.cs\n\nusing AutoGen.Core;\nusing AutoGen.SemanticKernel.Extension;\nusing Microsoft.SemanticKernel;\n\nnamespace AutoGen.SemanticKernel.Sample;\n\npublic class Create_Semantic_Kernel_Agent\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-3.5-turbo\";\n        var kernel = Kernel.CreateBuilder()\n            .AddOpenAIChatCompletion(modelId: modelId, apiKey: openAIKey)\n            .Build();\n\n        var skAgent = new SemanticKernelAgent(\n            kernel: kernel,\n            name: \"assistant\",\n            systemMessage: \"You are a helpful AI assistant\")\n            .RegisterMessageConnector() // register message connector so it support AutoGen built-in message types like TextMessage.\n            .RegisterPrintMessage(); // pretty print the message to the console\n\n        await skAgent.SendAsync(\"Hey tell me a long tedious joke\");\n    }\n}\n","sourceCodeStart":1,"sourceCodeEnd":30,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.SemanticKernel.Sample/Create_Semantic_Kernel_Agent.cs#L1-L30","documentation":"Thrown by the SemanticKernel sample 'Create_Semantic_Kernel_Agent' when OPENAI_API_KEY is not present in the environment. The key is required because the sample builds a Kernel with AddOpenAIChatCompletion(modelId, apiKey) directly against the public OpenAI endpoint. Failing here prevents a confusing 401 from the OpenAI API later.","triggerScenarios":"Invoking Create_Semantic_Kernel_Agent.RunAsync() without OPENAI_API_KEY defined in the process environment; the Kernel.CreateBuilder().AddOpenAIChatCompletion(...) call needs it immediately.","commonSituations":"Developer cloned AutoGen and ran samples before configuring keys; key stored only in appsettings/user-secrets but sample reads only the environment; running in a container or CI agent without the secret injected.","solutions":["Export/set OPENAI_API_KEY in the shell that launches the sample: export OPENAI_API_KEY=sk-... (bash) / $env:OPENAI_API_KEY='sk-...' (PowerShell).","Persist via setx (Windows) or shell profile (macOS/Linux) and restart the terminal/IDE.","Add the variable to the sample project's launchSettings.json environmentVariables section when debugging from an IDE.","If you want Azure instead, replace AddOpenAIChatCompletion with AddAzureOpenAIChatCompletion and set the Azure-specific env vars."],"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 add it to launchSettings.json / user-secrets.\");","handlingStrategy":"validation","validationCode":"var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(openAIKey))\n{\n    Console.Error.WriteLine(\"Missing OPENAI_API_KEY. Set it and rerun (see sample README).\");\n    return;\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Centralize key loading in one helper shared by samples so the failure mode is identical everywhere.","Add a startup env-var assertion to the sample host (Program.cs) that lists all missing keys at once.","Use dotnet user-secrets for local dev instead of ambient env vars."],"tags":["semantic-kernel","openai","configuration","environment-variables","sample","csharp"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}