- Integrate AI with c# code.
- Login to https://platform.openai.com/
- You can go for buying credits, so that you get your secret key.
- I have bought 5$ credit to get the security key.
- Now you can integrate the “API Key” to connect to openAI.
- Use the below code
- Install OpenAI package


CODE
public async static Task SimpleChatUsingOpenAIClientWithMessages(string modelName)
{
OpenAIClient openAiClient = new("API Key");
ChatClient chatClient = openAiClient.GetChatClient(modelName);
ChatMessage[] chatMessages =
[
new SystemChatMessage("You are a helpful assistant is very knowledgeable in motivation..."),
new UserChatMessage("Hi, can you help me?"),
new AssistantChatMessage("How can I help you ??"),
new UserChatMessage("Of course, I am feeling exhausted after a tiring and hectic week. Help me please ??"),
];
AsyncCollectionResult completionUpdates = chatClient.CompleteChatStreamingAsync(chatMessages);
await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)
{
foreach (ChatMessageContentPart contentPart in completionUpdate.ContentUpdate)
{
Console.Write(contentPart.Text);
}
}
}
using UseOpenAIFromNET;
using Microsoft.Extensions.Configuration;
var builder = new ConfigurationBuilder();
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
IConfiguration config = builder.Build();
var modelName = config["modelName"];
var imageModel = config["imageModelName"];
var audioModel = config["audioModelName"];
await ChatCompletions.SimpleChatUsingOpenAIClientWithMessages(modelName);
Console.WriteLine("Complete...");
Console.WriteLine();
