Unleashing AI Conversations: Building a .NET Core Console App with ChatGPT
Tags: chatgpt, dotnet, openai, learning
Published: 2023-07-27 13:20:27

## Introduction 

Curious about AI-powered applications? In this blog, we'll take you on a journey to create a console-based app using ChatGPT, a powerful language model. Get ready to harness the magic of ChatGPT in your projects and discover a whole new world of interactive possibilities. 

## Steps to follow

1.Create a console based application in visual studio(Any 
   other IDE).

2.Signup to OpenAi platform using the link. If you have an 
   account move to step 3.
   [Signup](https://beta.openai.com/signup/) 

3.If you already have an account please login and create a 
   api Key. This is a unique identity. You may find it or 
   create a new one at 
   [Get your key](https://platform.openai.com/account/api-keys)

```
private const string GptApiKey = "GPT_API_KEY";
private const string GptApiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
```
4.Move to program.cs and let create two variables(above). Replace 
   your key generated at step 3. 

5.Create a function to call gpt service using httpclient. 

```
using (var httpClient = new HttpClient())
        {
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {GptApiKey}");
            var content = new StringContent(JsonConvert.
                                SerializeObject(new { prompt = input, max_tokens = 100 }), 
            Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(GptApiUrl, content);
            return await response.Content.ReadAsStringAsync();
        }
```
6.Call the method on the basis of inputs received from the user. Here I am using "exit" keyword to terminate the conversation. 

```
while (true)
        {
            Console.Write("You: ");
            var userInput = Console.ReadLine().Trim();

            if (userInput.Equals("exit", StringComparison.OrdinalIgnoreCase))
                break;

            var response = await GetChatGptResponse(userInput);
            var gptChatResponse = JsonConvert.DeserializeObject<ChatGptResponse>(response);

            if (gptChatResponse != null && gptChatResponse.choices != null && gptChatResponse.choices.Length > 0)
            {
                var message = gptChatResponse.choices[0].text.Trim();
                Console.WriteLine("GPT: " + message);
            }
            else
            {
                Console.WriteLine("GPT: No response from GPT.");
            }
        }
```
  
7.ChatGPT shared response can be deserilaized using the following class structure. 

```
class ChatGptResponse
{
    public string id { get; set; }
    public string object_type { get; set; }
    public int created { get; set; }
    public int model { get; set; }
    public int object { get; set; }
    public double? usage { get; set; }
    public string prompt { get; set; }
    public Choice[] choices { get; set; }
}

class Choice
{
    public string text { get; set; }
    public int? finish_reason { get; set; }
}

```

8.Your own interactive gtp based console tool is ready. Please enter exit(Your termination term) for closure. 

Please find full code here. 


![P1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hj9kc8sy6is6etj566z.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccobk61wsazsknfayvl0.png)

## Conclusion

Embrace the AI revolution: With ChatGPT and .NET Core, you can create impressive conversational apps that redefine user interactions. Get coding now!

## References

Cover: https://zapier.com/blog/how-does-chatgpt-work/

## Connects

Check out my other blogs: 
[Travel/Geo Blogs](shishsingh.wordpress.com)
Subscribe to my channel: 
[Youtube Channel](youtube.com/@destinationhideout)
Instagram:
[Destination Hideout](https://www.instagram.com/destinationhideout/)