Lazarus

Free Pascal => General => Topic started by: indydev on December 21, 2022, 04:41:43 am

Title: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: indydev on December 21, 2022, 04:41:43 am
I am trying to get a simple console application to connect with OpenAI's chatGPT. There are libraries for several languages, but of course they don't have one for Free Pascal. However I was told that I could connect using HTTP and that I should look into using Synapse. I have never used the library, so this is my first attempt at doing this.

This is what I have so far (not working!):

Code: Pascal  [Select][+][-]
  1. program OpenAI;
  2.  
  3. {$mode objfpc}{$H+}
  4. uses
  5.   SysUtils, Classes, httpsend, Crt;
  6.  
  7. const
  8.   GREETING = 'Hello! I am your Assistant. Do you have any questions for me?';
  9.   FAREWELL = 'Thank you for asking me your questions I enjoy helping out when I can. Goodbye!';
  10.  
  11. var
  12.   input: string;
  13.   HTTP: THTTPSend;
  14.   Response: TStringList;
  15.   URL: string;
  16.   APIKey: string;
  17.   i: integer;
  18.  
  19. procedure Initialize;
  20. begin
  21.   URL := 'https://api.openai.com/v1/questions/answers';
  22.   APIKey := 'sk-sjLaiEls3i9l29lzOKA2MjdIwlpSK19jyN3q8D5WvAchK4';  //  <--not real key
  23.  
  24.   HTTP := THTTPSend.Create;
  25.  
  26.   HTTP.MimeType := 'application/json';
  27.   HTTP.UserName := APIKey;
  28.   HTTP.Password := '';
  29.   HTTP.Headers.Add('Content-Type: application/x-www-form-urlencoded');
  30.   HTTP.HTTPMethod('POST', URL);
  31. end;
  32.  
  33. function getInput: string;
  34. begin
  35.   write('> ');
  36.   readln(Result);
  37. end;
  38.  
  39. function isGoodbye(input: string): boolean;
  40. begin
  41.   Result := (input = 'goodbye') or (input = 'bye') or (input = 'quit');
  42. end;
  43.  
  44. function getOpenAI_Response(input: string): TStringList;
  45. var
  46.   Buffer: PChar;
  47. begin
  48.   Buffer := PChar(input);
  49.   Result := TStringList.Create;
  50.   HTTP.Document.Clear;
  51.   HTTP.Document.Write(Buffer^, Length(input));
  52.   Response.LoadFromStream(HTTP.Document);
  53. end;
  54.  
  55. begin
  56.   ClrScr;
  57.   Initialize;
  58.   writeln(GREETING);
  59.   try
  60.     repeat
  61.         input := getInput;
  62.         Response := getOpenAI_Response(input);
  63.         for i := 0 to Response.Count -1 do
  64.         begin
  65.            writeln(Response[i]);
  66.         end;
  67.     until isGoodbye(Lowercase(input));
  68.   Finally
  69.     Response.Free;
  70.     HTTP.Free;
  71.   end;
  72.   writeln(FAREWELL);
  73.   readln;
  74. end.
  75.  


I don't see any examples using HTTP since most of the people connecting just use one of the 8 languages they already support.  If you have a way, or are familiar with httpsend in Synapse I'm looking for a helping hand. Thanks.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 22, 2022, 11:21:36 pm
Hello I am new to Lazarus as well as programming but I would also be very interested to accomplish this. :)

I have managed  to connect to the API with the cURL method and get a response.
However, I always get this error message.


{,"    ""error"": {","        ""message"": ""We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON. If you have trouble figuring out how to fix this, please send an email to support@openai.com and include any relevant code you'd like help with.)"",","        ""type"": ""invalid_request_error"",","        ""param"": null,","        ""code"": null","    }",


This is the code I used:

Code: Pascal  [Select][+][-]
  1.  
  2. uses  
  3. SysUtils, Classes, Process;
  4.  
  5. var
  6.   url: string;
  7.   AStringList : TStringList;
  8.   Aprocess: TProcess;  
  9.  
  10. begin
  11.    AProcess := TProcess.Create(nil);
  12.    url:='https://api.openai.com/v1/completions';
  13.    AProcess.Executable:='curl';
  14.    //AProcess.Parameters.Add('-X POST');
  15.    AProcess.Parameters.Add(url);
  16.    AProcess.Parameters.Add('-H "Authorization: Bearer API-KEY"');
  17.    AProcess.Parameters.Add('-H "Content-Type: application/json"');
  18.    AProcess.Parameters.Add('-d ''{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}''');
  19.  
  20.    AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];
  21.    AProcess.Execute;
  22.    AStringList := TStringList.Create;
  23.    AStringList.LoadFromStream(AProcess.Output);
  24.    Label1.Caption:= AStringList.CommaText;  
  25. end;      
  26.  

Here the question is embedded and the answer will be output in Label1.

(I also asked Chatt-GPT for a possible solution to the problem, it decided to insert the excluded line, but with this I got "Error 400 bad". But maybe it would be the right approach...)

Maybe this will bring you a little further ;)

I would be happy if we could solve the problem.
Happy holidays
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ccrause on December 23, 2022, 06:35:52 am
I don't see any examples using HTTP since most of the people connecting just use one of the 8 languages they already support.  If you have a way, or are familiar with httpsend in Synapse I'm looking for a helping hand. Thanks.
See making requests (https://beta.openai.com/docs/api-reference/making-requests) in the documentation.  This shows a simple request example. Comparing the headers in the example with your code shows that the Authorization header field seems to be missing.  Also, the query should be packed into a JSON structure, as per example.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ccrause on December 23, 2022, 07:03:30 am
Code: Pascal  [Select][+][-]
  1.    AProcess.Parameters.Add('-d ''{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}''');

I'm not sure the JSON text should be inside single quotes. Try removing the single quotes before the { and after the  }.  Alternatively replace the single quotes with double quotes (") around the JSON, similar to the other parameters.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 09:43:04 am
Here's a simpler example that works, do not forget to substitute YOUR_API_KEY with your own:
Code: Pascal  [Select][+][-]
  1. program testopenai;
  2. {$mode objfpc}{$ofdef mswindows}{$apptype console}{$endif}
  3. uses Classes, Process;
  4. var
  5.   AStringList : TStrings;
  6.   Aprocess: TProcess;  
  7. begin
  8.    AProcess := TProcess.Create(nil);
  9.    try
  10.      AProcess.Options := AProcess.Options + [poWaitOnExit,poUsePipes];
  11.      AProcess.Executable:='curl.exe';
  12.      AProcess.Parameters.Add('https://api.openai.com/v1/models/text-davinci-003');
  13.      AProcess.Parameters.Add('-H');
  14.      Aprocess.Parameters.Add('"Authorization: Bearer YOUR_API_KEY"'); // do not quote your_APi_KEY!!
  15.      AProcess.Execute;
  16.      try
  17.        AStringList := TStringList.Create;
  18.        AStringList.LoadFromStream(AProcess.Output);    
  19.        Writeln(AStringList.Text);
  20.      finally
  21.        AStringList.Free;
  22.      end;
  23.    Finally  
  24.      AProcess.Free;
  25.    end;
  26. end.
   
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 23, 2022, 10:13:38 am
Quote
I'm not sure the JSON text should be inside single quotes. Try removing the single quotes before the { and after the  }.  Alternatively replace the single quotes with double quotes (") around the JSON, similar to the other parameters.

Good day, thank you very much for your answer. I tried the following two options and still got the same error message as above....

Code: Pascal  [Select][+][-]
  1. AProcess.Parameters.Add('-d {"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}');

and

Code: Pascal  [Select][+][-]
  1. AProcess.Parameters.Add('-d "{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}"');

Do you have any idea what the problem could be?
Thank you very much for your time.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 23, 2022, 10:17:28 am
Here's a simpler example that works, do not forget to substitute YOUR_API_KEY with your own:
Code: Pascal  [Select][+][-]
  1. program testopenai;
  2. {$mode objfpc}{$ofdef mswindows}{$apptype console}{$endif}
  3. uses Classes, Process;
  4. var
  5.   AStringList : TStrings;
  6.   Aprocess: TProcess;  
  7. begin
  8.    AProcess := TProcess.Create(nil);
  9.    try
  10.      AProcess.Options := AProcess.Options + [poWaitOnExit,poUsePipes];
  11.      AProcess.Executable:='curl.exe';
  12.      AProcess.Parameters.Add('https://api.openai.com/v1/models/text-davinci-003');
  13.      AProcess.Parameters.Add('-H');
  14.      Aprocess.Parameters.Add('"Authorization: Bearer YOUR_API_KEY"'); // do not quote your_APi_KEY!!
  15.      AProcess.Execute;
  16.      try
  17.        AStringList := TStringList.Create;
  18.        AStringList.LoadFromStream(AProcess.Output);    
  19.        Writeln(AStringList.Text);
  20.      finally
  21.        AStringList.Free;
  22.      end;
  23.    Finally  
  24.      AProcess.Free;
  25.    end;
  26. end.


Hello, thank you very much for your answer.

That worked amazingly well for me too and I got a response from the API! :)

Do you have any idea how I could make a request to https://api.openai.com/v1/completions with this method?
I just can't get my head around that.

Thanks a lot
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 01:47:17 pm
Here's the same in pure Pascal, no need for curl:
Code: Pascal  [Select][+][-]
  1. program fpopenai;
  2. {$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}{$H+}
  3. uses classes, fphttpclient,opensslsockets;
  4. const
  5.   API_KEY='<Your API Key>';
  6.   model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  7. var
  8.   Client:TfpHttpClient;  
  9. begin
  10.   Client :=TfpHttpClient.Create(nil);
  11.   Try
  12.     Client.AllowRedirect:= true;
  13.     Client.RequestHeaders.Add('Authorization: Bearer '+API_KEY); // replace API_KEY with yours, see above
  14.     writeln(Client.Get('https://api.openai.com/v1/models/text-davinci-003'));
  15.   finally
  16.    Client.Free
  17.   end;
  18. end.
'
Note that I also can't get the POST data to work, not wit this code, nor with the process approach.
But the above code works.
I believe that you have to issue a completion request first.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ccrause on December 23, 2022, 02:05:56 pm
Quote
I'm not sure the JSON text should be inside single quotes. Try removing the single quotes before the { and after the  }.  Alternatively replace the single quotes with double quotes (") around the JSON, similar to the other parameters.

Good day, thank you very much for your answer. I tried the following two options and still got the same error message as above....

Code: Pascal  [Select][+][-]
  1. AProcess.Parameters.Add('-d {"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}');

and

Code: Pascal  [Select][+][-]
  1. AProcess.Parameters.Add('-d "{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}"');

Do you have any idea what the problem could be?
Thank you very much for your time.

