Blog

All Blog Posts  |  Next Post  |  Previous Post

Use ChatGPT from Delphi

Bookmarks: 

Monday, December 26, 2022

TMS Software Delphi  Components

For a couple of weeks now, ChatGPT is the talk of the town.
In record time, millions of users signed up and tested the new AI NLP service from OpenAI and are amazed by the answers for questions it comes up with.

For us Delphi developers, it's even more fun having the ability to go a step further and automate sending questions and getting answers from a Delphi app. This is possible thanks to the ChatGPT REST API.

We'd liked to present simple code here that shows how this can be done in any type of Delphi app (or even Lazarus Object Pascal app) on any platform. To ensure this code can be used in Windows, macOS, iOS, Android, Linux apps, we opted to use the TTMSFNCCloudBase class from TMS FNC Core. This offers a rich interface to perform REST API requests from any platform and any framework. To get started with the OpenAI ChatGPT API, request your API key here: https://beta.openai.com/account/api-keys 


The code to ask questions and get answer from ChatGPT from a Delphi app is with TMS FNC TTMSCloudBase as simple as:

uses
  System.JSON, VCL.TMSFNCCloudBase;

function AskChatGPT(AQuestion: string): string;
var
  LCb: TTMSFNCCloudBase;
  LPostdata: string;
  LJsonValue: TJsonValue;
  LJsonArray: TJsonArray;
  LJSonString: TJsonString;
begin
  Result := '';

  LPostData := '{' +
    '"model": "text-davinci-003",'+
    '"prompt": "' + AQuestion + '",'+
    '"max_tokens": 2048,'+
    '"temperature": 0'+
    '}';

  // create instance of TMS FNC Cloud Base class
  LCb := TTMSFNCCloudBase.Create;

  try
    // Use JSON for the REST API calls and set API KEY via Authorization header
    LCb.Request.AddHeader('Authorization','Bearer ' + CHATGPT_APIKEY);
    LCb.Request.AddHeader('Content-Type','application/json');

    // Select HTTPS POST method, set POST data and specify endpoint URL
    LCb.Request.Method := rmPOST;
    LCb.Request.PostData := LPostData;
    LCb.Request.Host := 'https://api.openai.com';
    LCb.Request.Path := 'v1/completions';

    // Execute the HTTPS POST request synchronously (last param Async = false)
    LCb.ExecuteRequest(nil,nil,false);

    // Process returned JSON when request was successful 
    if Lcb.RequestResult.Success then
    begin
      LJsonValue := TJSonObject.ParseJSONValue(Lcb.RequestResult.ResultString);
      LJsonValue := LJsonValue.GetValue<TJSonValue>('choices');
      if LJsonValue is TJSonArray then
      begin
        LJSonArray := LJsonValue as TJSonArray;
        LJSonString := LJSonArray.Items[0].GetValue<TJSONString>('text');
        Result := LJSonString.Value;
      end
      else
    end
    else
      raise Exception.Create('HTTP response code: ' + LCb.RequestResult.ResponseCode.ToString);
  finally
    LCb.Free;
  end;
end;

With this code, using ChatGPT from a Delphi app becomes as simple as:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Lines.Text := AskChatGPT(Edit1.Text);
end;
When you want to use this in a FireMonkey cross-platform app, all you need to do is change in the uses list VCL.TMSFNCCloudBase to FMX.TMSFNCCloudBase. Or when you want to use this from Lazarus, change the unit name to LCLTMSFNCCloudBase.
Note that we do not mention TMS WEB Core here that TMS FNC also supports. This is because OpenAI specifies that the API key cannot be used in a web client application where this key would be visible to anyone.

You can get the app full source to replicate this test from Github. Make sure to download & install TMS FNC Core as well.

While playing a little bit with ChatGPT from the Delphi app, here are some of the answers it came up with:

TMS Software Delphi  Components

TMS Software Delphi  Components

And this was a question asked in connection with our TMS VCL TAdvStringGrid component and surprisingly, the answer is pretty spot-on and accurate. Who knows that shortly ChatGPT will make our support engineers redundant? :)

TMS Software Delphi  Components

We are curious to hear what you think about ChatGPT, how you envision using it in your Delphi apps or business in general?








Bruno Fierens


Bookmarks: 

This blog post has received 8 comments.


1. Tuesday, December 27, 2022 at 7:52:34 PM


Excellent work Bruno, is it possible to create this web application 100% made in tms web core? I appreciate your response. Thank you.

Mike


2. Tuesday, December 27, 2022 at 7:58:36 PM

What do you recommend as best practice to securely store API keys / tokens, when using WebCore, please? The purpose being to prevent a user from acquiring in plain text simply by using out-of-the-box source viewng / debugging features of modern browsers.

Hazell Richard


3. Wednesday, December 28, 2022 at 9:42:40 AM

I explained in the article: "This is because OpenAI specifies that the API key cannot be used in a web client application where this key would be visible to anyone."
See also this specification https://beta.openai.com/account/api-keys
So, the key cannot be used client-side in a web application.

Bruno Fierens


4. Wednesday, December 28, 2022 at 9:58:04 AM

Cool 👍

Dedi Supardi


5. Thursday, December 29, 2022 at 6:22:22 PM

Great work as always, Bruno. Just as a note and for people don''t get confused, this API is not to use ChatGPT. This API is to use GPT-3 text transformer. Although ChatGPT is based on GPT-3, they are totally different models, and there is no API to use ChatGPT yet.

Guile Lindroth


6. Thursday, December 29, 2022 at 6:27:41 PM

Confusing indeed, but I stand corrected. Thanks for pointing out.

Bruno Fierens


7. Saturday, August 5, 2023 at 9:51:28 PM

I installed the tms components and compiled the code. Probably I am doing something wrong because I always get a http response code 429 error. Any ideas? Thanks in advance

manuel lopez


8. Sunday, August 6, 2023 at 11:43:30 AM

Error 429 means:
The HTTP 429 Too Many Requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting").

Can it be you sent too much requests to the service already?

Bruno Fierens




Add a new comment

You will receive a confirmation mail with a link to validate your comment, please use a valid email address.
All fields are required.



All Blog Posts  |  Next Post  |  Previous Post