Saturday, April 13, 2024

Azure OpenAI Chat and DALL-E in C# and Python

Azure OpenAI Chat in C#:
// Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5
 
using System;
using System.Threading.Tasks;
using Azure;
using Azure.AI.OpenAI;
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            OpenAIClient client = new OpenAIClient(new Uri("https://xxx-xxxxxxxxx.openai.azure.com/"),
                new AzureKeyCredential("123456895a5bcef0hijklmnopqrstuvwx"));
 
            Response<ChatCompletions> responseWithoutStream = await client.GetChatCompletionsAsync("model_deployment_name",
                new ChatCompletionsOptions()
                {
                    Messages = {
                        new ChatMessage(ChatRole.System, @"You are an AI assistant that helps people find information."),
                        new ChatMessage(ChatRole.User, @"Summarize:
                        Full-stack developer with Azure Development")
                    },
                    Temperature = (float)0.7,
                    MaxTokens = 800,
                    NucleusSamplingFactor = (float)0.95,
                    FrequencyPenalty = 0,
                    PresencePenalty = 0,
                });
            ChatCompletions response = responseWithoutStream.Value;
            Console.WriteLine(response.Choices[0].Message.Content);
            Console.ReadKey();
        }
    }
}

Azure OpenAI Chat in Python:

from openai import AzureOpenAI

client = AzureOpenAI(
    azure_endpoint = "https://xxx-xxxxxxxxx.openai.azure.com/",
    api_key = "123456895a5bcef0hijklmnopqrstuvwx",  
    api_version="2024-02-15-preview"
    )