Posting content containing double quotes appears to be tricky (depending on the OS or shell, see e.g. this (https://stackoverflow.com/questions/7172784/how-do-i-post-json-data-with-curl), this (https://unix.stackexchange.com/questions/131184/proper-escaping-of-double-quotations-for-curl-post-data) and this (https://stackoverflow.com/questions/4514199/how-to-send-double-quote-in-d-parameter-for-curl-exe)).   Seems like the original attempt using single quotes around the JSON is generally thought to be correct, but there must be some interference from the executing shell environment.  Perhaps using TfpHttpClient will result in a more general solution where escaping of the JSON content is not interfered with by the shell environment.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 03:04:59 pm
WORKING!!!
Code: Pascal  [Select][+][-]
  1. program fpopenai_3;
  2. {$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}{$H+}
  3. uses classes, fphttpclient,opensslsockets;
  4. const
  5.   API_KEY='<API_KEY>';
  6.   model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  7. var
  8.   Client:TfpHttpClient;  
  9. begin
  10.   Client :=TfpHttpClient.Create(nil);
  11.   Try
  12.     Client.AllowRedirect:= true;
  13.     Client.RequestHeaders.Add('Content-Type: application/json');
  14.     Client.RequestHeaders.Add('Authorization: Bearer '+API_KEY); // replace API_KEY with yours, see above
  15.     writeln(Client.Get('https://api.openai.com/v1/models/text-davinci-003'));
  16.     Client.RequestBody:=TStringStream.Create(model);   // This was the culprit
  17.     writeln(Client.Post('https://api.openai.com/v1/completions'));    
  18.   finally
  19.     Client.RequestBody.Free;
  20.     Client.Free;
  21.   end;
  22. end.

Well, needs some beautification for the output, but we are getting there.
The output is valid and correct, see the last line:
Code: Bash  [Select][+][-]
  1.   "permission": [
  2.     {
  3.       "id": "modelperm-Dtl0tncKKco7k8ccFSZgdUA5",
  4.       "object": "model_permission",
  5.       "created": 1671664268,
  6.       "allow_create_engine": false,
  7.       "allow_sampling": true,
  8.       "allow_logprobs": true,
  9.       "allow_search_indices": false,
  10.       "allow_view": true,
  11.       "allow_fine_tuning": false,
  12.       "organization": "*",
  13.       "group": null,
  14.       "is_blocking": false
  15.     }
  16.   ],
  17.   "root": "text-davinci-003",
  18.   "parent": null
  19. }
  20.  
  21. {"id":"cmpl-6Qd8mRpAVR1rww75XNVAAwnrRitTh","object":"text_completion","created":1671805004,"model":"text-davinci-003","choices":[{"text":"\n\nThis is indeed a test","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":5,"completion_tokens":7,"total_tokens":12}}
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 04:54:44 pm
I have tested some more stuff after spending half a day getting it to work. It all works if you prepare the POST correctly.
I wasn't aware of that OpenAI but it is really interesting. Think I will do some more experiments.

Note that I prefer my pure Pascal solution over TProcess and curl.
(curl could have been done with libcurl instead of TProcess, btw. I did not fix that for Windows for nothing....  O:-) :) )
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 23, 2022, 05:26:13 pm
Wow thank you so much for your work! I am new to the forum and overwhelmed by the help I get here! :o

I still have a (hopefully) small problem to get your code to run...

I don't have a console because I'm using a GUI project so I want to output the answer by label.

but i only get the following text as answer. This does not contain the answer to the question (So I only get one answer in label 1). Also, with label2 I always get the error "Stream read Error". I am really new to Lazarus and I would be very happy if I could get it to run.

Code: Pascal  [Select][+][-]
  1. {
  2.   "id": "text-davinci-003",
  3.   "object": "model",
  4.   "created": 1669599635,
  5.   "owned_by": "openai-internal",
  6.   "permission": [
  7.     {
  8.       "id": "modelperm-Dtl0tncKKco7k8ccFSZgdUA5",
  9.       "object": "model_permission",
  10.       "created": 1671664268,
  11.       "allow_create_engine": false,
  12.       "allow_sampling": true,
  13.       "allow_logprobs": true,
  14.       "allow_search_indices": false,
  15.       "allow_view": true,
  16.       "allow_fine_tuning": false,
  17.       "organization": "*",
  18.       "group": null,
  19.       "is_blocking": false
  20.     }
  21.   ],
  22.   "root": "text-davinci-003",
  23.   "parent": null
  24. }
  25.  

Here is the code used:

Code: Pascal  [Select][+][-]
  1.  
  2. uses classes, fphttpclient, opensslsockets;
  3. const
  4.     API_KEY='Custom_API-Key';
  5.     model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  6.   var
  7.     Client:TfpHttpClient;
  8.     Body:TStringStream;
  9.   begin
  10.     Client :=TfpHttpClient.Create(nil);
  11.     Body :=TStringStream.Create;
  12.     Body.Write(Model,Length(model));
  13.     Try :(
  14.       Client.AllowRedirect:= true;
  15.       Client.RequestHeaders.Add('Content-Type: application/json');
  16.       Client.RequestHeaders.Add('Authorization: Bearer '+API_KEY); // replace API_KEY with yours, see above
  17.       Label1.Caption:=(Client.Get('https://api.openai.com/v1/models/text-davinci-003'));
  18.       Client.RequestBody:=Body;
  19.       Label2.Caption:=(Client.Post('https://api.openai.com/v1/completions'));
  20.     finally
  21.      Body.Free;
  22.      Client.Free;
  23.     end;
  24.   end;      

Thanks again to all for your help!

Quote
I wasn't aware of that OpenAI but it is really interesting.
Their work is truly breathtaking!
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 05:54:58 pm
Well, I am a server guy and do not much in user interfacing, but I am sure someone here can translate my code into a button click using the TfpHTTPclient component and fpJson for formatting... Indeed it is a small problem, very small.  :D :)
I can do that too of course, but enough for today.
It works and the logic works for the entire API and with any model.

Tnx for the fun day! Merry Christmas.

(Note that I edited the code somewhat to less lines)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 23, 2022, 07:10:40 pm
Thank you so much for your work! I also wish you Merry Christmas.

I have no idea why, but the code works now :)
If anyone is interested, that would be the code which prints the API response in a label when a button is pressed:

Code: Pascal  [Select][+][-]
  1. uses
  2. classes, SysUtils, Forms, fphttpclient, opensslsockets;
  3.  
  4. procedure TForm1.Button1Click(Sender: TObject);
  5.  
  6. const
  7.   API_KEY='Custom_API-Key';
  8.   model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  9.  
  10. var
  11.   Client:TfpHttpClient;
  12.  
  13. begin
  14.   Client :=TfpHttpClient.Create(nil);
  15.   Try
  16.     Client.AllowRedirect:= true;
  17.     Client.RequestHeaders.Add('Content-Type: application/json');
  18.     Client.RequestHeaders.Add('Authorization: Bearer '+API_KEY); // replace API_KEY with yours, see above
  19.     Client.RequestBody:=TStringStream.Create(model);
  20.     Label1.Caption:=(Client.Post('https://api.openai.com/v1/completions'));
  21.  
  22.   finally
  23.     Client.RequestBody.Free;
  24.     Client.Free;
  25.  
  26.   end;
  27. end;    
  28.  

This code outputs the following:
Code: Pascal  [Select][+][-]
  1. {"id":"cmpl-6QgmYn44ANDSuOQDBjdaXeutlYRmq","object":"text_completion","created":1671819002,"model":"text-davinci-003","choices":[{"text":"\n\nThis is indeed a test","index":0,"logprobs":null,"finish_reason":"length"}],"usage":{"prompt_tokens":5,"completion_tokens":7,"total_tokens":12}}
  2.  

Now my last request would be to print only the pure response text, so in this case "This is indeed a Test".

If someone knows how this could work I would appreciate your advice. I will try to figure it out and keep you updated.

Thanks to all.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 23, 2022, 07:27:48 pm
That is simple with fpjson. I leave that to you as an excersice. :o

Of course the documentation contains an example:
https://www.freepascal.org/docs-html/current/fcl/fpjson/index.html

Spoiler: the trick is in the findpath.
You seem quite capable of solving that.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Simiba7 on December 23, 2022, 11:17:29 pm
Hooray! It works like this! Including the paragraphs! :)

I spent the last hours trying to figure out how, but now it works with the following code:

Code: Pascal  [Select][+][-]
  1. uses
  2. classes, SysUtils, Forms, fphttpclient, opensslsockets, fpJSON, jsonparser;
  3.  
  4.  
  5. procedure TForm1.Button1Click(Sender: TObject);
  6.  
  7. const
  8.   API_KEY='Custom_API-Key';
  9.   model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  10.  
  11. var
  12.   Client:TfpHttpClient;
  13.   JSON_STRING: AnsiString;
  14.   JSON_OBJECT: TJSONObject;  
  15.  
  16. begin
  17.   Client :=TfpHttpClient.Create(nil);
  18.   Try
  19.     Client.AllowRedirect:= true;
  20.     Client.RequestHeaders.Add('Content-Type: application/json');
  21.     Client.RequestHeaders.Add('Authorization: Bearer '+API_KEY); // replace API_KEY with yours, see above
  22.     Client.RequestBody:=TStringStream.Create(model);
  23.     JSON_STRING:=(Client.Post('https://api.openai.com/v1/completions'));
  24.     JSON_OBJECT := TJSONObject(GetJSON(JSON_STRING));
  25.     Label1.Caption:=(JSON_OBJECT.FindPath('choices[0].text').AsString);
  26.  
  27.   finally
  28.     Client.RequestBody.Free;
  29.     Client.Free;
  30.  
  31.   end;
  32. end;  

(strangely it hangs in lazarus when testing, but when I run the .exe file in the project folder it works...)  %)

Thanks to all for your time and effort, enjoy the holidays!  :D
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 09:04:48 am
Here's a version with response formatting:
Code: Pascal  [Select][+][-]
  1. program fpopenai_4;
  2. {
  3.   Demo on how to use openai in Freepascal
  4.   Find out more at https://openai.com where you can also obtain a key.
  5.   Put the key in a file called openai.key surrounded by single quotes.
  6.  
  7.   Enjoy, Thaddy de Koning, 24 december 2022
  8. }  
  9. {$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}{$H+}
  10. uses classes, fphttpclient,opensslsockets,fpJson, jsonparser;
  11. const
  12.   model ='{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}';
  13. var
  14.   d:TJsonData;
  15. begin
  16.   with TfpHttpClient.Create(nil) do
  17.   Try
  18.     AllowRedirect:= true;
  19.     RequestHeaders.Add('Content-Type: application/json');
  20.     // put your key with single quotes in a textfile called openai.key
  21.     RequestHeaders.Add('Authorization: Bearer '+{$I openai.key});
  22.     writeln(Get('https://api.openai.com/v1/models/text-davinci-003'));
  23.     RequestBody:=TStringStream.Create(model);    
  24.     try
  25.       d:=GetJson(Post('https://api.openai.com/v1/completions'));
  26.       writeln(d.FormatJson);
  27.     finally
  28.       d.free;
  29.     end;    
  30.   finally
  31.     RequestBody.Free;
  32.     Free;
  33.   end;
  34. end.

