{"record":{"id":"e6f7ca196179a2b2","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-e6f7ca","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/Example05_Dalle_And_GPT4V.cs","lineNumber":55,"sourceCode":"        var imageResponse = await openAIClient.GetImageClient(\"dall-e-3\").GenerateImageAsync(prompt, option);\n        var imageUrl = imageResponse.Value.ImageUri.OriginalString;\n\n        return $@\"// ignore this line [IMAGE_GENERATION]\nThe image is generated from prompt {prompt}\n\n{imageUrl}\";\n    }\n\n    public static async Task RunAsync()\n    {\n        // This example shows how to use DALL-E and GPT-4V to generate image from prompt and feedback.\n        // The DALL-E agent will generate image from prompt.\n        // The GPT-4V agent will provide feedback to DALL-E agent to help it generate better image.\n        // The conversation will be terminated when the image satisfies the condition.\n        // The image will be saved to image.jpg in current directory.\n\n        // get OpenAI Key and create config\n        var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n        var openAIClient = new OpenAIClient(openAIKey);\n        var instance = new Example05_Dalle_And_GPT4V(openAIClient);\n        var imagePath = Path.Combine(\"resource\", \"images\", \"background.png\");\n        if (File.Exists(imagePath))\n        {\n            File.Delete(imagePath);\n        }\n\n        var generateImageFunctionMiddleware = new FunctionCallMiddleware(\n            functions: [instance.GenerateImageFunctionContract],\n            functionMap: new Dictionary<string, Func<string, Task<string>>>\n            {\n                { nameof(GenerateImage), instance.GenerateImageWrapper },\n            });\n        var dalleAgent = new OpenAIChatAgent(\n            chatClient: openAIClient.GetChatClient(\"gpt-4o-mini\"),\n            name: \"dalle\",\n            systemMessage: \"You are a DALL-E agent that generate image from prompt, when conversation is terminated, return the most recent image url\")","sourceCodeStart":37,"sourceCodeEnd":73,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example05_Dalle_And_GPT4V.cs#L37-L73","documentation":"Fail-fast guard in the DALL-E + GPT-4V sample: before constructing OpenAIClient, the sample reads OPENAI_API_KEY and throws a plain Exception if it is missing, because every OpenAI API call (image generation with DALL-E and GPT-4V vision feedback) needs that key. The throw comes from the sample's RunAsync, not from AutoGen or the OpenAI .NET SDK.","triggerScenarios":"Invoking Example05_Dalle_And_GPT4V.RunAsync() in a process where OPENAI_API_KEY is unset/empty. The throw happens immediately at startup, before any image generation or GPT-4V call is attempted.","commonSituations":"Running the sample suite (many AutoGen.Basic.Sample examples) with only some API keys configured; CI runs without OpenAI secrets; launching from an IDE whose process does not inherit the shell-exported variable; key stored only in a .env file that the sample does not load.","solutions":["Export the key in the launching shell: export OPENAI_API_KEY=sk-... (or setx / $env: on Windows), then re-run RunAsync.","Configure the key in the IDE's run profile (launchSettings.json environmentVariables) if you start the sample from Visual Studio/Rider.","Confirm the variable reaches the process (dotnet does not read .env files automatically — load it explicitly or set it in the environment).","Note this example also incurs image-generation costs; verify the key has DALL-E access before running."],"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 your run configuration before running this sample.\");","handlingStrategy":"validation","validationCode":"var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(openAIKey))\n{\n    Console.Error.WriteLine(\"OPENAI_API_KEY is required for the DALL-E + GPT-4V sample.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Example05_Dalle_And_GPT4V.RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Missing credential: {ex.Message}\");\n}","preventionTips":["Check all required env variables in one startup block before running a multi-model example (this one uses DALL-E and GPT-4V).","Inject keys via IDE run profiles or CI secrets instead of ad-hoc shell exports.","Be aware image-generation samples incur per-image costs; validate the key and budget before running."],"tags":["configuration","environment-variables","openai","dall-e","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}