microsoft/autogen · error · Exception
Please set OPENAI_API_KEY environment variable.
Error message
Please set OPENAI_API_KEY environment variable.
What it means
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.
Source
Thrown at dotnet/samples/AgentChat/AutoGen.Basic.Sample/GettingStart/Streaming_Tool_Call.cs:30
internal class Streaming_Tool_Call
{
public static async Task RunAsync()
{
#region Create_tools
var tools = new Tools();
#endregion Create_tools
#region Create_auto_invoke_middleware
var autoInvokeMiddleware = new FunctionCallMiddleware(
functions: [tools.GetWeatherFunctionContract],
functionMap: new Dictionary<string, Func<string, Task<string>>>()
{
{ tools.GetWeatherFunctionContract.Name, tools.GetWeatherWrapper },
});
#endregion Create_auto_invoke_middleware
#region Create_Agent
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
var model = "gpt-4o-mini";
var openaiClient = new OpenAIClient(apiKey);
var agent = new OpenAIChatAgent(
chatClient: openaiClient.GetChatClient(model),
name: "agent",
systemMessage: "You are a helpful AI assistant")
.RegisterMessageConnector()
.RegisterStreamingMiddleware(autoInvokeMiddleware)
.RegisterPrintMessage();
#endregion Create_Agent
IMessage finalReply = null;
var question = new TextMessage(Role.User, "What's the weather in Seattle");
// In streaming function call
// function can only be invoked untill all the chunks are collected
// therefore, only one ToolCallAggregateMessage chunk will be return here.
await foreach (var message in agent.GenerateStreamingReplyAsync([question]))View on GitHub (pinned to 027ecf0a37)
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.
Example fix
// before
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
// after
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
?? throw new InvalidOperationException("OPENAI_API_KEY is not set. Export it before running Streaming_Tool_Call."); Defensive patterns
Strategy: validation
Validate before calling
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
Console.Error.WriteLine("Set OPENAI_API_KEY before running Streaming_Tool_Call.");
return;
} Try / catch
try
{
await RunAsync();
}
catch (Exception ex) when (ex.Message.Contains("OPENAI_API_KEY"))
{
Console.Error.WriteLine($"Configuration error: {ex.Message}");
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Please set OPENAI_API_KEY environment variable.
- Please set OPENAI_API_KEY environment variable.
- Please set OPENAI_API_KEY environment variable.
- Please set OPENAI_API_KEY environment variable.
- Please set OPENAI_API_KEY environment variable.
AI-assisted analysis of microsoft/autogen@027ecf0a37 (2026-08-15).
Data as JSON: /api/errors/b270c2a4052b9d1e.
Report an issue: GitHub.