I am also busy experimenting with the codex model.
With that you can use AI to translate from one programming language to another language  :o ;D
In this case Pascal to Haskell .. :-[
See image.

What you see is the following:
Instruct the model in natural language to translate a given Pascal program into Haskell.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 10:20:35 am
Here is an openai model that writes a Pascal program that calculates what the distance is between the earth and the moon today.
Natural language input, not a default example but a request that just came to mind:
 "write a program in pascal that calculates the distance between the earth and the moon today":
Code: [Select]
'{"model": "text-davinci-003",  "prompt": "write a program in pascal that calculates the distance between the earth and the moon today","temperature": 0.7,"max_tokens": 256,"top_p": 1,  "frequency_penalty": 0,  "presence_penalty": 0}';
The model output is this program:
Code: Pascal  [Select][+][-]
  1. program Distance_Earth_Moon;
  2. { program to calculate the distance between the earth and the moon today }
  3. uses sysutils,dateutils, math; // only manual addition
  4. const
  5.   AVERAGE_EARTH_MOON_DISTANCE = 384400; { km }
  6.  
  7. var
  8.   TodayEarthMoonDistance: Real;
  9.  
  10. begin
  11.   TodayEarthMoonDistance := AVERAGE_EARTH_MOON_DISTANCE * (1 + 0.0167 * Cos(360 * DaysBetween(Now, Date) / 27.321661));
  12.   Writeln('The distance between the earth and the moon today is: ', TodayEarthMoonDistance:0:2, ' km');
  13. end.
I just had to
- escape some single quotes in the Json response, since single quotes are not escaped in Json.
- add the uses clause by hand. The rest of the program is machine generated.

Pretty impressive!


Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on December 24, 2022, 11:41:40 am
*snip*

Pretty impressive!
Yes, it is. At first.
But playing about half an hour with ChatGPT is a bit disappointing (or encouraging that the robocalypse hasn't happened yet). 8)

Try asking for a program with a specific constraint e.g.
You can see the latter one is plain wrong.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: wp on December 24, 2022, 11:57:39 am
I repeated Thaddy's request for the earth-moon distance (exactly same model text} and got this non-sense result:
Code: Pascal  [Select][+][-]
  1. program Distance;
  2. {Calculates the distance between Earth and the Moon today}
  3. const
  4.   EarthRadius = 6378.14;  {km}
  5.   MoonRadius = 1738.0;    {km}
  6. var
  7.   EarthToMoonDistance : Real;
  8. begin
  9.   {The distance between Earth and the Moon is calculated as the sum of their radii}
  10.   EarthToMoonDistance := EarthRadius + MoonRadius;
  11.   {Display the result}
  12.   Writeln('The distance between Earth and the Moon today is ', EarthToMoonDistance :0:2, ' km.');
  13.  
  14.   ReadLn;  // wp - added by myself
  15. end.
With an error rate of 1 out of 2, this AI is pretty much useless.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ccrause on December 24, 2022, 12:46:54 pm
With an error rate of 1 out of 2, this AI is pretty much useless.
Or about as useful as a typical first year university/college student  :)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 01:00:58 pm
Well it is still under heavy development, so errors must be expected.
At least it seems to be always valid Pascal. In my opinion it is a nice toy.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: KodeZwerg on December 24, 2022, 03:09:26 pm
At least it seems to be always valid Pascal.
I show you something funny.
Quote
Me: Create a Delphi console application that implements a chatbot
Code: Pascal  [Select][+][-]
  1. program Chatbot;
  2.  
  3. {$APPTYPE CONSOLE}
  4.  
  5. uses
  6.   SysUtils;
  7.  
  8. var
  9.   input: string;
  10.  
  11. begin
  12.   WriteLn('Hello, I am a chatbot. How can I help you today?');
  13.  
  14.   while True do
  15.   begin
  16.     Write('You: ');
  17.     ReadLn(input);
  18.  
  19.     if input = 'exit' then
  20.       Break;
  21.  
  22.     case input of
  23.       'hi', 'hello':
  24.         WriteLn('Chatbot: Hi there! How are you doing?');
  25.       'how are you':
  26.         WriteLn('Chatbot: I am just a computer program, so I don''t have feelings. But I am here to assist you.');
  27.       'what can you do':
  28.         WriteLn('Chatbot: I can answer questions, provide information, and carry out simple tasks. Is there anything specific you would like to know or do?');
  29.       else
  30.         WriteLn('Chatbot: I am sorry, I didn''t understand your question. Could you please rephrase it or ask for something else?');
  31.     end;
  32.   end;
  33. end.
Who find the error first?  :P
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 03:17:52 pm
Delphi does not support string labels in case?
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: KodeZwerg on December 24, 2022, 03:30:32 pm
Delphi does not support string labels in case?
A string is not of ordinal type in Delphi a case is limited to that. So yes, you found the little but massive error  8)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 03:40:24 pm
Note that the engine officially does not support delphi, only pascal.