message_text = [
    {"role":"system",
     "content":"You are an AI assistant that helps people find information."},
    {"role":"user","content":"Summary  
\nFull-stack developer with Azure Development"}
    ]

completion = client.chat.completions.create(
    model="model_deployment_name",
    messages = message_text,
    temperature=0.7,
    max_tokens=800,
    top_p=0.95,
    frequency_penalty=0,
    presence_penalty=0,
    stop=None
    )

print(completion.choices[0].message.content)



Azure OpenAI DALL-E 3 in Python:
# Note: DALL-E 3 requires version 1.0.0 of the openai-python library or later
# !pip install openai
import os
from openai import AzureOpenAI
import json

client = AzureOpenAI(
    api_version="2024-02-01",
    azure_endpoint="https://mydemo.openai.azure.com/",
    api_key='key'  # os.environ["AZURE_OPENAI_API_KEY"],
)

result = client.images.generate(
    model="Dalle3", # the name of your DALL-E 3 deployment
    prompt="A relisting image of a futuristic skyline consisting of the world's
tallest building ",
    n=1
)

image_url = json.loads(result.model_dump_json())['data'][0]['url']
print(image_url)









































Use Azure OpenAI APIs in your app c#:

// {
//     "AzureOAIEndpoint": "https://rg1openailab.openai.azure.com/",
//     "AzureOAIKey": "e9742dc25fd446a38492fecb6f3c8e3d",
//     "AzureOAIDeploymentName": "gpt35turbo16kdemo"
// }

//  dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.14
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Azure;
using Azure.AI.OpenAI;

IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json").Build();
string? oaiEndpoint = config["AzureOAIEndpoint"];
string? oaiKey = config["AzureOAIKey"];
string? oaiDeploymentName = config["AzureOAIDeploymentName"];

if (string.IsNullOrEmpty(oaiEndpoint) || string.IsNullOrEmpty(oaiKey) ||
string.IsNullOrEmpty(oaiDeploymentName))
{
    Console.WriteLine("Please check your appsettings.json file for missing
or incorrect values.");
    return;
}

OpenAIClient client = new OpenAIClient(new Uri(oaiEndpoint),
new AzureKeyCredential(oaiKey));
string systemMessage = "I am a hiking enthusiast named Forest who helps
people discover hikes in their area. If no area is specified, I will
default to near Rainier National Park. I will then provide three
suggestions for nearby hikes that vary in length. I will also share an
interesting fact about the local nature on the hikes when making a
recommendation.";
var messagesList = new List<ChatRequestMessage>()
{
    new ChatRequestSystemMessage(systemMessage),
};

do
{
    Console.WriteLine("Enter your prompt text (or type 'quit' to exit): ");
    string? inputText = Console.ReadLine();
    if (inputText == "quit") break;

    if (inputText == null)
    {
        Console.WriteLine("Please enter a prompt.");
        continue;
    }

    Console.WriteLine("\nSending request for summary to Azure OpenAI
endpoint...\n\n");
    messagesList.Add(new ChatRequestUserMessage(inputText));

    ChatCompletionsOptions chatCompletionsOptions = new
ChatCompletionsOptions()
    {
        MaxTokens = 1200,
        Temperature = 0.7f,
        DeploymentName = oaiDeploymentName
    };

    foreach (ChatRequestMessage chatMessage in messagesList)
    {
        chatCompletionsOptions.Messages.Add(chatMessage);
    }

    ChatCompletions response =
client.GetChatCompletions(chatCompletionsOptions);
    string completion = response.Choices[0].Message.Content;
    messagesList.Add(new ChatRequestAssistantMessage(completion));
    Console.WriteLine("Response: " + completion + "\n");
} while (true);





Utilize prompt engineering in your app in c#:

// {
//     "AzureOAIEndpoint": "https://openailab.openai.azure.com/",
//     "AzureOAIKey": "e8762dc15fd441a68495fecb7f3c8e3d",
//     "AzureOAIDeploymentName": "gpt35turbo16kdemo"
// }
//  dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.14
//dotnet run - to run app
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Azure;
using Azure.AI.OpenAI;

IConfiguration config = new ConfigurationBuilder().
AddJsonFile("appsettings.json").Build();
string? oaiEndpoint = config["AzureOAIEndpoint"];
string? oaiKey = config["AzureOAIKey"];
string? oaiDeploymentName = config["AzureOAIDeploymentName"];
bool printFullResponse = true;

do
{
    Console.WriteLine("-----------\nPausing the app to allow you to change
the system prompt.\nPress any key to continue...");
    Console.ReadKey();
    Console.WriteLine("\nUsing system message from system.txt");
    string systemMessage = System.IO.File.ReadAllText("system.txt");
    systemMessage = systemMessage.Trim();
    Console.WriteLine("\nEnter user message or type 'quit' to exit:");
    string userMessage = Console.ReadLine() ?? "";
    userMessage = userMessage.Trim();
    if (systemMessage.ToLower() == "quit" ||
userMessage.ToLower() == "quit")
    {
        break;
    }
    else if (string.IsNullOrEmpty(systemMessage) ||
string.IsNullOrEmpty(userMessage))
    {
        Console.WriteLine("Please enter a system and user message.");
        continue;
    }
    else
    {
        await GetResponseFromOpenAI(systemMessage, userMessage);
    }
} while (true);

async Task GetResponseFromOpenAI(string systemMessage, string userMessage)
{
    Console.WriteLine("\nSending prompt to Azure OpenAI endpoint...\n\n");
    if (string.IsNullOrEmpty(oaiEndpoint) || string.IsNullOrEmpty(oaiKey)
|| string.IsNullOrEmpty(oaiDeploymentName))
    {
        Console.WriteLine("Please check your appsettings.json file for
missing or incorrect values.");
        return;
    }
    OpenAIClient client = new OpenAIClient(new Uri(oaiEndpoint),
new AzureKeyCredential(oaiKey));
    Console.WriteLine("\nAdding grounding context from grounding.txt");
    string groundingText = System.IO.File.ReadAllText("grounding.txt");
    userMessage = groundingText + userMessage;
    var chatCompletionsOptions = new ChatCompletionsOptions()
    {
        Messages =
     {
         new ChatRequestSystemMessage(systemMessage),
         new ChatRequestUserMessage(userMessage)
     },
        Temperature = 0.7f,
        MaxTokens = 800,
        DeploymentName = oaiDeploymentName
    };
    Response<ChatCompletions> response =
await client.GetChatCompletionsAsync(chatCompletionsOptions);
    ChatCompletions completions = response.Value;
    string completion = completions.Choices[0].Message.Content;
    if (printFullResponse)
    {
        Console.WriteLine($"\nFull response:
{JsonSerializer.Serialize(completions, new JsonSerializerOptions
{ WriteIndented = true })}\n\n");
    }
    Console.WriteLine($"\nResponse:\n{completion}\n\n");
}







Friday, January 19, 2024

Sent Email in C#

Sent Email in C#:

//Option 1:
using System;
using System.Net.Mail;
using System.Security;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Start....");
            string password = "password"; //ConfigurationManager.AppSettings["EmailPassword"];
            SecureString secure_passWord = new SecureString();
            foreach (char c in password.ToCharArray()) { secure_passWord.AppendChar(c); }
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            //client.Credentials = new NetworkCredential("abc@xyz.com", secure_passWord);
            client.Credentials = new NetworkCredential("abc@xyz.com", "password");
            client.Port = 587; //replace with actual value
            client.Host = "smpt.mail.com"; //replace with actual value
            //client.DeliveryMethod = SmtpDeliveryMethod.Network;
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("abc@xyz.com");
            mail.To.Add("def@xyz.com");
            mail.Subject = "Test Mail";
            mail.Body = "Test body";
            mail.BodyEncoding = Encoding.UTF8;
            mail.IsBodyHtml = true;
            client.Send(mail);
            Console.WriteLine("End....");
        }
    }
}


//Option 2:
//https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/email/send-email?tabs=windows%2Cconnection-string&pivots=programming-language-csharp
//Quickstart: How to send an email using Azure Communication Service
using Azure;
using Azure.Communication.Email;
 
namespace SendEmail
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            string connectionString = "connectionString";
            EmailClient emailClient = new EmailClient(connectionString);
            var subject = "Welcome to Azure Communication Service Email APIs.";
            var htmlContent = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email.</h4><p>This mail was sent using .NET SDK!!</p></body></html>";
            var sender = "DoNotReply@fcc11977-0b46-46c9-a657-4216db032070.azurecomm.net";
            var recipient = "abc@xyz.com";
            try
            {
                Console.WriteLine("Sending email...");
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Completed, sender, recipient, subject, htmlContent);
                EmailSendResult statusMonitor = emailSendOperation.Value;
                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");
                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }
    }
}


