{"record":{"id":"bfae506e5a11c00e","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-bfae50","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/Structural_Output.cs","lineNumber":20,"sourceCode":"// Structural_Output.cs\n\nusing System.Text.Json;\nusing System.Text.Json.Serialization;\nusing AutoGen.Core;\nusing AutoGen.OpenAI.Extension;\nusing FluentAssertions;\nusing Json.Schema;\nusing Json.Schema.Generation;\nusing OpenAI;\n\nnamespace AutoGen.OpenAI.Sample;\n\npublic class Structural_Output\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 schemaBuilder = new JsonSchemaBuilder().FromType<Person>();\n        var schema = schemaBuilder.Build();\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\")\n            .RegisterMessageConnector()\n            .RegisterPrintMessage();\n        #endregion create_agent\n\n        #region chat_with_agent\n        var prompt = new TextMessage(Role.User, \"\"\"\n            My name is John, I am 25 years old, and I live in Seattle. I like to play soccer and read books.\n            \"\"\");\n        var reply = await openAIClientAgent.GenerateReplyAsync(","sourceCodeStart":2,"sourceCodeEnd":38,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Structural_Output.cs#L2-L38","documentation":"Guard in the structured-output sample: it reads OPENAI_API_KEY and throws a plain Exception when missing, because OpenAIClient(apiKey) must authenticate the gpt-4o-mini client used with a JSON-schema structured output. Thrown by sample code before the JsonSchemaBuilder or the OpenAIChatAgent is constructed.","triggerScenarios":"Calling Structural_Output.RunAsync() with OPENAI_API_KEY absent. Fails at startup; the schema build, agent creation, and the structured-output request never execute.","commonSituations":"Running the whole AutoGen.OpenAI.Sample project with missing credentials; CI without OpenAI secrets; key present only under Azure variable names.","solutions":["Set OPENAI_API_KEY in the launching shell or IDE environment, then re-run.","Verify the key can access gpt-4o-mini and JSON structured output features.","Check for typos/whitespace in the variable value if you believe it's already set.","Store the key in a secrets mechanism (user-secrets, CI secret variables) instead of source or command history."],"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 Structural_Output.\");","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 Structural_Output.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Structural_Output.RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Configuration error: {ex.Message}\");\n}","preventionTips":["Validate the key at startup before building schemas and agents.","Confirm gpt-4o-mini and structured-output support on the key/account.","Keep credentials in IDE run profiles or secret stores rather than ad-hoc exports."],"tags":["configuration","environment-variables","openai","structured-output","json-schema","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}