Here's another chatty one:
input: write an Eliza program in pascal
Code generated:
Code: Pascal  [Select][+][-]
  1. program Eliza;
  2. uses crt;
  3.  
  4. var
  5.     input, response : string;
  6.  
  7. begin
  8.     writeln('Hello! I am Eliza, your virtual therapist. How can I help you?');
  9.     readln(input);
  10.  
  11.     while input <> 'bye' do
  12.     begin
  13.         {randomly select a response for the input}
  14.         case random(4) of
  15.             0 : response := 'Please tell me more about that.';
  16.             1 : response := 'Can you explain more?';
  17.             2 : response := 'How does that make you feel?';
  18.             3 : response := 'Do you think that is a problem?';
  19.         end;
  20.  
  21.         writeln(response);
  22.         readln(input);
  23.     end;
  24.  
  25.     writeln('Goodbye!');
  26. end.

Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: indydev on December 24, 2022, 06:37:41 pm
So glad to see these responses!  I was stuck in an airport and haven't been able to check until now.  As for Pascal code generation. It's hit and miss. This is what I got when I asked it to generate a quiz application in Pascal just in the chat window, no api call (I couldn't get that to work). 

Code: Pascal  [Select][+][-]
  1. program quizzer;
  2.  
  3. {$mode objfpc}{$H+}
  4. uses
  5.         Sysutils, Classes, Crt;
  6.  
  7. type
  8.         TQuizQuestion = record
  9.                 question: string;
  10.                 answers: array[1..4] of string;
  11.                 correctAnswer: char;
  12.                 explanation: string;
  13.         end;
  14.        
  15. const
  16.         NUM_QUESTIONS = 10;    
  17.        
  18. var
  19.         quiz: array[1..NUM_QUESTIONS] of TQuizQuestion;
  20.         i: integer;
  21.         f: TextFile;
  22.         answer: char;
  23.         tryagain: char;
  24.        
  25. Begin
  26.         AssignFile(f, 'quiz.txt');
  27.        
  28.         try
  29.                 Reset(f);
  30.                
  31.                 for i := 1 to NUM_QUESTIONS do
  32.                 begin
  33.                         ReadLn(f, quiz[i].question);
  34.                         ReadLn(f, quiz[i].answers[1]);
  35.                         ReadLn(f, quiz[i].answers[2]);
  36.                         ReadLn(f, quiz[i].answers[3]);
  37.                         ReadLn(f, quiz[i].answers[4]);
  38.                         ReadLn(f, quiz[i].correctAnswer);
  39.                         ReadLn(f, quiz[i].explanation);
  40.                 end;
  41.        
  42.         finally
  43.                 CloseFile(f);
  44.         end;
  45.        
  46.         repeat
  47.                 ClrScr;
  48.                 for i := 1 to NUM_QUESTIONS do
  49.                 begin // Present the question and answers to the user
  50.                         WriteLn(quiz[i].question);
  51.                         WriteLn('1. ', quiz[i].answers[1]);
  52.                         WriteLn('2. ', quiz[i].answers[2]);
  53.                         WriteLn('3. ', quiz[i].answers[3]);
  54.                         WriteLn('4. ', quiz[i].answers[4]);
  55.                        
  56.                         // Get the user's answer
  57.                         Write('Enter your answer: ');
  58.                         ReadLn(answer);
  59.                        
  60.                         // Check the user's answer
  61.                         if answer = quiz[i].correctAnswer then
  62.                         begin
  63.                                 WriteLn('Correct!');
  64.                                 WriteLn('Explanation: ', quiz[i].explanation);
  65.                         end
  66.                         else
  67.                         begin
  68.                                 WriteLn('Incorrect.');
  69.                                 WriteLn('Correct answer: ', quiz[i].correctAnswer);
  70.                                 WriteLn('Explanation: ', quiz[i].explanation);
  71.                         end;
  72.                 end;
  73.                 ClrScr;
  74.                 Write('The Quiz is over. Do you want to try again? (y/n)?');
  75.                 ReadLn(tryagain);
  76.         until tryagain <> 'y'; 
  77.                 ClrScr;
  78.                
  79. End.   
  80.  

The format of your quiz.txt file must be as follows:

Question 1
Answer 1
Answer 2
Answer 3
Answer 4
3 (correct answer)
Explanation for correct answer
Question 2
Answer 1
Answer 2
Answer 3
Answer 4
1 (correct answer)
Explanation for correct answer
Question 3
Answer 1
Answer 2
Answer 3
Answer 4
2 (correct answer)

The correct answer is only a suggestion. Let me know if there is more I can help you with.

-----------------

I added {$mode objfpc}{$H+} compiled it and it ran.

I asked it to write out an Eliza program as well. That was pretty bad. I had to adjust the Respond method so that it would at least close properly. I did this about a week ago. Again, I had to add the compiler directives and I wanted the Crt unit.

Code: Pascal  [Select][+][-]
  1. program Eliza;
  2.  
  3. {$mode objfpc}{$H+}
  4. uses
  5.   SysUtils, Classes, Crt;
  6.  
  7. const
  8.   GREETING = 'Hello! My name is Eliza. How are you feeling today?';
  9.   FAREWELL = 'Thank you for talking with me. Goodbye!';
  10.  
  11. var
  12.   input: string;
  13.  
  14. function GetInput: string;
  15. begin
  16.   write('> ');
  17.   readln(Result);
  18. end;
  19.  
  20. function IsGoodbye(input: string): boolean;
  21. begin
  22.   Result := (input = 'goodbye') or (input = 'bye') or (input = 'quit');
  23. end;
  24.  
  25. procedure Respond(input: string);
  26. begin
  27.   case input of
  28.     'i feel': writeln('Why do you feel that way?');
  29.     'i am': writeln('Why are you feeling that way?');
  30.     'you': writeln('Why do you bring me up?');
  31.     'my': writeln('Tell me more about your situation.');
  32.     'i': writeln('Why do you say that?');
  33.   else
  34.     writeln('Please go on.');
  35.   end;
  36. end;
  37.  
  38. begin
  39.   ClrScr;
  40.   writeln(GREETING);
  41.   repeat
  42.     input := GetInput;
  43.     Respond(Lowercase(input));
  44.   until IsGoodbye(Lowercase(input));
  45.   writeln(FAREWELL);
  46.   readln;
  47. end.
  48.  

Thanks to Thaddy for getting the api working. I also want to try and use codex. Getting to the api functionality now...
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 24, 2022, 11:11:00 pm
OpenAI seems to have a user affinity.
That can explain the differences between the exact same models.
I was really impressed with the Eliza one. I have written many Eliza's, every so often, for educational purposes, but that one was certainly better than my first..thirthiest attempts back in the late 70's till late 80's.
@wp
https://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors#Modern_methods
So that code suits your interests? I may be very wrong of course, just like many of the models are....
But that code seems correct in that context.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 25, 2022, 04:18:35 pm
Follow uuuuup again:
Code: Pascal  [Select][+][-]
  1. program fpopenai_5;
  2. {
  3.   Demo on how to use openai in Freepascal
  4.   Find out more at https://openai.com where you can also obtain a key.
  5.   Put the key in a file called openai.key surrounded by single quotes.
  6.  
  7.   Enjoy, Thaddy de Koning, 25 december 2022
  8. }  
  9. {$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}{$H+}
  10. uses classes, fphttpclient,opensslsockets,fpJson, jsonparser;
  11. const
  12.   model ='{"model": "text-davinci-003",  "prompt": "write an anagram generator in Pascal","temperature": 0.7,"max_tokens": 2048,"top_p": 1,  "frequency_penalty": 0,  "presence_penalty": 0}';
  13. var
  14.   d:TJsonData;
  15. begin
  16.   with TfpHttpClient.Create(nil) do
  17.   Try
  18.     AllowRedirect:= true;
  19.     RequestHeaders.Add('Content-Type: application/json');
  20.     // put your key with single quotes in a textfile called openai.key
  21.     RequestHeaders.Add('Authorization: Bearer '+{$I openai.key});
  22.     writeln(Get('https://api.openai.com/v1/models/text-davinci-003'));
  23.     RequestBody:=TStringStream.Create(model);    
  24.     try
  25.       d:=GetJson(Post('https://api.openai.com/v1/completions'));
  26.       writeln(jsonstringtostring(d.FormatJson));
  27.     finally
  28.       d.free;
  29.     end;    
  30.   finally
  31.     RequestBody.Free;
  32.     Free;
  33.   end;
  34. end.
The code works crudely but the json output is more usable.
I am currently writing OpenAI studio 0.1 in Lazarus.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 25, 2022, 04:43:32 pm
Now cooking Christmas dinner...
I got this as output:
Code: Pascal  [Select][+][-]
  1. program AnagramGenerator;
  2.  
  3. uses crt;
  4.  
  5. var
  6.   word : string;
  7.   anagram : string;
  8.   i, j : integer;
  9.   ch : char;
  10.  
  11. begin
  12.   clrscr;
  13.   Writeln('Enter a word to generate an anagram:');
  14.   Readln(word);
  15.   anagram := '';
  16.   randomize;
  17.   for i := length(word) downto 1 do
  18.   begin
  19.     j := random(i);
  20.     ch := word[j];
  21.     delete(word, j, 1);
  22.     anagram := anagram + ch;
  23.   end;
  24.   Writeln('Your anagram is: ', anagram);
  25.   Readln;
  26. end.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on December 25, 2022, 06:15:57 pm
Despite the initial "Wow" impression, it raises a numerous controversies.
Quote
Given criticisms of GPT-3’s bias and abusive language patterns, it seems that OpenAI hasn’t found a way to prevent algorithms from inheriting its training data’s worst elements.
On the Dangers of Stochastic Parrots: Can Language Models Be Too Big? (https://dl.acm.org/doi/10.1145/3442188.3445922)
Class-action lawsuit filed against Microsoft's GitHub Copilot for software piracy (https://www.neowin.net/news/class-action-lawsuit-filed-against-microsofts-github-copilot-for-software-piracy/)
GitHub and Copilot Intellectual Property Litigation (https://www.saverilawfirm.com/our-cases/github-copilot-intellectual-property-litigation)

AFAIR there was a discussion in that forum some time ago about GitHub's possible nefarious use of the open source code and perhaps it comes to fruition.
Isn't it that fear one of the reasons to move Laz to Gitlab?
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 25, 2022, 06:49:32 pm
Well, that lawsuit is a bit ridiculous. In my opinion the OpenAI partners are allowed to use open sourcecode to feed their learning models as long as they adhere to the licenses.
Which they do. Frivolous and nothing worth paying attention to.
Happens all the time.
The main guy involved is probably a "better" lawyer than he is as a programmer.
"case dismissed"  ::) No merit.

(did a prep in law way back in 1981 as a second study (propedeuse) because I was bored and passed it with honors, dropped it for a board place in a student organisation. Law is often a second study in the Netherlands, it is easy and only requires lookups and a bit of memorizing, the philosophy part came already with my political science, in parallel and better)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on December 25, 2022, 08:13:12 pm
Aside from the legal stuff, which I admit I'm not well versed in, using a huge amount of code of varying quality is of questionable outcome to say the least.

In my everyday work with a limited aspect of NN (namely ALPR) it is easy to see its peculiarities compared to more traditional methods and to imagine how they can be magnified by using such a mammoth volumes of training data as those into the recent NLP models.

Perhaps the first paper (https://dl.acm.org/doi/10.1145/3442188.3445922) cited is worth reading.

Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: MarkMLl on December 25, 2022, 11:37:20 pm
Aside from the legal stuff, which I admit I'm not well versed in,

The issue appears to be that the "AI" isn't propagating an acceptable synthesis of the licenses stipulated for the code from which it's borrowing.

OK, so has anybody tried the "Star Trek trick" of asking it to evaluate "this statement is false"? Or some heavy maths involving imaginary numbers?

MarkMLl
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on December 26, 2022, 01:05:51 am
I've tried some variations of a simple task. The starting one was:
Q: write a program in pascal which prints Fibonacci numbers in range from 1 to 100
And the answer was:
Code: Pascal  [Select][+][-]
  1. program PrintFibonacci;
  2.  
  3. var
  4.   current, next, count: Integer;  // loop variables
  5.  
  6. begin
  7.   current := 1;  // initialize current to the first Fibonacci number
  8.   next := 1;  // initialize next to the second Fibonacci number
  9.   count := 1;  // initialize count to 1
  10.  
  11.   WriteLn(current);  // print the first Fibonacci number
  12.  
  13.   while count < 100 do  // loop until we have printed 100 Fibonacci numbers
  14.   begin
  15.     WriteLn(next);  // print the next Fibonacci number
  16.     Inc(count);  // increment the count
  17.  
  18.     next := current + next;  // calculate the next Fibonacci number
  19.     current := next - current;  // update current to the previous value of next
  20.   end;
  21. end.
  22.  
It will obviously print 100 Fibonacci numbers no matter of the range.

The next one was:
Q: write a program in pascal which prints half of the Fibonacci numbers in range from 1 to 100
The answer was:
Code: Pascal  [Select][+][-]
  1. program PrintHalfFibonacci;
  2.  
  3. var
  4.   current, next, count: Integer;  // loop variables
  5.  
  6. begin
  7.   current := 1;  // initialize current to the first Fibonacci number
  8.   next := 1;  // initialize next to the second Fibonacci number
  9.   count := 1;  // initialize count to 1
  10.  
  11.   WriteLn(current);  // print the first Fibonacci number
  12.  
  13.   while count < Trunc(100 / 2) do  // loop until we have printed half of the desired number of Fibonacci numbers
  14.   begin
  15.     WriteLn(next);  // print the next Fibonacci number
  16.     Inc(count);  // increment the count
  17.  
  18.     next := current + next;  // calculate the next Fibonacci number
  19.     current := next - current;  // update current to the previous value of next
  20.   end;
  21. end.
As it can be seen, it will print 50 numbers, which is 5x 10x times more than needed  (https://www.wolframalpha.com/input?i=how+many+are+fibonacci+numbers+between+1+and+100).

Then:
Q: write a program in pascal which prints first 13 of the prime numbers
Code: Pascal  [Select][+][-]
  1. program PrintPrimes;
  2.  
  3. const
  4.   MAX_PRIMES = 13;  // number of prime numbers to print
  5.  
  6. var
  7.   num, count: Integer;  // loop variables
  8.  
  9. begin
  10.   count := 0;  // initialize count to 0
  11.  
  12.   for num := 2 to MaxInt do  // loop through all positive integers
  13.   begin
  14.     if IsPrime(num) then  // check if the current number is prime
  15.     begin
  16.       WriteLn(num);  // print the prime number
  17.       Inc(count);  // increment the count
  18.     end;
  19.  
  20.     if count = MAX_PRIMES then  // if we have printed the desired number of primes, exit the loop
  21.       Break;
  22.   end;
  23. end.
  24.  
And that one will work.

The last one:
Q: write a program in pascal which prints the first two and the last three of the prime numbers not bigger than 100
Code: Pascal  [Select][+][-]
  1. program PrintPrimeRange;
  2.  
  3. var
  4.   num, count: Integer;  // loop variables
  5.   last_three: array[1..3] of Integer;  // array to store the last three prime numbers
  6.  
  7. begin
  8.   count := 0;  // initialize count to 0
  9.  
  10.   for num := 2 to 100 do  // loop through the range from 2 to 100
  11.   begin
  12.     if IsPrime(num) then  // check if the current number is prime
  13.     begin
  14.       Inc(count);  // increment the count
  15.  
  16.       if count <= 2 then  // if count is less than or equal to 2, print the prime number
  17.         WriteLn(num)
  18.       else  // if count is greater than 2, store the prime number in the last_three array
  19.         last_three[count - 2] := num;
  20.     end;
  21.   end;
  22.  
  23.   for num := 1 to 3 do  // loop through the last_three array and print the stored prime numbers
  24.     WriteLn(last_three[num]);
  25. end.
  26.  
This one will print 2, 3 and give a range error on the 6-th prime, 13.

For me, it is of no use at all. Assuming you should go through every line of the generated code to search for errors, then where is the point?
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 26, 2022, 09:35:07 am
I have used OpenAI chatGPT to answer a topic in another thread:
https://forum.lazarus.freepascal.org/index.php/topic,61711.msg465087.html#msg465087

I was using this slightly better code where you can formulate any request and just returns the answer:
Code: Pascal  [Select][+][-]
  1. program fpopenai_6;
  2. {
  3.   Demo on how to use openai in Freepascal
  4.   Find out more at https://openai.com where you can also obtain a key.
  5.   Put the key in a file called openai.key surrounded by single quotes.
  6.  
  7.   Enjoy, Thaddy de Koning, 26 december 2022
  8. }  
  9. {$mode objfpc}{$ifdef mswindows}{$apptype console}{$endif}{$H+}
  10. uses classes, sysutils,fphttpclient,opensslsockets,fpJson, jsonparser;
  11. const
  12.   model ='{"model": "text-davinci-003",  "prompt": "%s","temperature": 0.7,"max_tokens": 2048,"top_p": 1,  "frequency_penalty": 0,  "presence_penalty": 0}';
  13. var
  14.   d:TJsonData;
  15.   s:string;
  16. begin
  17.   writeln('What is your request?');
  18.   readln(s);
  19.   writeln;
  20.   with TfpHttpClient.Create(nil) do
  21.   Try
  22.     AllowRedirect:= true;
  23.     RequestHeaders.Add('Content-Type: application/json');
  24.     // put your key with single quotes in a textfile called openai.key
  25.     RequestHeaders.Add('Authorization: Bearer '+{$I openai.key});
  26.     RequestBody:=TStringStream.Create(format(model,[s]));    
  27.     writeln('Please wait for the response, this can take some time:');
  28.     try
  29.       d:=GetJson(Post('https://api.openai.com/v1/completions'));
  30.       writeln(d.findpath('choices[0].text').AsString);
  31.     finally
  32.       d.free;
  33.     end;    
  34.   finally
  35.     RequestBody.Free;
  36.     Free;
  37.   end;
  38. end.
Code: [Select]
What is your question?
write a pascal function that returns the inverse hyperbolic cosequant

Please wait for the response, this can take some time:


Function InverseHyperbolicCosecant(x : Real): Real;
Begin
    Result := ArcCosh(1/x);
End;

The model can give different responses for the same request...
Try to make the same request more than once...
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 26, 2022, 11:55:56 am
You can also ask the model to give multiple solutions like here:
Code: Bash  [Select][+][-]
  1. What is your request?
  2. write three pascal programs that solve the knapsack problem in three different ways
  3.  
  4. Please wait for the response, this can take some time:
  5.  
  6.  
  7. //Solution 1: Dynamic Programming
  8.  
  9. program Knapsack;
  10.  
  11. const
  12.   MAXWEIGHT = 100;
  13.   MAXITEMS = 10;
  14.  
  15. type
  16.   Item = record
  17.     weight, value : integer;
  18.   end;
  19.  
  20. var
  21.   items : array[1..MAXITEMS] of Item;
  22.   maxval : array[0..MAXWEIGHT] of integer;
  23.   numitems, weight : integer;
  24.   i, w : integer;
  25.  
  26. begin
  27.   // Read data
  28.   writeln('How many items?');
  29.   readln(numitems);
  30.   for i := 1 to numitems do
  31.     begin
  32.       writeln('Enter weight and value of item ', i);
  33.       readln(items[i].weight, items[i].value);
  34.     end;
  35.   writeln('Maximum weight?');
  36.   readln(weight);
  37.  
  38.   // Initialize maxval array
  39.   maxval[0] := 0;
  40.   for w := 1 to weight do
  41.     maxval[w] := -1;
  42.  
  43.   // Calculate maximum value
  44.   for i := 1 to numitems do
  45.     for w := weight downto 0 do
  46.       if (items[i].weight <= w) and (maxval[w - items[i].weight] >= 0) then
  47.         if maxval[w] < 0 then
  48.           maxval[w] := maxval[w - items[i].weight] + items[i].value
  49.         else
  50.           maxval[w] := maxval[w] + maxval[w - items[i].weight] + items[i].value;
  51.  
  52.   // Show result
  53.   writeln('Maximum value = ', maxval[weight]);
  54. end.
  55.  
  56.  
  57. //Solution 2: Greedy Algorithm
  58.  
  59. program Knapsack;
  60.  
  61. const
  62.   MAXWEIGHT = 100;
  63.   MAXITEMS = 10;
  64.  
  65. type
  66.   Item = record
  67.     weight, value : integer;
  68.     ratio : real;
  69.   end;
  70.  
  71. var
  72.   items : array[1..MAXITEMS] of Item;
  73.   maxval : array[0..MAXWEIGHT] of integer;
  74.   numitems, weight : integer;
  75.   i, w : integer;
  76.  
  77. function cmp(i1, i2 : integer) : boolean;
  78. begin
  79.   cmp := items[i1].ratio > items[i2].ratio;
  80. end;
  81.  
  82. begin
  83.   // Read data
  84.   writeln('How many items?');
  85.   readln(numitems);
  86.   for i := 1 to numitems do
  87.     begin
  88.       writeln('Enter weight and value of item ', i);
  89.       readln(items[i].weight, items[i].value);
  90.       items[i].ratio := items[i].value / items[i].weight;
  91.     end;
  92.   writeln('Maximum weight?');
  93.   readln(weight);
  94.  
  95.   // Sort items by ratio
  96.   for i := 1 to numitems - 1 do
  97.     for j := i + 1 to numitems do
  98.       if cmp(j, i) then
  99.         begin
  100.           items[0] := items[i];
  101.           items[i] := items[j];
  102.           items[j] := items[0];
  103.         end;
  104.  
  105.   // Calculate maximum value
  106.   maxval[0] := 0;
  107.   for i := 1 to numitems do
  108.     for w := weight downto 0 do
  109.       if (items[i].weight <= w) and (maxval[w - items[i].weight] >= 0) then
  110.         maxval[w] := maxval[w] + items[i].value;
  111.  
  112.   // Show result
  113.   writeln('Maximum value = ', maxval[weight]);
  114. end.
  115.  
  116.  
  117. //Solution 3: Branch and Bound
  118.  
  119. program Knapsack;
  120.  
  121. const
  122.   MAXWEIGHT = 100;
  123.   MAXITEMS = 10;
  124.  
  125. type
  126.   Item = record
  127.     weight, value : integer;
  128.     ratio : real;
  129.   end;
  130.  
  131. var
  132.   items : array[1..MAXITEMS] of Item;
  133.   maxval : array[0..MAXWEIGHT] of integer;
  134.   numitems, weight : integer;
  135.   i, w : integer;
  136.  
  137. function cmp(i1, i2 : integer) : boolean;
  138. begin
  139.   cmp := items[i1].ratio > items[i2].ratio;
  140. end;
  141.  
  142. procedure branch_and_bound(i, w : integer; curval : integer);
  143. begin
  144.   if i > numitems then
  145.     begin
  146.       if curval > maxval[w] then
  147.         maxval[w] := curval;
  148.       exit;
  149.     end;
  150.   if (items[i].weight <= w) and (curval + maxval[w - items[i].weight] > maxval[w]) then
  151.     begin
  152.       branch_and_bound(i + 1, w, curval);
  153.       branch_and_bound(i + 1, w - items[i].weight, curval + items[i].value);
  154.     end;
  155. end;
  156.  
  157. begin
  158.   // Read data
  159.   writeln('How many items?');
  160.   readln(numitems);
  161.   for i := 1 to numitems do
  162.     begin
  163.       writeln('Enter weight and value of item ', i);
  164.       readln(items[i].weight, items[i].value);
  165.       items[i].ratio := items[i].value / items[i].weight;
  166.     end;
  167.   writeln('Maximum weight?');
  168.   readln(weight);
  169.  
  170.   // Sort items by ratio
  171.   for i := 1 to numitems - 1 do
  172.     for j := i + 1 to numitems do
  173.       if cmp(j, i) then
  174.         begin
  175.           items[0] := items[i];
  176.           items[i] := items[j];
  177.           items[j] := items[0];
  178.         end;
  179.  
  180.   // Initialize maxval array
  181.   maxval[0] := 0;
  182.   for w := 1 to weight do
  183.     maxval[w] := -1;
  184.  
  185.   // Calculate maximum value
  186.   branch_and_bound(1, weight, 0);
  187.  
  188.   // Show result
  189.   writeln('Maximum value = ', maxval[weight]);
  190. end.
Now you should be impressed.. ;D
Seems a perfect way to not have to answer the recurring requests for help that can be identified as homework....
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 26, 2022, 12:12:30 pm
Or these two moonlander games (inspired by the first game I wrote in BASIC on a Burroughs terminal in 1979).
Code: Text  [Select][+][-]
  1. What is your request?
  2. write two pascal programs that implement a moonlander game in two different ways
  3.  
  4. Please wait for the response, this can take some time:
  5.  
  6.  
  7. 1. Program to Implement a Moonlander Game Using a While Loop
  8.  
  9. program MoonlanderGame;
  10.  
  11. var
  12.   fuel, velocity, altitude : real;
  13.   done : boolean;
  14.  
  15. begin
  16.   done := false;
  17.   altitude := 1000;
  18.   fuel := 50;
  19.   velocity := 0;
  20.  
  21.   writeln('Welcome to Moonlander!');
  22.   writeln('You have 50 units of fuel to land your lunar module on the moon.');
  23.   writeln('Good luck!');
  24.  
  25.   while not done do
  26.   begin
  27.     writeln('Altitude = ', altitude:6:2, 'Velocity = ', velocity:6:2, 'Fuel = ', fuel:6:2);
  28.     writeln('Enter 1 to fire thruster, 0 to skip: ');
  29.     if (readkey = '1') then
  30.     begin
  31.       if (fuel > 0) then
  32.       begin
  33.         fuel := fuel - 1;
  34.         velocity := velocity + 1;
  35.         altitude := altitude - velocity;
  36.       end
  37.       else
  38.         writeln('Out of fuel!');
  39.     end
  40.     else
  41.       altitude := altitude - velocity;
  42.  
  43.     if (altitude <= 0) then
  44.       done := true;
  45.   end;
  46.  
  47.   if (velocity = 0) then
  48.     writeln('Landed safely!')
  49.   else
  50.     writeln('Crashed!');
  51. end.
  52.  
  53. 2. Program to Implement a Moonlander Game Using a Repeat-Until Loop
  54.  
  55. program MoonlanderGame;
  56.  
  57. var
  58.   fuel, velocity, altitude : real;
  59.  
  60. begin
  61.   altitude := 1000;
  62.   fuel := 50;
  63.   velocity := 0;
  64.  
  65.   writeln('Welcome to Moonlander!');
  66.   writeln('You have 50 units of fuel to land your lunar module on the moon.');
  67.   writeln('Good luck!');
  68.  
  69.   repeat
  70.     writeln('Altitude = ', altitude:6:2, 'Velocity = ', velocity:6:2, 'Fuel = ', fuel:6:2);
  71.     writeln('Enter 1 to fire thruster, 0 to skip: ');
  72.     if (readkey = '1') then
  73.     begin
  74.       if (fuel > 0) then
  75.       begin
  76.         fuel := fuel - 1;
  77.         velocity := velocity + 1;
  78.         altitude := altitude - velocity;
  79.       end
  80.       else
  81.         writeln('Out of fuel!');
  82.     end
  83.     else
  84.       altitude := altitude - velocity;
  85.   until (altitude <= 0);
  86.  
  87.   if (velocity = 0) then
  88.     writeln('Landed safely!')
  89.   else
  90.     writeln('Crashed!');
  91. end.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on December 26, 2022, 04:36:19 pm
And even christmas dinner (Yes, we have duck from the Kamado on second christmas day):
Code: [Select]
What is your request?
Can you give me a recipe to cook a whole duck on the Kamado? I prefer an orange sauce and plenty of garlic.

Please wait for the response, this can take some time:


Ingredients:

1 whole duck

1 orange

2 cloves garlic, minced

1 teaspoon ground ginger

1 teaspoon ground cinnamon

1 teaspoon ground nutmeg

2 tablespoons olive oil

Salt and pepper to taste

Directions:

1. Preheat the Kamado grill to 350 degrees F.

2. Rinse the duck and pat dry with paper towels.

3. Rub the duck with the olive oil and season with salt and pepper.

4. Place the duck on the grill and cook for 1 hour and 15 minutes, flipping every 15 minutes.

5. Meanwhile, in a medium saucepan, combine the orange juice, garlic, ginger, cinnamon, and nutmeg. Bring to a simmer over medium heat and cook until reduced by half.

6. Remove the duck from the grill and transfer to a cutting board. Let rest for 10 minutes before carving.

7. Serve the duck alongside the orange sauce and garlic. Enjoy!
The recipe is good, but I still use my own twist.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: avra on January 02, 2023, 03:19:36 pm
When I enter
Quote
create pascal source code example for socketcan
into
Quote
https://chat.openai.com/chat
I get this almost working code:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2.  
  3. uses
  4.   Classes, SysUtils, Sockets, can;
  5.  
  6. var
  7.   sock: LongInt;
  8.   ifr: TIfReq;
  9.   addr: TSockAddrCAN;
  10.   frame: TCanFrame;
  11.   nbytes: LongInt;
  12. begin
  13.   // Create a socket
  14.   sock := fpsocket(PF_CAN, SOCK_RAW, CAN_RAW);
  15.   if sock < 0 then
  16.   begin
  17.     raise Exception.Create('Error creating socket');
  18.     exit;
  19.   end;
  20.  
  21.   // Bind the socket to a CAN interface
  22.   StrPCopy(ifr.ifr_name, 'can0');
  23.   fpsioctl(sock, SIOCGIFINDEX, @ifr);
  24.  
  25.   addr.can_family := AF_CAN;
  26.   addr.can_ifindex := ifr.ifr_ifindex;
  27.   if fpsocket(sock, SOCK_RAW, PF_CAN, @addr, SizeOf(addr)) < 0 then
  28.   begin
  29.     raise Exception.Create('Error binding socket to interface');
  30.     exit;
  31.   end;
  32.  
  33.   // Build the CAN frame
  34.   frame.can_id := 0x123;
  35.   frame.can_dlc := Length('Hello, world!');
  36.   Move('Hello, world!', frame.data[0], frame.can_dlc);
  37.  
  38.   // Send the frame
  39.   nbytes := fpsend(sock, @frame, SizeOf(frame), 0);
  40.   if nbytes < 0 then
  41.   begin
  42.     raise Exception.Create('Error sending frame');
  43.     exit;
  44.   end;
  45.  
  46.   WriteLn('Frame sent successfully');
  47.  
  48.   // Close the socket
  49.   fpclose(sock);
  50. end.
  51.  

This is crazy. My SocketCAN lib did not get into official repo yet. This forum is the only place where you can find any pascal SocketCAN code, and it was not a translation from some other language to pascal because it uses exact names of the types and units I used.

Big brother is watching...  :o
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: MarkMLl on January 02, 2023, 03:30:48 pm
This is crazy. My SocketCAN lib did not get into official repo yet. This forum is the only place where you can find any pascal SocketCAN code,

The really interesting thing there is whether it would respect the robots=noindex tag.

It's probably too late to find out.

MarkMLl
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 02, 2023, 03:37:53 pm
Different CAN, same question:
Code: Text  [Select][+][-]
  1. program SocketCAN;
  2.  
  3. uses
  4.   SysUtils,
  5.   SocketCAN;
  6.  
  7. // create a socket to use
  8. var
  9.   Socket: TSocketCAN;
  10.  
  11. // create a message to send
  12. var
  13.   SendMsg: TMsgCAN;
  14.   SendData: array[0..7] of Byte;
  15.  
  16. // create a message to receive
  17. var
  18.   RecvMsg: TMsgCAN;
  19.   RecvData: array[0..7] of Byte;
  20.  
  21. // setup the message to send
  22. SendMsg.ID := $100;
  23. SendMsg.DLC := 8;
  24. for i := 0 to 7 do
  25.   SendData[i] := i;
  26. SendMsg.Data := @SendData;
  27.  
  28. // open the socket
  29. Socket := TSocketCAN.Create;
  30. Socket.Open('vcan0');
  31.  
  32. // send the message
  33. Socket.SendMsg(@SendMsg);
  34.  
  35. // receive the message
  36. Socket.ReceiveMsg(@RecvMsg);
  37.  
  38. // save the received data
  39. for i := 0 to 7 do
  40.   RecvData[i] := RecvMsg.Data[i];
  41.  
  42. // close the socket
  43. Socket.Close;
  44.  
  45. // print the received data
  46. for i := 0 to 7 do
  47.   Writeln(IntToHex(RecvData[i], 2));
  48.  
  49. end.
needs more work.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: mika on January 02, 2023, 06:18:45 pm
Can AI write program in Pascal that produces compiler internal error? Answer will give away where from AI have learned that.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: korba812 on January 02, 2023, 10:37:26 pm
When I enter
Quote
create pascal source code example for socketcan
into
Quote
https://chat.openai.com/chat
I get this almost working code:
Code: Pascal  [Select][+][-]
  1. {$mode objfpc}{$H+}
  2.  
  3. uses
  4.   Classes, SysUtils, Sockets, can;
  5.  
  6. var
  7.   sock: LongInt;
  8.   ifr: TIfReq;
  9.   addr: TSockAddrCAN;
  10.   frame: TCanFrame;
  11.   nbytes: LongInt;
  12. begin
  13.   // Create a socket
  14.   sock := fpsocket(PF_CAN, SOCK_RAW, CAN_RAW);
  15.   if sock < 0 then
  16.   begin
  17.     raise Exception.Create('Error creating socket');
  18.     exit;
  19.   end;
  20.  
  21.   // Bind the socket to a CAN interface
  22.   StrPCopy(ifr.ifr_name, 'can0');
  23.   fpsioctl(sock, SIOCGIFINDEX, @ifr);
  24.  
  25.   addr.can_family := AF_CAN;
  26.   addr.can_ifindex := ifr.ifr_ifindex;
  27.   if fpsocket(sock, SOCK_RAW, PF_CAN, @addr, SizeOf(addr)) < 0 then
  28.   begin
  29.     raise Exception.Create('Error binding socket to interface');
  30.     exit;
  31.   end;
  32.  
  33.   // Build the CAN frame
  34.   frame.can_id := 0x123;
  35.   frame.can_dlc := Length('Hello, world!');
  36.   Move('Hello, world!', frame.data[0], frame.can_dlc);
  37.  
  38.   // Send the frame
  39.   nbytes := fpsend(sock, @frame, SizeOf(frame), 0);
  40.   if nbytes < 0 then
  41.   begin
  42.     raise Exception.Create('Error sending frame');
  43.     exit;
  44.   end;
  45.  
  46.   WriteLn('Frame sent successfully');
  47.  
  48.   // Close the socket
  49.   fpclose(sock);
  50. end.
  51.  

This is crazy. My SocketCAN lib did not get into official repo yet. This forum is the only place where you can find any pascal SocketCAN code, and it was not a translation from some other language to pascal because it uses exact names of the types and units I used.

Big brother is watching...  :o
I don't think the AI wrote it himself. It looks similar:
https://github.com/speedbyte/llcf/blob/9565eaab6eaf7af5ea3dbf094d05d0bc252e15f3/llcf_src_vw/src/test/tst-raw-sendto-SingStream.c
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: avra on January 03, 2023, 08:53:26 pm
I don't think the AI wrote it himself. It looks similar:
https://github.com/speedbyte/llcf/blob/9565eaab6eaf7af5ea3dbf094d05d0bc252e15f3/llcf_src_vw/src/test/tst-raw-sendto-SingStream.c
You are right. My simple demos have C origins so that might be the answer. It still amazes me how it named structures on the fly in pascal fashion.

I wanted to check it, so I remembered that I have made 2 unique socketcan utilities which exist only in pascal and have no C counter part that I know of, and I instructed AI to generate code similar to one of them (hlcanerrdump):

Quote
Q: write pascal code to check errors in socketcan messages and display their textual meaning
Quote
A: To check for errors in SocketCAN messages and display their textual meaning in Pascal, you can use the following code:
Code: Pascal  [Select][+][-]
  1. uses
  2.   ..., // Include any necessary units here
  3.   SocketCAN;
  4.  
  5. const
  6.   // Define an array of error codes and their corresponding textual meanings
  7.   ERROR_CODES: array[0..15] of string = (
  8.     'No Error',
  9.     'Transmission request failed',
  10.     'Lost arbitration',
  11.     'Controller problems',
  12.     'Protocol violation',
  13.     'Transceiver status',
  14.     'No acknowledge on transmission',
  15.     'Software errors',
  16.     'CAN error passive',
  17.     'Controller restarted',
  18.     'Taken into operation',
  19.     'Left operation',
  20.     'CAN error warning',
  21.     'Protocol error in data field',
  22.     'Protocol error in transmission',
  23.     'Transceiver not available'
  24.   );
  25.  
  26. var
  27.   message: TSockCANMessage;
  28.   errorCode: Byte;
  29. begin
  30.   // Read the message from the SocketCAN interface
  31.   ReadSocketCANMessage(message);
  32.  
  33.   // Check the error code in the message
  34.   errorCode := message.ErrorCode;
  35.   if (errorCode > 0) and (errorCode <= 15) then
  36.   begin
  37.     // If an error is detected, display the corresponding textual meaning
  38.     writeln('Error detected: ', ERROR_CODES[errorCode]);
  39.   end;
  40. end.
Quote
This code defines an array of error codes and their corresponding textual meanings, and then reads a message from the SocketCAN interface using the ReadSocketCANMessage function. It then checks the error code in the message and, if an error is detected, displays the corresponding textual meaning.

I hope this helps! Let me know if you have any questions.

Ok, that was very rudimentary, so I spiced it a little...

Quote
Q: do it again but using TxTimeout, LostArbitration and other individual bits
Quote
A: To check for specific errors in SocketCAN messages using individual bits and display their textual meanings in Pascal, you can use the following code:
Code: Pascal  [Select][+][-]
  1. uses
  2.   ..., // Include any necessary units here
  3.   SocketCAN;
  4.  
  5. const
  6.   // Define an array of error codes and their corresponding textual meanings
  7.   ERROR_CODES: array[0..7] of string = (
  8.     'No Error',
  9.     'Transmission request failed',
  10.     'Lost arbitration',
  11.     'Controller problems',
  12.     'Protocol violation',
  13.     'Transceiver status',
  14.     'No acknowledge on transmission',
  15.     'Software errors'
  16.   );
  17.  
  18. var
  19.   message: TSockCANMessage;
  20.   errorCode: Byte;
  21. begin
  22.   // Read the message from the SocketCAN interface
  23.   ReadSocketCANMessage(message);
  24.  
  25.   // Check the individual bits in the error code
  26.   if (message.ErrorCode and SocketCAN_ErrorFlag_TxTimeout) <> 0 then
  27.     writeln('Error detected: Transmission timeout');
  28.   if (message.ErrorCode and SocketCAN_ErrorFlag_LostArbitration) <> 0 then
  29.     writeln('Error detected: Lost arbitration');
  30.   if (message.ErrorCode and SocketCAN_ErrorFlag_ControllerProblems) <> 0 then
  31.     writeln('Error detected: Controller problems');
  32.   // Check the other individual bits as needed
  33.  
  34.   // Check the general error code as a fallback
  35.   errorCode := message.ErrorCode and $0F;
  36.   if (errorCode > 0) and (errorCode <= 7) then
  37.   begin
  38.     // If an error is detected, display the corresponding textual meaning
  39.     writeln('Error detected: ', ERROR_CODES[errorCode]);
  40.   end;
  41. end.
Quote
This code defines an array of general error codes and their corresponding textual meanings, and then reads a message from the SocketCAN interface using the ReadSocketCANMessage function. It then checks the individual bits in the error code to detect specific errors, and displays the corresponding textual meaning. If no specific error is detected, it falls back to checking the general error code and, if an error is detected, displays the corresponding textual meaning.

I hope this helps! Let me know if you have any questions.

Still not even close to hlcanerrdump, but it built a basic skelethon which is almost usable. I really didn't expect that.

I even continued with
Quote
Q: also include check for OverflowRX bit
and it obeyed joyfully.

Wow factor has just been amplified...
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: elender on January 06, 2023, 01:28:05 pm
This Github repository has a Delphi example:

https://github.com/fpiette/DelphiChatGPT (https://github.com/fpiette/DelphiChatGPT)



Use ChatGPT from Delphi https://www.tmssoftware.com/site/blog.asp?post=1045 (https://www.tmssoftware.com/site/blog.asp?post=1045)

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

Code: Pascal  [Select][+][-]
  1. uses
  2.   System.JSON, VCL.TMSFNCCloudBase;
  3.  
  4. function AskChatGPT(AQuestion: string): string;
  5. var
  6.   LCb: TTMSFNCCloudBase;
  7.   LPostdata: string;
  8.   LJsonValue: TJsonValue;
  9.   LJsonArray: TJsonArray;
  10.   LJSonString: TJsonString;
  11. begin
  12.   Result := '';
  13.  
  14.   LPostData := '{' +
  15.     '"model": "text-davinci-003",'+
  16.     '"prompt": "' + AQuestion + '",'+
  17.     '"max_tokens": 2048,'+
  18.     '"temperature": 0'+
  19.     '}';
  20.  
  21.   // create instance of TMS FNC Cloud Base class
  22.   LCb := TTMSFNCCloudBase.Create;
  23.  
  24.   try
  25.     // Use JSON for the REST API calls and set API KEY via Authorization header
  26.     LCb.Request.AddHeader('Authorization','Bearer ' + CHATGPT_APIKEY);
  27.     LCb.Request.AddHeader('Content-Type','application/json');
  28.  
  29.     // Select HTTPS POST method, set POST data and specify endpoint URL
  30.     LCb.Request.Method := rmPOST;
  31.     LCb.Request.PostData := LPostData;
  32.     LCb.Request.Host := 'https://api.openai.com';
  33.     LCb.Request.Path := 'v1/completions';
  34.  
  35.     // Execute the HTTPS POST request synchronously (last param Async = false)
  36.     LCb.ExecuteRequest(nil,nil,false);
  37.  
  38.     // Process returned JSON when request was successful
  39.     if Lcb.RequestResult.Success then
  40.     begin
  41.       LJsonValue := TJSonObject.ParseJSONValue(Lcb.RequestResult.ResultString);
  42.       LJsonValue := LJsonValue.GetValue<TJSonValue>('choices');
  43.       if LJsonValue is TJSonArray then
  44.       begin
  45.         LJSonArray := LJsonValue as TJSonArray;
  46.         LJSonString := LJSonArray.Items[0].GetValue<TJSONString>('text');
  47.         Result := LJSonString.Value;
  48.       end
  49.       else
  50.     end
  51.     else
  52.       raise Exception.Create('HTTP response code: ' + LCb.RequestResult.ResponseCode.ToString);
  53.   finally
  54.     LCb.Free;
  55.   end;
  56. end;
  57.  

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

Code: Pascal  [Select][+][-]
  1. procedure TForm1.Button1Click(Sender: TObject);  
  2. begin  
  3.   Memo1.Lines.Text := AskChatGPT(Edit1.Text);  
  4. end;  
  5.  

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.
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.

Make sure to download & install TMS FNC Core as well. https://www.tmssoftware.com/site/tmsfnccore.asp (https://www.tmssoftware.com/site/tmsfnccore.asp)



Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 06, 2023, 02:11:36 pm
That is the same as for our code .... But way more heavy weight.
In the mean time there are IDE's and components under development based on my core code demo code by multiple FreePascal users.
Anyway, my simple core code supports way more platforms and only uses standard FreePascal libraries.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: fabiopesaju on January 06, 2023, 04:08:34 pm
https://www.youtube.com/watch?v=V7bumJP6YAY&

Here one more example using Delphi.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: jamie on January 07, 2023, 03:44:32 pm
This is funny,.

 Recently teachers and students in NYC public schools are barred from using ChatGPT.

 Is there something they know we don't ?
 :o
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on January 07, 2023, 05:54:52 pm
This is funny,.

 Recently teachers and students in NYC public schools are barred from using ChatGPT.

 Is there something they know we don't ?
 :o
Searching more info about that, I've found this: https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned

I'm not a regular visitor in stackoverflow, perhaps other members should have been noticed that earlier.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Fred vS on January 07, 2023, 07:41:13 pm
This is funny,.

 Recently teachers and students in NYC public schools are barred from using ChatGPT.

 Is there something they know we don't ?
 :o
Searching more info about that, I've found this: https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned

I'm not a regular visitor in stackoverflow, perhaps other members should have been noticed that earlier.

ChatGPT is an Artificial Intelligence based chat bot by OpenAI and was announced on 30-11-2022.
And already so much noise.
2023 will be the OpenAI revolution.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 07, 2023, 08:01:45 pm
I told you it can do homework  :o ;D
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Fred vS on January 07, 2023, 08:15:32 pm
I told you it can do homework  :o ;D

Did you read the answers of : https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned ?
Funny to read all those developers who are afraid to loose their medals because of OpenAI....
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 07, 2023, 08:23:19 pm
Did you read the answers of : https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned ?
Funny to read all those developers who are afraid to loose their medals because of OpenAI....
That is the scariest of all!! :-X %) :o Programmers that do not understand what other programmers are capable of.
They are just jealous on the amount of things that can be achieved if MS$ invests a billion dollars so the project can hire the best people in the field and on every single aspect of the project..
And maybe Jealous on the hardware they are playing with... I am!!

I asked a very personal friend about his opinion and he said he has "only half that budget", telling for one of the most recognized people in the field of AI.
( https://usa.nissannews.com/en-US/releases/nissans-dr-maarten-sierhuis-named-motortrend-software-defined-vehicle-innovator-awards-winner# )
We used to get very drunk together about 45-30 years ago.... And we still see eachother every so often.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: MarkMLl on January 07, 2023, 08:38:11 pm
And maybe Jealous on the hardware they are playing with... I am!!

I'm not. It's just PCs... plus a few graphics cards and so on... meh.

Now, if Lenat et al had ever got some decent ontologies working, well, then I might be jealous.

But right now it's just pattern matching, and even though it's scarily impressive... well, I'd rather not be anywhere near it when things start going wrong.

MarkMLl
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 07, 2023, 08:52:08 pm
I'm not. It's just PCs... plus a few graphics cards and so on... meh.
No Mark, and you can predict my answer:
They use the PC's just like we did in the 70ths and 80ths, as a Terminal to bigiron. (Well, cloud is basically accumulated iron, but very much bigger than bigiron in the past...and still uses old school bigiron too.)
Nothing new there.... ;D ;D Been there, seen it, used it and I know for sure you did too...

Seems you have forgotten part of your past?  :P

And it is not pattern matching as such, it is set theory. Pattern matching is just one of the ways to reduce to a set, and the slowest one, combinatory theory being the fastest. (pattern matching starts with a given pattern or partial pattern, combinatory theory reduces to a pattern. It does not need a pattern or partial pattern)
What worries me personally about those complainers is that they have forgotten about such simple things in math like Venn diagrams and set theory to either explain big data and its risks or implement access to big data . Now that is for another story... Hm, you can explain sixth graders what risks they are taking on the internet, just by showing them Venn diagrams  (I did that on my youngest daughter's (14 - 15 year age range) secondary school and they all got the point. No big math involved.) I bet you many on this forum can not even use them or set theory properly, let alone see the impact. And, hey it is a Pascal forum, they should know sets.....(NOT  >:D ) and combinatory math on sets (NOT AT ALL  >:D )

Yes, I am a grumpy old man...

Regards,

Thaddy
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: MarkMLl on January 07, 2023, 09:41:04 pm
They use the PC's just like we did in the 70ths and 80ths, as a Terminal to bigiron. (Well, cloud is basically accumulated iron, but very much bigger than bigiron in the past...and still uses old school bigiron too.)

Yes, but the "bigiron" is basically PCs with GPU-like extensions. Nothing really sexy and nothing- despite appearances- that /understands/ what it's doing.

And as for "The Cloud": it's basically everybody buying mainframe time from a megacorporation. It'll end in tears...

MarkMLl
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: alpine on January 07, 2023, 09:48:19 pm
Quote from: MarkMLl
But right now it's just pattern matching, and even though it's scarily impressive... well, I'd rather not be anywhere near it when things start going wrong.
Yeah, me too.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 07, 2023, 09:53:54 pm
/understands/ what it's doing.
No Mark. I accept it is rudimentary, but the models from OpenAI are disinguished from being dumb:
They are capable of understanding they might have given a wrong answer or a below par answer and start looking for and gathering additional information. And the models do that without the need for our responses. They analyse their answers themselves. (Not only based on weight, but based on weight and interpretation of context)
To me that is some form of intelligence. Not perfect - but intelligence is flawed by default- and this approach is certainly not new, but in the past very hard to implement. It still is.
A much earlier example of the applied technology is:
Code: [Select]
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 cxd4 13. cxd4 Nc6 14. Nf1 Bg4 15. Be3 Rac8 16. Qd2 Bxf3 17. Nxf3 Nd8 18. Nh4 Bf8 19. Nf5 Qe7 20. Nxg7 Kxg7 21. Bxh7+ Kxh7 22. Qh6+ Kg8 23. Qh7+ Kf8 24. Qh8+ Ke7 25. Qxg7+ Kd8 26. Bf4 Kc8 27. Re3 d5 28. exd5 Rcd7 29. Qf6 Kb8 30. Qxd8+ Rxd8 31. Bxd6 Rd6 32. Bf4 Rg6 33. Re7 Kc8 34. Rae1 Kd8 35. g3 Kc8 36. Kf1 Kd8 37. Re8+ Kc7 38. R8e7+ Kb6 39. Rd7 Kc5 40. Be3+ Kxd5 41. Bd4+ Kc6 42. Re6+ Kd7 43. Re7+ Kd6 44. Re6+ Kc7 45. Rc6+ Kb8 46. Rb6+ Kc8 47. Rd6 Kc7 48. Bxg7 Rd7 49. Rxd7+ Kxd7 50. Bf6 a5 51. Ke2 Kc6 52. Kd3 Kb5 53. Kc4 Ka4 54. Kb3 Kb4 55. Bb2+ Kc5 56. Kc3 Kd4 57. Bg7 a4 58. Bf6 a3 59. Kb3 Kc5 60. Be5 a2 61. Kxa2 1-0
Cudo's to the ones that know what I mean here  ::)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: MarkMLl on January 07, 2023, 11:08:50 pm
They are capable of understanding

They don't /understand/. Understanding is a sentient prerogative, and they're not.

Quote
Cudo's to the ones that know what I mean here  ::)

Kudos. And I'm not working through it right now.

MarkMLl
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: VisualLab on January 08, 2023, 12:05:10 am
I accept it is rudimentary...

No, it's complex and complicated.

...but the models from OpenAI are disinguished from being dumb:

Full agreement. Machines and algorithms can be neither smart nor stupid. At most, their constructors can be like that. Machines and algorithms can only be primitive or sophisticated. This one rather belongs to the latter category. But it's still just an automaton.

To me that is some form of intelligence. Not perfect - but intelligence is flawed by default- and this approach is certainly not new, but in the past very hard to implement. It still is.

But there's nothing intelligent about it. For now, it just searches, slices and sticks the provided content (simplifying). Complex automaton. Where's the learning from mistakes?

A much earlier example of the applied technology is:
Code: [Select]
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Na5 10. Bc2 c5 11. d4 Qc7 12. Nbd2 cxd4 13. cxd4 Nc6 14. Nf1 Bg4 15. Be3 Rac8 16. Qd2 Bxf3 17. Nxf3 Nd8 18. Nh4 Bf8 19. Nf5 Qe7 20. Nxg7 Kxg7 21. Bxh7+ Kxh7 22. Qh6+ Kg8 23. Qh7+ Kf8 24. Qh8+ Ke7 25. Qxg7+ Kd8 26. Bf4 Kc8 27. Re3 d5 28. exd5 Rcd7 29. Qf6 Kb8 30. Qxd8+ Rxd8 31. Bxd6 Rd6 32. Bf4 Rg6 33. Re7 Kc8 34. Rae1 Kd8 35. g3 Kc8 36. Kf1 Kd8 37. Re8+ Kc7 38. R8e7+ Kb6 39. Rd7 Kc5 40. Be3+ Kxd5 41. Bd4+ Kc6 42. Re6+ Kd7 43. Re7+ Kd6 44. Re6+ Kc7 45. Rc6+ Kb8 46. Rb6+ Kc8 47. Rd6 Kc7 48. Bxg7 Rd7 49. Rxd7+ Kxd7 50. Bf6 a5 51. Ke2 Kc6 52. Kd3 Kb5 53. Kc4 Ka4 54. Kb3 Kb4 55. Bb2+ Kc5 56. Kc3 Kd4 57. Bg7 a4 58. Bf6 a3 59. Kb3 Kc5 60. Be5 a2 61. Kxa2 1-0
Cudo's to the ones that know what I mean here  ::)

I was paralyzed and blinded on "2 Hail Marys" :)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 08, 2023, 12:13:56 am
I give both you and Mark a riddle:

"The deep blue sea, in a huge wave, swallowed Casper's son and he sadly died".

Trust me, NOT machine generated, just my "I".
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: VisualLab on January 08, 2023, 01:02:56 am
"The deep blue sea, in a huge wave, swallowed Casper's son and he sadly died".

A very beautiful haiku :)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: speter on January 08, 2023, 02:03:55 am
Q: write a haiku in english, about casper's son
A:
Casper's son, lost
To the deep blue sea's raging cost
Gone, but not forgotten

:)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Thaddy on January 08, 2023, 09:54:59 am
Ok, Ok, I will give the answer:
It is about chess.
It is the ninth game between Garry Kasparov and Deep Blue, which Kasparov lost and so Deep Blue was the winner of this tournament. Much to Caspar's son chagrin... He did not see that coming at the time.
OpenAI was even able to point out where he lost: move 23 was already the killer blow, Kasparov only gave up because anyone can see he would have lost in two moves and much later.
Deep Blue is an IBM super computer (well super at the time)
Kasparov means son of Kaspar.(Or Caspar/Casper)
Apart from the two unplayed moves I have no clue what was happening after move 23.
Deep blue was trained on a large amount of data, but under the rules could not do any database look-ups.
One of the best examples where AI outperformed very talented human skills to this day.

I do like the Haiku's! All should lead a chess player to the same conclusion as I explained above.

https://en.wikipedia.org/wiki/Deep_Blue_(chess_computer)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Webdrifter on January 12, 2023, 04:57:20 pm

They don't /understand/. Understanding is a sentient prerogative, and they're not.


I believe that not to be true entirely.
I believe that understanding as we "perceive it" is a sentient prerogative.
I believe there to be levels of "understanding" on a sliding scale.

Off course this also depends on how you define understanding.
But I prefer a wider definition because otherwise I would lack a proper word for the non sentient kind....

The same counts for "intelligence" or "emotions".
(Study animals, or even plants, and you know what I mean)


 
 
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Fred vS on January 31, 2023, 08:55:30 pm
Hello.

Yep, OpenAI will recognize OpenAI (or not)  ;)
https://openai.com/blog/new-ai-classifier-for-indicating-ai-written-text/
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Ericktux on April 03, 2023, 06:50:25 pm
Hello friends, thank you very much for sharing your knowledge, as of today (04-03-2023) when using the thaddy friend's code I get:

Code: Pascal  [Select][+][-]
  1. {
  2.     "error": {
  3.         "message": "You exceeded your current quota, please check your plan and billing details.",
  4.         "type": "insufficient_quota",
  5.         "param": null,
  6.         "code": null
  7.     }
  8. }

On the web it works normally, only with the Lazarus app it doesn't work
can it be solved?  :(
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Edson on April 03, 2023, 07:26:03 pm
Hello.

Yep, OpenAI will recognize OpenAI (or not)  ;)
https://openai.com/blog/new-ai-classifier-for-indicating-ai-written-text/

Not accurate. I tested my articles and they returned to be created by AI.  :o
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Roland57 on April 03, 2023, 07:37:32 pm
Absolutely nothing to give a damn about OpenAI. I put people who talk about OpenAI on my list of people to ignore.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Fred vS on April 03, 2023, 08:04:42 pm
I put people who talk about OpenAI on my list of people to ignore.

Ok but all the others who don't talk about it are the ones who use it.
 ;)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Ericktux on April 03, 2023, 09:42:58 pm
