{"record":{"id":"b270c2a4052b9d1e","repo":"microsoft/autogen","slug":"please-set-openai-api-key-environment-variable-b270c2","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/Streaming_Tool_Call.cs","lineNumber":30,"sourceCode":"internal class Streaming_Tool_Call\n{\n    public static async Task RunAsync()\n    {\n        #region Create_tools\n        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_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()\n            .RegisterStreamingMiddleware(autoInvokeMiddleware)\n            .RegisterPrintMessage();\n        #endregion Create_Agent\n\n        IMessage finalReply = null;\n        var question = new TextMessage(Role.User, \"What's the weather in Seattle\");\n\n        // In streaming function call\n        // function can only be invoked untill all the chunks are collected\n        // therefore, only one ToolCallAggregateMessage chunk will be return here.\n        await foreach (var message in agent.GenerateStreamingReplyAsync([question]))","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Streaming_Tool_Call.cs#L12-L48","documentation":"Startup guard in the streaming tool-call getting-started sample: before constructing OpenAIClient and the OpenAIChatAgent with streaming function-call middleware, the sample reads OPENAI_API_KEY and throws when it is absent. It fires at agent-construction time in sample code — no streaming request or weather tool call is attempted.","triggerScenarios":"Invoking the sample's run method with OPENAI_API_KEY unset in the process. The throw precedes OpenAIClient creation, so nothing network-related has happened yet.","commonSituations":"Running getting-started samples without key setup; IDE debug sessions that don't inherit exported variables; only Azure OpenAI credentials configured while this sample targets the public OpenAI endpoint.","solutions":["Set OPENAI_API_KEY in the launching shell or IDE run profile and re-run.","Verify with a quick environment dump that the sample process sees the variable.","Confirm gpt-4o-mini access on the key (the model is hard-coded).","Remember streaming function calls require a tool-capable model — an invalid model/key surfaces as an API error after this guard passes."],"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 Streaming_Tool_Call.\");","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 Streaming_Tool_Call.\");\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":["Export the key in the exact shell/IDE that launches the sample.","Verify tool-capable model access (gpt-4o-mini) so startup passes and streaming tool calls also work.","Keep credentials in run profiles or secret stores, not in code."],"tags":["configuration","environment-variables","openai","streaming","function-calling","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}