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

ChatGPT-API for Windows: Use ChatGPT in your Windows Applications

5.00/5 (16 votes)
2 Mar 2023CPOL 24.5K  
Quicky generate text and images
ChatGPT API is available. Why not use it right now?

Introduction

OpenAI released its REST API in March 2023. I am ready to use it for text, image generation and more in my video editor!

Background

Generate Text

C++
CHATGPT_API c("your_api_key");
c.SetModel("code-davinci-002"); // optional
auto off = c.Text("What is your name?");
auto& r = off.value();
std::cout << r.t << std::endl;

It returns a std::optional<CHATGPT_RESULT> that contains the response from the model. 

There's a temperature parameter available to decide the randomness of the response (the lowest - the less random). You can also set a code model (which is currently free) to test code generation.

Generate Images

C++
CHATGPT_API c("your_api_key");
auto off = c.Image("Red cat");
auto& r = off.value();
std::cout << r.t << std::endl;

It returns a std::optional<CHATGPT_RESULT> that contains the raw data of a PNG image of a red cat. 

The library depends on my REST API (included in the repository) and communicates via JSON with the ChatGPT endpoint. For example, member Text() is implemented like that:

C++
  std::optional<CHATGPT_RESULT> Text(const char* prompt, 
                int Temperature = 0, int max_tokens = 10)
    {
        std::vector<char> data(10000);
        sprintf_s(data.data(), 10000, R"({
"model": "%s",
"prompt" : "%s",
"temperature" : %i,
"max_tokens" : %i,
"top_p" : 1,
"frequency_penalty" : 0.2,
"presence_penalty" : 0
})", model.c_str(), prompt, Temperature, max_tokens);

        data.resize(strlen(data.data()));
        RESTAPI::REST r;
        r.Connect(L"api.openai.com", true, 0, 0, 0, 0);
        std::initializer_list<std::wstring> hdrs = {
            Bearer(),
            L"Content-Type: application/json",
        };
        auto hi = r.RequestWithBuffer(L"/v1/completions", 
                  L"POST", hdrs, data.data(), data.size());
        std::vector<char> out;
        r.ReadToMemory(hi, out);
        out.resize(out.size() + 1);
        try
        {
            jsonxx::Object o;
            o.parse(out.data());
            CHATGPT_RESULT r;
            r.o = o;
            auto& choices = o.get<jsonxx::Array>("choices");
            auto& choice0 = choices.get<jsonxx::Object>(0);
            r.t = choice0.get<jsonxx::String>("text");
            return r;
        }
        catch (...)
        {
        }
        return {};
    }

Points of Interest

Right now, I'm too busy implementing those awesome functions in my Turbo Play, so I will be constantly implementing new stuff!

History

  • 2nd March, 2023 - First release

License

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