I have created another api again and the same error continues, perhaps in the client apps created by lazarus this limitation is given, because the web version continues to work normally.
Has anyone else had the same problem?
Or is it that now there is no free version and it is necessary to pay  :(
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ASBzone on April 03, 2023, 10:55:07 pm
There are now some costs associated with using ChatGPT in certain contexts.

https://openai.com/pricing (https://openai.com/pricing)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: jamie on April 03, 2023, 11:01:34 pm
Absolutely nothing to give a damn about OpenAI. I put people who talk about OpenAI on my list of people to ignore.

Ah, Men! Brother! 8-)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: ASBzone on April 03, 2023, 11:28:01 pm
Absolutely nothing to give a damn about OpenAI. I put people who talk about OpenAI on my list of people to ignore.

What is the wisdom in that?

There are plenty of topics that happen in these forums that either don't interest me personally or professionally, or are not things I need to focus on at this time.   I'm certain this is true for pretty much everyone here.

How noisy and unproductive it would be, if we jumped into every thread that did not appeal or make sense to us, and proclaim its uselessness!
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: 440bx on April 03, 2023, 11:58:27 pm
Just in case... this post is tongue in cheek...

I'm very pleased there is a great deal of effort going on in the field of Artificial Intelligence.  Maybe someday we'll have enough AI to compensate for the increasing scarcity of the natural one.

