{"record":{"id":"fc996159c9bd89f2","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-fc9961","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/GettingStart/Use_Tools_With_Agent.cs","lineNumber":52,"sourceCode":"        var tools = new Tools();\n        #endregion Create_tools\n\n        #region Create_auto_invoke_middleware\n        var autoInvokeMiddleware = new FunctionCallMiddleware(\n            functions: [tools.GetWeatherFunctionContract],\n            functionMap: new Dictionary<string, Func<string, Task<string>>>()\n            {\n                { tools.GetWeatherFunctionContract.Name!, tools.GetWeatherWrapper },\n            });\n        #endregion Create_auto_invoke_middleware\n\n        #region Create_no_invoke_middleware\n        var noInvokeMiddleware = new FunctionCallMiddleware(\n            functions: [tools.GetWeatherFunctionContract]);\n        #endregion Create_no_invoke_middleware\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        var openaiClient = new OpenAIClient(apiKey);\n        var agent = new OpenAIChatAgent(\n            chatClient: openaiClient.GetChatClient(model),\n            name: \"agent\",\n            systemMessage: \"You are a helpful AI assistant\")\n            .RegisterMessageConnector(); // convert OpenAI message to AutoGen message\n        #endregion Create_Agent\n\n        #region Single_Turn_Auto_Invoke\n        var autoInvokeAgent = agent\n            .RegisterMiddleware(autoInvokeMiddleware) // pass function definition to agent.\n            .RegisterPrintMessage(); // print the message content\n        var question = new TextMessage(Role.User, \"What is the weather in Seattle?\");\n        var reply = await autoInvokeAgent.SendAsync(question);\n        reply.Should().BeOfType<ToolCallAggregateMessage>();\n        #endregion Single_Turn_Auto_Invoke\n","sourceCodeStart":34,"sourceCodeEnd":70,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Use_Tools_With_Agent.cs#L34-L70","documentation":"Startup guard in the use-tools getting-started sample: it reads OPENAI_API_KEY and throws a plain Exception when missing, because OpenAIClient(apiKey) must authenticate the gpt-4o-mini chat client used for both auto-invoke and no-invoke tool scenarios. Thrown by sample code before any agent or FunctionCallMiddleware executes.","triggerScenarios":"Running the sample with OPENAI_API_KEY absent from the process environment. The exception occurs at the Create_Agent stage, before the Single_Turn_Auto_Invoke / No_Invoke demonstrations.","commonSituations":"First-run of the samples without credential setup; IDE sessions missing shell exports; CI pipelines without OpenAI secrets; the key configured only for Azure deployments.","solutions":["Export OPENAI_API_KEY (bash: export OPENAI_API_KEY=sk-...; PowerShell: $env:OPENAI_API_KEY='sk-...') and re-run.","Put the key in launchSettings.json or the IDE debug profile when launching from Visual Studio/Rider.","Check the variable name and value (no whitespace) if you believe it is set.","Ensure the key supports gpt-4o-mini tool calls for the auto-invoke scenario to work after startup."],"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 or add it to your IDE run configuration.\");","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 Use_Tools_With_Agent.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Configuration error: {ex.Message}\");\n}","preventionTips":["Run a startup credential check before exercising tool-invocation samples.","Use IDE run profiles for keys to avoid shell/IDE environment mismatches.","Confirm model access (gpt-4o-mini with tools) after the key is set."],"tags":["configuration","environment-variables","openai","function-calling","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}