Forum > General
Has anyone used Free Pascal to connect with chatGPT (OpenAI)?
indydev:
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 [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program OpenAI; {$mode objfpc}{$H+}uses SysUtils, Classes, httpsend, Crt; const GREETING = 'Hello! I am your Assistant. Do you have any questions for me?'; FAREWELL = 'Thank you for asking me your questions I enjoy helping out when I can. Goodbye!'; var input: string; HTTP: THTTPSend; Response: TStringList; URL: string; APIKey: string; i: integer; procedure Initialize;begin URL := 'https://api.openai.com/v1/questions/answers'; APIKey := 'sk-sjLaiEls3i9l29lzOKA2MjdIwlpSK19jyN3q8D5WvAchK4'; // <--not real key HTTP := THTTPSend.Create; HTTP.MimeType := 'application/json'; HTTP.UserName := APIKey; HTTP.Password := ''; HTTP.Headers.Add('Content-Type: application/x-www-form-urlencoded'); HTTP.HTTPMethod('POST', URL);end; function getInput: string;begin write('> '); readln(Result);end; function isGoodbye(input: string): boolean;begin Result := (input = 'goodbye') or (input = 'bye') or (input = 'quit');end; function getOpenAI_Response(input: string): TStringList;var Buffer: PChar;begin Buffer := PChar(input); Result := TStringList.Create; HTTP.Document.Clear; HTTP.Document.Write(Buffer^, Length(input)); Response.LoadFromStream(HTTP.Document);end; begin ClrScr; Initialize; writeln(GREETING); try repeat input := getInput; Response := getOpenAI_Response(input); for i := 0 to Response.Count -1 do begin writeln(Response[i]); end; until isGoodbye(Lowercase(input)); Finally Response.Free; HTTP.Free; end; writeln(FAREWELL); readln;end.
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.
Simiba7:
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 [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} --- uses SysUtils, Classes, Process; var url: string; AStringList : TStringList; Aprocess: TProcess; begin AProcess := TProcess.Create(nil); url:='https://api.openai.com/v1/completions'; AProcess.Executable:='curl'; //AProcess.Parameters.Add('-X POST'); AProcess.Parameters.Add(url); AProcess.Parameters.Add('-H "Authorization: Bearer API-KEY"'); AProcess.Parameters.Add('-H "Content-Type: application/json"'); AProcess.Parameters.Add('-d ''{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}'''); AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; AProcess.Execute; AStringList := TStringList.Create; AStringList.LoadFromStream(AProcess.Output); Label1.Caption:= AStringList.CommaText; end;
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
ccrause:
--- Quote from: indydev on December 21, 2022, 04:41:43 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.
--- End quote ---
See 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.
ccrause:
--- Quote from: Simiba7 on December 22, 2022, 11:21:36 pm ---
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} --- AProcess.Parameters.Add('-d ''{"model": "text-davinci-003", "prompt": "Say this is a test", "temperature": 0, "max_tokens": 7}''');
--- End 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.
Thaddy:
Here's a simpler example that works, do not forget to substitute YOUR_API_KEY with your own:
--- Code: Pascal [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---program testopenai;{$mode objfpc}{$ofdef mswindows}{$apptype console}{$endif}uses Classes, Process;var AStringList : TStrings; Aprocess: TProcess; begin AProcess := TProcess.Create(nil); try AProcess.Options := AProcess.Options + [poWaitOnExit,poUsePipes]; AProcess.Executable:='curl.exe'; AProcess.Parameters.Add('https://api.openai.com/v1/models/text-davinci-003'); AProcess.Parameters.Add('-H'); Aprocess.Parameters.Add('"Authorization: Bearer YOUR_API_KEY"'); // do not quote your_APi_KEY!! AProcess.Execute; try AStringList := TStringList.Create; AStringList.LoadFromStream(AProcess.Output); Writeln(AStringList.Text); finally AStringList.Free; end; Finally AProcess.Free; end;end.
Navigation
[0] Message Index
[#] Next page