Some say SETI was created to increase the sources of intelligence because little, if any, could be found locally (see the movie I.Q)

if you have any doubts about the above, consider that Einstein found the source of infinite stupidity (and nobody gave him a Nobel prize for figuring out the obvious) but the source of infinite intelligence is yet to be found.  I rest my case ;)

Artificial coloring... Artificial flavors... Artificial intelligence... evolution never stops :)
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: dbannon on April 04, 2023, 11:08:04 am
Of course we can choose to ignore AI, and people who are interested in it.

Personally, I am not interested in it, don't want to work with it, won't contribute anything to it. But I sure know I cannot possibly afford to ignore it !

Davo
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: Tomas Hajny on April 04, 2023, 02:24:09 pm
This discussion doesn't seem to be related to Free Pascal in its current form - please, don't continue it.
Title: Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
Post by: schuler on December 01, 2023, 11:21:03 pm
:) Hello Pascal Lovers! :)

In the case that the moderator allows me, I would like to go back to the page 3 of this thread regarding pascal (it was very interesting).

I had a problem last weekend when I needed to use very long string lists and it was slow to get the "delimited text". So, I asked GPT 4 to give me a solution. This was my question:

Code: Pascal  [Select][+][-]
  1. // I have this pascal method but it's too slow as the number of elements grow:
  2.  
  3. Function TStrings.GetDelimitedText: string;
  4. ...
  5. end;