//Option 3:
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //Required Azure Application Permissions : Mail.Send
            string clientId = "clientId";
            string clientSecret = "clientSecret";
            string tenantId = "tenantId";
            string userEmail = "abc@xyz.com"; // The user on behalf of whom you want to send the email
 
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                .Build();
 
            var authResult = await confidentialClient.
                AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" })
                .ExecuteAsync();
 
            string accessToken = authResult.AccessToken;
 
            using (var httpClient = new HttpClient())
            {
                //Required Azure Application Permissions : Mail.Send
                var apiUrl = $"https://graph.microsoft.com/v1.0/users/{userEmail}/sendMail"; //Mail.Send
 
                var message = new
                {
                    message = new
                    {
                        subject = "Subject of the email",
                        body = new
                        {
                            content = "Body of the email",
                            contentType = "Text"
                        },
                        toRecipients = new[]
                        {
                        new { emailAddress = new { address = "def@xyz.com" } }
                    }
                    }
                };
 
                var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 
                var response = await httpClient.PostAsync(apiUrl, jsonContent);
 
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Email sent successfully.");
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
                }
            }
        }
    }
}


//Option 4:
//https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth-ropc
Microsoft identity platform and OAuth 2.0 Resource Owner Password Credentials
 
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var clientId = "clientId";
            var tenantId = "tenantId";
            var clientSecret = "clientSecret";
            var userName = "userName";
            var userPassword = "userPassword";
            var requestUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
            var apiUrl = "https://graph.microsoft.com/v1.0/me/sendmail";
 
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            request.Headers.Add("Cookie", "fpc=AohS41ndFd5KswGP3EyyEk11dsNQAQAAADIbQ90OAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
            List<KeyValuePair<string, string>> collection = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", userPassword),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("scope", "mail.send")
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(collection);
            request.Content = content;
            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();
            //Console.WriteLine(responseContent);
            dynamic jsonData = JsonConvert.DeserializeObject(responseContent);
            string accessToken = jsonData.access_token;
            Console.WriteLine(accessToken);
 
            var message = new
            {
                message = new
                {
                    subject = "Subject of the email",
                    body = new
                    {
                        content = "Body of the email",
                        contentType = "Text"
                    },
                    toRecipients = new[]
                    {
                        new { emailAddress = new { address = "user1@gmail.com" } }
                    }
                }
            };
            var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response1 = await client.PostAsync(apiUrl, jsonContent);
            if (response1.IsSuccessStatusCode)
            {
                Console.WriteLine("Email sent successfully.");
            }
            else
            {
                Console.WriteLine($"Error: {response1.StatusCode} - {await response1.Content.ReadAsStringAsync()}");
            }
            Console.ReadKey();
        }
    }
}

Featured Post

Azure OpenAI Chat and DALL-E in C# and Python

Azure OpenAI Chat in C#: // Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5   using System; u...

Popular posts