{"record":{"id":"1b2ca3c80bb9ddf6","repo":"microsoft/autogen","slug":"please-set-environment-variable-azure-openai-api-k","errorCode":null,"errorMessage":"Please set environment variable AZURE_OPENAI_API_KEY","messagePattern":"Please set environment variable AZURE_OPENAI_API_KEY","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Connect_To_Azure_OpenAI.cs","lineNumber":18,"sourceCode":"// Copyright (c) Microsoft Corporation. All rights reserved.\n// Connect_To_Azure_OpenAI.cs\n\n#region using_statement\nusing System.ClientModel;\nusing AutoGen.Core;\nusing AutoGen.OpenAI.Extension;\nusing Azure.AI.OpenAI;\n#endregion using_statement\n\nnamespace AutoGen.OpenAI.Sample;\n\npublic class Connect_To_Azure_OpenAI\n{\n    public static async Task RunAsync()\n    {\n        #region create_agent\n        var apiKey = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\") ?? throw new InvalidOperationException(\"Please set environment variable AZURE_OPENAI_API_KEY\");\n        var endpoint = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\") ?? throw new InvalidOperationException(\"Please set environment variable AZURE_OPENAI_ENDPOINT\");\n        var model = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_DEPLOY_NAME\") ?? \"gpt-4o-mini\";\n\n        // Use AzureOpenAIClient to connect to openai model deployed on azure.\n        // The AzureOpenAIClient comes from Azure.AI.OpenAI package\n        var openAIClient = new AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(apiKey));\n\n        var agent = new OpenAIChatAgent(\n            chatClient: openAIClient.GetChatClient(model),\n            name: \"assistant\",\n            systemMessage: \"You are a helpful assistant designed to output JSON.\",\n            seed: 0)\n            .RegisterMessageConnector()\n            .RegisterPrintMessage();\n        #endregion create_agent\n\n        #region send_message\n        await agent.SendAsync(\"Can you write a piece of C# code to calculate 100th of fibonacci?\");","sourceCodeStart":1,"sourceCodeEnd":36,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/dotnet/samples/AgentChat/AutoGen.OpenAI.Sample/Connect_To_Azure_OpenAI.cs#L1-L36","documentation":"Guard in the Connect_To_Azure_OpenAI sample: it reads AZURE_OPENAI_API_KEY and throws InvalidOperationException when it is missing, because AzureOpenAIClient(new Uri(endpoint), new ApiKeyCredential(apiKey)) cannot authenticate without it. It is sample-authored fail-fast code executed before the OpenAIChatAgent is constructed; note this sample uses InvalidOperationException, unlike the Basic samples' plain Exception.","triggerScenarios":"Calling Connect_To_Azure_OpenAI.RunAsync() with AZURE_OPENAI_API_KEY unset. The throw fires before AZURE_OPENAI_ENDPOINT is read, so an endpoint error cannot occur until the key is provided.","commonSituations":"Running OpenAI-sample suites with Azure credentials absent; key configured only for the public OpenAI endpoint; CI jobs without Azure secrets; fresh environment after cloning.","solutions":["Set AZURE_OPENAI_API_KEY from your Azure OpenAI resource (Portal -> Keys and Endpoint) in the launching environment.","Also set AZURE_OPENAI_ENDPOINT (required next line) and optionally AZURE_OPENAI_DEPLOY_NAME (defaults model to gpt-4o-mini).","Prefer IUserSecrets/CI secret variables over plain exports for long-lived setups.","Confirm you are not mixing SDK keys — this must be an Azure OpenAI resource key, not an sk- public key."],"exampleFix":"// before\nvar apiKey = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\") ?? throw new InvalidOperationException(\"Please set environment variable AZURE_OPENAI_API_KEY\");\n\n// after\nvar apiKey = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\")\n    ?? throw new InvalidOperationException(\"AZURE_OPENAI_API_KEY is not set. Copy a key from your Azure OpenAI resource and export it before running.\");","handlingStrategy":"validation","validationCode":"var apiKey = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_API_KEY\");\nvar endpoint = Environment.GetEnvironmentVariable(\"AZURE_OPENAI_ENDPOINT\");\nif (string.IsNullOrWhiteSpace(apiKey) || string.IsNullOrWhiteSpace(endpoint))\n{\n    throw new InvalidOperationException(\"Both AZURE_OPENAI_API_KEY and AZURE_OPENAI_ENDPOINT are required.\");\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    await Connect_To_Azure_OpenAI.RunAsync();\n}\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"AZURE_OPENAI_API_KEY\"))\n{\n    Console.Error.WriteLine($\"Missing Azure credential: {ex.Message}\");\n}","preventionTips":["Configure the full Azure trio (key, endpoint, optional deployment name) before running Azure samples.","Use an Azure OpenAI resource key, not a public OpenAI sk- key, with AzureOpenAIClient.","Prefer secret managers (user-secrets, CI variables) over shell exports for long-lived setups."],"tags":["configuration","environment-variables","azure","azure-openai","dotnet","autogen"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}