microsoft/semantic-kernel · error · InvalidOperationException

OPENAI_API_KEY is not set.

Error message

OPENAI_API_KEY is not set.

What it means

The OpenAI ToolCall migration sample throws InvalidOperationException when OPENAI_API_KEY is missing. This sample demonstrates function calling (GetWeather) against the direct OpenAI API, comparing SK and AF tool registration. The API key constructs the OpenAIClient that handles tool-call round trips.

Source

Thrown at dotnet/samples/AgentFrameworkMigration/OpenAI/Step02_ToolCall/Program.cs:11

// Copyright (c) Microsoft. All rights reserved.

using System.ComponentModel;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using OpenAI;
using OpenAI.Chat;

var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
var model = System.Environment.GetEnvironmentVariable("OPENAI_MODEL") ?? "gpt-4o";
var userInput = "What is the weather like in Amsterdam?";

Console.WriteLine($"User Input: {userInput}");

[KernelFunction]
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
    => $"The weather in {location} is cloudy with a high of 15°C.";

await SKAgentAsync();
await SKAgent_As_AFAgentAsync();
await AFAgentAsync();

async Task SKAgentAsync()
{
    var builder = Kernel.CreateBuilder().AddOpenAIChatClient(model, apiKey);

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Set OPENAI_API_KEY to your OpenAI API key
  2. Optionally set OPENAI_MODEL (defaults to gpt-4o)
  3. Verify the key is valid and has credit/quota
  4. Ensure the model supports function calling (gpt-4o does)

Example fix

// before
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");

// after
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
    throw new InvalidOperationException(
        "OPENAI_API_KEY is not set. Tool-calling samples require a valid OpenAI key.");
Defensive patterns

Strategy: validation

Validate before calling

var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
    Console.Error.WriteLine("OPENAI_API_KEY is not set. Required for tool-calling samples.");
    return;
}

Type guard

static bool IsOpenAIKeyConfigured() =>
    !string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_API_KEY"));

Try / catch

try
{
    var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY")
        ?? throw new InvalidOperationException("OPENAI_API_KEY is not set.");
}
catch (InvalidOperationException ex) when (ex.Message.Contains("OPENAI_API_KEY"))
{
    Console.Error.WriteLine(ex.Message);
    return;
}

Prevention

When it happens

Trigger: Running OpenAI/Step02_ToolCall without OPENAI_API_KEY. The throw at line 11 fires before the GetWeather KernelFunction is defined.

Common situations: The API key was set in a previous terminal that was closed; the key lacks sufficient quota or permissions for function-calling models; confusing this direct-OpenAI sample with the Azure OpenAI equivalents.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/ffb335bd9c422c84. Report an issue: GitHub.