Saturday, January 25, 2025

Azure AI services - Develop Azure AI services applications with Azure Key Vault - Language service

Azure AI services - Develop Azure AI services applications with Azure Key Vault:

https://learn.microsoft.com/en-us/azure/ai-services/use-key-vault?tabs=azure-cli&pivots=programming-language-csharp

C# Code:

using Azure;
using Azure.AI.TextAnalytics;
using Azure.Identity;
using Azure.Security.KeyVault.Secrets;
using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var keyVaultName = "sreekeyvault2";
            const string keySecretName = "CognitiveServicesKey";
            const string endpointSecretName = "CognitiveServicesEndpoint";
            var kvUri = $"https://{keyVaultName}.vault.azure.net";
            var keyVaultClient = new SecretClient(new Uri(kvUri),             new DefaultAzureCredential());
            Console.WriteLine($"Retrieving your secrets from {keyVaultName}.");
            var keySecret = await keyVaultClient.GetSecretAsync(keySecretName);
            var endpointSecret =
            await keyVaultClient.GetSecretAsync(endpointSecretName);
            Console.WriteLine($"Your key secret value is: {keySecret.Value.Value}");
            Console.WriteLine($"Your endpoint secret value is:
            {endpointSecret.Value.Value}");
            Console.WriteLine("Secrets retrieved successfully");
            EntityRecognitionExample(keySecret.Value.Value,
            endpointSecret.Value.Value);
            Console.ReadKey();
        }

        private static void EntityRecognitionExample(string keySecret,
        string endpointSecret)
        {
            var exampleString = "I had a wonderful trip to Seattle last week.";
            AzureKeyCredential azureKeyCredential = new AzureKeyCredential(keySecret);
            Uri endpoint = new Uri(endpointSecret);
            var languageServiceClient = new TextAnalyticsClient(endpoint,
            azureKeyCredential);
            Console.WriteLine($"Sending a Named Entity Recognition (NER) request");
            var response = languageServiceClient.RecognizeEntities(exampleString);
            Console.WriteLine("Named Entities:");
            foreach (var entity in response.Value)
            {
                Console.WriteLine($"\tText: {entity.Text},\tCategory:
                {entity.Category},\tSub-Category: {entity.SubCategory}");
                Console.WriteLine($"\t\tScore: {entity.ConfidenceScore:F2},\tLength:
                {entity.Length},\tOffset: {entity.Offset}\n");
            }
        }
    }
}

OutPut:

No comments:

Post a Comment

Featured Post

Azure AI services - Recognize and synthesize speech

Azure AI services - Recognize and synthesize speech: 1. Create 'Speech service' in Azure C# Code: using System; using System.Threa...

Popular posts