Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / artificial-intelligence / ChatGPT

ChatGPT API in C# WPF / XAML / MVVM

5.00/5 (8 votes)
16 Feb 2024CPOL2 min read 16.3K  
Implement ChatGPT API in C# WPF with GPT3.5-turbo
C# WPF app that communicates with OpenAI GPT3.5-turbo API (free)

Introduction

This is a C# WPF app that communicates with OpenAI GPT-3.5 Turbo API. The app's UI layout is similar to the OpenAI chat website https://chat.openai.com.

Using the Code

To use the code, you need to sign up and get your OpenAI GPT-3.5 Turbo API key (free) at:

Put your key in App.xaml.cs. Your key could look like 'sk-Ih...WPd'.

Image 1

This app uses MVVM design pattern with MainWindow class and ChatViewModel class.

C#
public ChatViewModel(WhetstoneChatGPTService chatGPTService)
{
    _chatGPTService = chatGPTService;
    _chatHistory = new ChatHistory();
    _selectedChat = _chatHistory.AddNewChat();
    ChatList = new ObservableCollection<Chat>(_chatHistory.ChatList);
}

ChatViewModel contains WhetstoneChatGPTService wrapping the NuGet package Whetstone.ChatGPT that does communication with OpenAI GPT-3.5 Turbo API.

ChatViewModel also contains ChatHistory tracking a chat list with each chat holding the chat result.

ChatList binds with the chat list in XAML on the left panel.

C#
[RelayCommand]
private async Task Send()
{    
    if (!ValidateInput(ChatInput, out string prompt))
    {
        return;
    }

    try
    {       
        await Send(prompt, prompt);     
        PostProcessOnSend(prompt);
    }
    catch (Exception ex)
    {
        StatusMessage = ex.Message;
    }
}

When the user clicks 'Send' button, prompt (input in the text box) will be sent to OpenAI API server and result will be displayed on the right side of the screen.

Image 2

I personally use this app like a helper, so I have added Explain, Translate to, and Speak features.

Explain is like a lookup, kind of a shortcut of Send. For example, with input of 'ML.NET', I will automatically send "Explain 'ML.NET'" to the GPT server. This feature is helpful for finding meaning of a single word or a phrase.

Translate to is just simply a Send with selected language (e.g., "Translate to Spanish 'ChatGPT'"). You would get "'chatgpt' se traduce al espaƱol como 'chatgpt'."

C#
[RelayCommand]
private async Task Explain()
{
    await ExecutePost("Explain");
}

[RelayCommand]
private async Task TranslateTo()
{
    await ExecutePost($"Translate to {SelectedLang}");
}

private async Task ExecutePost(string prefix)
{   
    try
    {     
        // 'Explain' or 'Translate to' always uses a new chat
        AddNewChatIfNotExists();

        prompt = $"{prefix} '{prompt}'";
        await Send(prompt, prompt);

        PostProcessOnSend(prompt);     
    }
    catch (Exception ex)
    {
        StatusMessage = ex.Message;
    }
}

Speak has nothing to with GPT, but a way of finding out pronunciation of input.

C#
[RelayCommand]
private void Speak()
{
    try
    {
        var synthesizer = new SpeechSynthesizer()
        {
            Volume = 100,  // 0...100
            Rate = -2,     // -10...10
        };

        synthesizer.SelectVoiceByHints
         (IsFemaleVoice ? VoiceGender.Female : VoiceGender.Male, VoiceAge.Adult);

        synthesizer.SpeakAsync(ChatInput);
    }
    catch (Exception ex)
    {
        StatusMessage = ex.Message;
    }
}

With the features above, I am using this app much more often!

Image 3

Lastly, you can ask GPT-3.5 Turbo to create an image based on a prompt (see "Australian Open tennis" above).

Points of Interest

This app is compiled with Visual Studio 2022 (Community version okay). If you don't have .NET 8 installed on your machine, simply remove net8.0-windows from CSharpWpfChatGPT.csproj.

Try out the source code and feel free to reach out by leaving me messages in the comment section below.

History

  • 7th February, 2024: Initial version
  • 16th February, 2024: Added Explain, Translate to and Speak

If you like this article and the source code, please give it a star!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)