DEV Community

Cover image for Unleashing AI Conversations: Building a .NET Core Console App with ChatGPT
Shish Singh
Shish Singh

Posted on • Updated on

Unleashing AI Conversations: Building a .NET Core Console App with ChatGPT

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

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

private const string GptApiKey = "GPT_API_KEY";
private const string GptApiUrl = "https://api.openai.com/v1/engines/davinci-codex/completions";
Enter fullscreen mode Exit fullscreen mode

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();
        }
Enter fullscreen mode Exit fullscreen mode

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.");
            }
        }
Enter fullscreen mode Exit fullscreen mode

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; }
}

Enter fullscreen mode Exit fullscreen mode

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

Please find full code here.

P1

Image description

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
Subscribe to my channel:
Youtube Channel
Instagram:
Destination Hideout

Top comments (0)