Click here to Skip to main content
15,940,246 members
Articles / Artificial Intelligence / ChatGPT
Tip/Trick

ChatGPT API in C# WPF / XAML / MVVM

Rate me:
Please Sign up or sign in to vote.
5.00/5 (8 votes)
16 Feb 2024CPOL2 min read 14K   18   15
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)


Written By
Software Developer (Senior)
United States United States
I am a full stack Windows developer and based in Orange County, California. Currently, I am focusing on C#, WPF, WinForms, Azure App Service, Web API, gRPC, SQL, Entity Framework, and .NET MAUI.

Comments and Discussions

 
QuestionOpenAI API usage requiring credits starting March 8, 2024 Pin
Peter Sun (247)6-Mar-24 20:45
Peter Sun (247)6-Mar-24 20:45 
QuestionRate limit errors but can't figure out more details Pin
PHenry19-Feb-24 10:58
PHenry19-Feb-24 10:58 
AnswerRe: Rate limit errors but can't figure out more details Pin
Peter Sun (247)19-Feb-24 15:19
Peter Sun (247)19-Feb-24 15:19 
GeneralRe: Rate limit errors but can't figure out more details Pin
PHenry20-Feb-24 4:25
PHenry20-Feb-24 4:25 
GeneralRe: Rate limit errors but can't figure out more details Pin
Peter Sun (247)20-Feb-24 8:43
Peter Sun (247)20-Feb-24 8:43 
GeneralRe: Rate limit errors but can't figure out more details Pin
PHenry22-Feb-24 10:44
PHenry22-Feb-24 10:44 
GeneralRe: Rate limit errors but can't figure out more details Pin
Peter Sun (247)22-Feb-24 18:35
Peter Sun (247)22-Feb-24 18:35 
GeneralRe: Rate limit errors but can't figure out more details Pin
PHenry27-Feb-24 6:25
PHenry27-Feb-24 6:25 
GeneralRe: Rate limit errors but can't figure out more details Pin
Peter Sun (247)27-Feb-24 9:26
Peter Sun (247)27-Feb-24 9:26 
GeneralTwo .NET versions in the project file Pin
Rod at work11-Feb-24 4:24
Rod at work11-Feb-24 4:24 
GeneralRe: Two .NET versions in the project file Pin
Peter Sun (247)11-Feb-24 16:02
Peter Sun (247)11-Feb-24 16:02 
GeneralRe: Two .NET versions in the project file Pin
Rod at work16-Feb-24 13:48
Rod at work16-Feb-24 13:48 
GeneralRe: Two .NET versions in the project file Pin
Peter Sun (247)17-Feb-24 9:24
Peter Sun (247)17-Feb-24 9:24 
GeneralMy vote of 5 Pin
HJ 20208-Feb-24 20:24
HJ 20208-Feb-24 20:24 
GeneralRe: My vote of 5 Pin
Peter Sun (247)9-Feb-24 11:05
Peter Sun (247)9-Feb-24 11:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.