Hello,
The API is very simple, you can use Indy to send the POST request and then parse the JSON response. Find below an example:
function AskChatGPT(const aAPI, aQuestion: string): string;
var
oHTTP: TIdHTTP;
oSSL: TIdSSLIOHandlerSocketOpenSSL;
oStream: TStringStream;
vPostData: string;
oJSON: TJSONValue;
oArray: TJSonArray;
begin
oHTTP := TIdHTTP.Create(nil);
oSSL := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
Try
oSSL.SSLOptions.Method := sslvTLSv1_2;
oHTTP.IOHandler := oSSL;
oHTTP.Request.CustomHeaders.Add('Authorization: Bearer ' + aAPI);
oHTTP.Request.ContentType := 'application/json';
vPostData :=
Format('{"model": "text-davinci-003","prompt": "%s","max_tokens": 2048,"temperature": 0}',
[aQuestion]);
// send request
oStream := TStringStream.Create(vPostData);
Try
result := oHTTP.Post('https://api.openai.com/v1/completions', oStream);
// parse response
oJSON := TJSonObject.ParseJSONValue(result).GetValue<TJSONValue>
('choices');
result := TJSonArray(oJSON).Items[0].GetValue<TJSONString>('text').Value;
Finally
oStream.Free;
End;
Finally
oSSL.Free;
oHTTP.Free;
End;
end;
The function has 2 arguments, the API key (can be obtained from https://beta.openai.com/account/api-keys) and the message you want to sent to ChatGPT. The function just sends the API Key as a Bearer Token and POST the JSON message to the server. The server returns a JSON object that must be parsed to obtain the response text.
I've attached the complete project with the required openSSL libraries.
Kind Regards,
Sergio
chatgpt_esegece.zip