AI Foundry Playground produces invalid code sample in VS Code

Morris 0 Reputation points
2025-06-19T08:31:29.8366667+00:00

I have set up an Azure AI Foundry resource to use the gpt-4.1 model. I cannot get it to work in C#, so I tried it out on the Playground, where it works perfectly. From the Playground, clicking on "Open in VS Code" produces a C# program that also does not work. (The only thing I changed was adding my API Key directly, whereas the sample program reads it from the environment) Both programs produce a HTTP 401 error:

"Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource."

How can the Microsoft-generated sample not work? I'm completely stuck!

Here is the code from the VS Code sample, with the Endpoint edited to replace my personal details with "<MY-NAME>":

// Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --prerelease
using Azure;
using Azure.AI.OpenAI;
using OpenAI.Chat;

using static System.Environment;
using System.Text.Json;

async Task RunAsync()
{
  // Retrieve the OpenAI endpoint from environment variables
  var endpoint = GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? "https://<MY-NAME>.cognitiveservices.azure.com/";
  if (string.IsNullOrEmpty(endpoint))
  {
      Console.WriteLine("Please set the AZURE_OPENAI_ENDPOINT environment variable.");
      return;
  }

  var key = "<MY_API_KEY>"; //GetEnvironmentVariable("AZURE_OPENAI_KEY");
  if (string.IsNullOrEmpty(key))
  {
      Console.WriteLine("Please set the AZURE_OPENAI_KEY environment variable.");
      return;
  }

    AzureKeyCredential credential = new AzureKeyCredential(key);

    // Initialize the AzureOpenAIClient
    AzureOpenAIClient azureClient = new(new Uri(endpoint), credential);

    // Initialize the ChatClient with the specified deployment name
    ChatClient chatClient = azureClient.GetChatClient("gpt-4.1");
    
    // Create a list of chat messages
    var messages = new List<ChatMessage>
    {
        new SystemChatMessage(@"You are an AI assistant that helps people find information."),
              new UserChatMessage(@"I am going to Paris, what should I see?"),
              new AssistantChatMessage(@"Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:

1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.
2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.
3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.

These are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world."),
              new UserChatMessage(@"What is so great about #1?"),
    };


    // Create chat completion options

    var options = new ChatCompletionOptions {
        Temperature = (float)0.7,
        MaxOutputTokenCount = 800,
        
        TopP=(float)0.95,
        FrequencyPenalty=(float)0,
        PresencePenalty=(float)0
    };

    try
    {
        // Create the chat completion request
        ChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);

        // Print the response
        if (completion != null)
        {
            Console.WriteLine(JsonSerializer.Serialize(completion, new JsonSerializerOptions() { WriteIndented = true }));
        }
        else
        {
            Console.WriteLine("No response received.");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"An error occurred: {ex.Message}");
    }
}

await RunAsync();
Azure AI services
Azure AI services
A group of Azure services, SDKs, and APIs designed to make apps more intelligent, engaging, and discoverable.
3,602 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Morris 0 Reputation points
    2025-06-19T08:51:59.67+00:00

    I've found a sloution: When I click on the "View Code" link in the Playground, the Endpoint is different, and correct!

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.