{"record":{"id":"bd2d1daa6e7caee1","repo":"microsoft/semantic-kernel","slug":"openai-api-key-is-not-set-bd2d1d","errorCode":null,"errorMessage":"OPENAI_API_KEY is not set.","messagePattern":"OPENAI_API_KEY is not set\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/samples/AgentFrameworkMigration/OpenAI/Step03_DependencyInjection/Program.cs","lineNumber":10,"sourceCode":"﻿// Copyright (c) Microsoft. All rights reserved.\n\nusing Microsoft.Agents.AI;\nusing Microsoft.Extensions.DependencyInjection;\nusing Microsoft.SemanticKernel;\nusing Microsoft.SemanticKernel.Agents;\nusing OpenAI;\nusing OpenAI.Chat;\n\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new InvalidOperationException(\"OPENAI_API_KEY is not set.\");\nvar model = System.Environment.GetEnvironmentVariable(\"OPENAI_MODEL\") ?? \"gpt-4o\";\nvar userInput = \"Tell me a joke about a pirate.\";\n\nConsole.WriteLine($\"User Input: {userInput}\");\n\nawait SKAgentAsync();\nawait SKAgent_As_AFAgentAsync();\nawait AFAgentAsync();\n\nasync Task SKAgentAsync()\n{\n    Console.WriteLine(\"\\n=== SK Agent ===\\n\");\n\n    var serviceCollection = new ServiceCollection();\n    serviceCollection.AddKernel().AddOpenAIChatClient(model, apiKey);\n    serviceCollection.AddTransient((sp) => new ChatCompletionAgent()\n    {\n        Kernel = sp.GetRequiredService<Kernel>(),","sourceCodeStart":1,"sourceCodeEnd":28,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/dotnet/samples/AgentFrameworkMigration/OpenAI/Step03_DependencyInjection/Program.cs#L1-L28","documentation":"The OpenAI DependencyInjection migration sample throws InvalidOperationException when OPENAI_API_KEY is null. This sample shows DI-based agent registration against the direct OpenAI API, comparing SK's Kernel-dependent ChatCompletionAgent with AF's keyed-singleton AIAgent. The key is needed at composition time to build the chat client registered in the container.","triggerScenarios":"Running OpenAI/Step03_DependencyInjection without OPENAI_API_KEY. The throw at line 10 fires before any ServiceCollection is built or agents registered.","commonSituations":"DI samples read env vars directly rather than user secrets or IConfiguration; the key is in a .env file that the console host doesn't auto-load; running from VS without the env var in launchSettings.json.","solutions":["Set OPENAI_API_KEY to your OpenAI API key","Optionally set OPENAI_MODEL (defaults to gpt-4o)","If using VS, add the variable to Properties/launchSettings.json","Consider using .NET user secrets for local dev: dotnet user-secrets set OPENAI_API_KEY 'sk-...'"],"exampleFix":"// before\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new InvalidOperationException(\"OPENAI_API_KEY is not set.\");\n\n// after\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(apiKey))\n    throw new InvalidOperationException(\n        \"OPENAI_API_KEY is not set. See README.md Environment Variables section.\");","handlingStrategy":"validation","validationCode":"var apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(apiKey))\n{\n    Console.Error.WriteLine(\"OPENAI_API_KEY is not set. Required for DI samples.\");\n    return;\n}","typeGuard":"static bool IsOpenAIKeyConfigured() =>\n    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\"));","tryCatchPattern":"try\n{\n    var apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n        ?? throw new InvalidOperationException(\"OPENAI_API_KEY is not set.\");\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine(ex.Message);\n    return;\n}","preventionTips":["DI samples read env vars directly — use user secrets (dotnet user-secrets) or launchSettings.json","Do not assume IConfiguration or appsettings.json provides the key","Validate the key at the top of Program.cs before building the DI container","Never commit API keys to source control — use .gitignore for .env files"],"tags":["configuration","csharp","openai","semantic-kernel","environment-variables","dependency-injection","agent-framework-migration"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-14T10:17:34.591Z"}