{"record":{"id":"fe81d20f27926380","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-fe81d2","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/Example17_ReActAgent.cs","lineNumber":162,"sourceCode":"    {\n        return $\"Paris\";\n    }\n\n    /// <summary>\n    /// Get current date as DD/MM/YYYY\n    /// </summary>\n    [Function]\n    public async Task<string> GetDateToday(string dummy)\n    {\n        return $\"27/05/2024\";\n    }\n}\n\npublic class Example17_ReActAgent\n{\n    public static async Task RunAsync()\n    {\n        var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\") ?? throw new Exception(\"Please set OPENAI_API_KEY environment variable.\");\n        var modelName = \"gpt-4-turbo\";\n        var tools = new Tools();\n        var openAIClient = new OpenAIClient(openAIKey);\n        var gpt4o = LLMConfiguration.GetOpenAIGPT4o_mini();\n        var reactAgent = new OpenAIReActAgent(\n            client: openAIClient.GetChatClient(modelName),\n            name: \"react-agent\",\n            tools: [tools.GetLocalizationFunctionContract, tools.GetDateTodayFunctionContract, tools.WeatherReportFunctionContract],\n            toolExecutors: new Dictionary<string, Func<string, Task<string>>>\n            {\n                { tools.GetLocalizationFunctionContract.Name, tools.GetLocalizationWrapper },\n                { tools.GetDateTodayFunctionContract.Name, tools.GetDateTodayWrapper },\n                { tools.WeatherReportFunctionContract.Name, tools.WeatherReportWrapper },\n            }\n            )\n            .RegisterPrintMessage();\n\n        var message = new TextMessage(Role.User, \"What is the weather here\", from: \"user\");","sourceCodeStart":144,"sourceCodeEnd":180,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/Example17_ReActAgent.cs#L144-L180","documentation":"Startup guard in the ReAct agent sample: it reads OPENAI_API_KEY and throws when missing, because OpenAIClient(openAIKey) requires the key to call gpt-4-turbo for reasoning, tool use, and execution. Thrown by sample code at the top of RunAsync, before OpenAIReActAgent or any tool middleware is created.","triggerScenarios":"Calling Example17_ReActAgent.RunAsync() with OPENAI_API_KEY unset in the process. Fails immediately at OpenAIClient construction time — no ReAct loop, tool call, or streaming happens.","commonSituations":"Running the sample project's full example list with only non-OpenAI keys set; IDE sessions that don't inherit shell exports; expired or mistyped key set under the right name (that fails later at the API, not here).","solutions":["Export OPENAI_API_KEY in the shell/IDE that launches the sample, then re-run.","Set it in launchSettings.json (environmentVariables) when debugging from Visual Studio/Rider so the sample process sees it.","Sanity-check with a trivial curl or SDK call that the key is valid for gpt-4-turbo, since this sample uses a heavyweight model.","Note the sample also uses LLMConfiguration.GetOpenAIGPT4o_mini() — the same OPENAI_API_KEY must be present for that call too."],"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 (bash: export OPENAI_API_KEY=sk-...) and re-run.\");","handlingStrategy":"validation","validationCode":"var openAIKey = Environment.GetEnvironmentVariable(\"OPENAI_API_KEY\");\nif (string.IsNullOrWhiteSpace(openAIKey))\n{\n    Console.Error.WriteLine(\"Set OPENAI_API_KEY before running Example17_ReActAgent.\");\n    return;\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Example17_ReActAgent.RunAsync();\n}\ncatch (Exception ex) when (ex.Message.Contains(\"OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Configuration error: {ex.Message}\");\n}","preventionTips":["Validate keys once at startup for the whole sample run, not per-method.","Remember this sample needs the key twice: direct OpenAIClient and LLMConfiguration.GetOpenAIGPT4o_mini().","Use gpt-4-class tool-calling models for ReAct loops; cheaper models often fail the tool-call steps."],"tags":["configuration","environment-variables","openai","react-agent","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}