{"record":{"id":"e333975edca9efef","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-e33397","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.OpenAI.Sample/Use_Json_Mode.cs","lineNumber":19,"sourceCode":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Use_Json_Mode.cs\n\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing AutoGen.Core;\nusing AutoGen.OpenAI.Extension;\nusing FluentAssertions;\nusing OpenAI;\nusing OpenAI.Chat;\n\nnamespace AutoGen.OpenAI.Sample;\n\npublic class Use_Json_Mode\n{\n    public static async Task RunAsync()\n    {\n        #region create_agent\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        var openAIClient = new OpenAIClient(apiKey);\n        var openAIClientAgent = new OpenAIChatAgent(\n            chatClient: openAIClient.GetChatClient(model),\n            name: \"assistant\",\n            systemMessage: \"You are a helpful assistant designed to output JSON.\",\n            seed: 0, // explicitly set a seed to enable deterministic output\n            responseFormat: ChatResponseFormat.CreateJsonObjectFormat()) // set response format to JSON object to enable JSON mode\n            .RegisterMessageConnector()\n            .RegisterPrintMessage();\n        #endregion create_agent\n\n        #region chat_with_agent\n        var reply = await openAIClientAgent.SendAsync(\"My name is John, I am 25 years old, and I live in Seattle.\");\n\n        var person = JsonSerializer.Deserialize<Person>(reply.GetContent());\n        Console.WriteLine($\"Name: {person.Name}\");","sourceCodeStart":1,"sourceCodeEnd":37,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Use_Json_Mode.cs#L1-L37","documentation":"This exception is thrown by the AutoGen OpenAI sample 'Use_Json_Mode' when the OPENAI_API_KEY environment variable is null. The sample deliberately fails fast instead of passing an empty key to the OpenAI SDK, because the OpenAIClient would otherwise fail later with a less clear auth error. It is a sample-app guard, not library logic.","triggerScenarios":"Running the AutoGen.OpenAI.Sample Use_Json_Mode.RunAsync() (e.g. 'dotnet run' on the sample project) in a shell/process where OPENAI_API_KEY is unset, null, or only set in a different user session.","commonSituations":"New clone of the AutoGen repo without reading the sample README; env var set in PowerShell but sample run from VS/WSL where it does not propagate; CI pipeline without seeded secrets; using 'set' (cmd, session-only) instead of 'setx' or launchSettings.json.","solutions":["Set the variable for the current session: export OPENAI_API_KEY=sk-... (bash) or $env:OPENAI_API_KEY='sk-...' (PowerShell), then rerun the sample.","Or persist it: setx OPENAI_API_KEY sk-... (Windows) / add to ~/.bashrc or ~/.zshrc (Linux/macOS), then open a new terminal.","Or, when running from Visual Studio / Rider, put it in dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Properties/launchSettings.json under environmentVariables.","Never hardcode the key in the sample source; use dotnet user-secrets for shared machines."],"exampleFix":"// before\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n\n// after (fail fast with actionable hint, no code change required if env var is set in launchSettings.json)\nvar apiKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")\n    ?? throw new InvalidOperationException(\"Set OPENAI_API_KEY (e.g. `export OPENAI_API_KEY=sk-...`) before running this sample.\");","handlingStrategy":"validation","validationCode":"if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\")))\n{\n    Console.Error.WriteLine(\"OPENAI_API_KEY is not set. Export it (bash: export OPENAI_API_KEY=sk-...) and rerun.\");\n    return; // or Environment.Exit(1)\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Add required env vars to the sample project's launchSettings.json so IDE runs always have them.","Create a check-env script or dotnet user-secrets setup step documented in the sample README and run it before the app.","Never hardcode keys in source; use user-secrets or a .env file excluded from git."],"tags":["openai","configuration","environment-variables","sample","csharp","dotnet"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}