This is what I got in the result:

Code: Pascal  [Select][+][-]
  1. // To optimize this, you can use a TStringBuilder object, which is designed for efficient string manipulations, especially when building a string in a loop. Here's how you can modify your function:
  2.  
  3. uses
  4.   SysUtils, StrUtils, Classes;
  5.  
  6. function TStrings.GetDelimitedText: string;
  7. var
  8.   I: Integer;
  9.   S: String;
  10.   BreakChars: set of Char;
  11.   DoQuote: Boolean;
  12.   StringBuilder: TStringBuilder;
  13. begin
  14.   CheckSpecialChars;
  15.   if StrictDelimiter then
  16.     BreakChars := [#0, QuoteChar, Delimiter]
  17.   else
  18.     BreakChars := [#0..' ', QuoteChar, Delimiter];
  19.  
  20.   StringBuilder := TStringBuilder.Create;
  21.   try
  22.     for I := 0 to Count - 1 do
  23.     begin
  24.       S := Strings[I];
  25.       DoQuote := FAlwaysQuote;
  26.       if not DoQuote then
  27.       begin
  28.         // Quote strings that include BreakChars
  29.         DoQuote := StrHasChars(S, True, BreakChars);
  30.       end;
  31.       if DoQuote and (QuoteChar <> #0) then
  32.         StringBuilder.Append(AnsiQuotedStr(S, QuoteChar))
  33.       else
  34.         StringBuilder.Append(S);
  35.  
  36.       if I < Count - 1 then
  37.         StringBuilder.Append(Delimiter);
  38.     end;
  39.  
  40.     // Quote empty string
  41.     if (StringBuilder.Length = 0) and (Count = 1) and (QuoteChar <> #0) then
  42.       StringBuilder.Append(QuoteChar).Append(QuoteChar);
  43.  
  44.     Result := StringBuilder.ToString;
  45.   finally
  46.     StringBuilder.Free;
  47.   end;
  48. end;
  49.  
  50. // Helper function to check if a string contains any character from a set
  51. function StrHasChars(const Str: string; Strict: Boolean; const Chars: TSysCharSet): Boolean;
  52. var
  53.   P: PChar;
  54. begin
  55.   P := PChar(Str);
  56.   while (P^ <> #0) and (not CharInSet(P^, Chars) or Strict) do Inc(P);
  57.   Result := P^ <> #0;
  58. end;
  59.  
  60.  

It's not perfect but looks like a very good reply to me...
TinyPortal © 2005-2018