Chat Bot using Chat GPT 3.5 in C#
Unleashing the Power of OpenAI and C# to Build Your Own Chatbot
This code employs the power of OpenAI’s chat API to create a sophisticated chatbot. The bot’s neural network is trained on a vast corpus of text, enabling it to respond to user input with impressive fluency and flexibility. The chatbot is initialized with a set of messages that introduce it to the user, and then it waits for the user’s input.
Once the user enters a message, the code sends that message, along with all previous messages, to the OpenAI API for processing. The API uses cutting-edge natural language processing algorithms to generate a response, which is then parsed and displayed to the user. This process repeats indefinitely, allowing for a fluid and engaging conversation between the user and the bot.
The code uses a combination of asynchronous HTTP requests and JSON parsing to communicate with the OpenAI API and handle the responses. It also incorporates Spectre.Console, a powerful library for styling and formatting console output, to display the messages and responses in an attractive and readable format. Overall, this code represents a sophisticated and powerful example of how modern AI technologies can be leveraged to create compelling conversational interfaces.
Simply create a new c# .net console application and paste the following code into program.cs
// See: https://platform.openai.com/docs/guides/chat/introduction
// See: https://platform.openai.com/docs/api-reference/chat
using Newtonsoft.Json;
using Spectre.Console;
const string key = "YOUR API KEY";
const string url = "https://api.openai.com/v1/chat/completions";
// Initialise the chat by describing the assistant,
// and providing the assistants first question to the user
var messages = new List<dynamic>
{
new {role = "system",
content = "You are ChatGPT, a large language " +
"model trained by OpenAI. " +
"Answer as concisely as possible. " +
"Make a joke every few lines just to spice things up."},
new {role = "assistant",
content = "How can I help you?"}
};
AnsiConsole.MarkupLine($"[purple]MACHINE:[/] [blue]{Markup.Escape(messages[1].content)}[/]");
while (true)
{
// Capture the users messages and add to
// messages list for submitting to the chat API
var userMessage = AnsiConsole.Ask<string>($"[purple]USER:[/] ");
messages.Add(new { role = "user", content = userMessage });
// Create the request for the API sending the
// latest collection of chat messages
var request = new
{
messages,
model = "gpt-3.5-turbo",
max_tokens = 300,
};
// Send the request and capture the response
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {key}");
var requestJson = JsonConvert.SerializeObject(request);
var requestContent = new StringContent(requestJson, System.Text.Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PostAsync(url, requestContent);
var jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var responseObject = JsonConvert.DeserializeAnonymousType(jsonString, new
{
choices = new [] {new {message=new {role=string.Empty,content=string.Empty}}},
error=new {message=string.Empty}
});
if (!string.IsNullOrEmpty(responseObject?.error?.message)) // Check for errors
{
AnsiConsole.MarkupLine($"[bold red]{Markup.Escape(responseObject?.error.message)}[/]");
}
else // Add the message object to the message collection
{
var messageObject = responseObject?.choices[0].message;
messages.Add(messageObject);
AnsiConsole.MarkupLine($"[purple]MACHINE:[/] [blue]{Markup.Escape(messageObject.content)}[/]");
}
}
Ensure to add the following two nuget packages.
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="Spectre.Console" Version="0.46.0" />
Click F5 to run or dotnet run from command line!
Here is a sample conversation (ignore my bad spelling, chat gpt does!)
p.s the opening 3 paragraphs was written by the ChatGPT API!