Recent

Author Topic: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?  (Read 15729 times)

Simiba7

  • Newbie
  • Posts: 6
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #15 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

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #16 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.
« Last Edit: December 24, 2022, 09:11:36 am by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #17 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!


« Last Edit: December 24, 2022, 10:42:37 am by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

alpine

  • Hero Member
  • *****
  • Posts: 1410
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #18 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.
  • write a program in pascal which prints prime numbers in range from 11 to 777
  • write a program in pascal which prints half of the prime numbers in range from 11 to 777
You can see the latter one is plain wrong.
"I'm sorry Dave, I'm afraid I can't do that."
—HAL 9000

wp

  • Hero Member
  • *****
  • Posts: 13212
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #19 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.
« Last Edit: December 24, 2022, 12:01:17 pm by wp »

ccrause

  • Hero Member
  • *****
  • Posts: 1080
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #20 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  :)

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #21 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.
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

KodeZwerg

  • Hero Member
  • *****
  • Posts: 2269
  • Fifty shades of code.
    • Delphi & FreePascal
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #22 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
« Last Edit: Tomorrow at 31:76:97 xm by KodeZwerg »

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #23 on: December 24, 2022, 03:17:52 pm »
Delphi does not support string labels in case?
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

KodeZwerg

  • Hero Member
  • *****
  • Posts: 2269
  • Fifty shades of code.
    • Delphi & FreePascal
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #24 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)
« Last Edit: Tomorrow at 31:76:97 xm by KodeZwerg »

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #25 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.

« Last Edit: December 24, 2022, 03:57:07 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

indydev

  • Full Member
  • ***
  • Posts: 127
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #26 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...

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #27 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.
« Last Edit: December 24, 2022, 11:20:18 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #28 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.
« Last Edit: December 25, 2022, 04:48:13 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

Thaddy

  • Hero Member
  • *****
  • Posts: 18334
  • Here stood a man who saw the Elbe and jumped it.
Re: Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
« Reply #29 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.
« Last Edit: December 25, 2022, 04:50:14 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

 

TinyPortal © 2005-2018