unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls,
OpenSSLSockets;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
uses
fphttpclient, // For HTTP requests
fpjson, // For JSON parsing
jsonparser; // For JSON parsing
{$R *.lfm}
const
API_URL = 'https://api.openai.com/v1/completions';
API_KEY = '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';
var
HttpClient: TFPHTTPClient;
Response: TStringStream;
JsonRequest, JsonResponse: TJSONObject;
JsonBody: TStringStream;
Prompt: string;
Temperature: Double;
MaxTokens: Integer;
ResponseText: string;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
// Prompt for ChatGPT
Prompt := 'Translate the following English text to French: "Hello, how are you?"';
Temperature := 0.7; // Controls randomness. 0.0 for deterministic responses
MaxTokens := 50; // Maximum number of tokens to generate
// Create the HTTP client
HttpClient := TFPHTTPClient.Create(nil);
Response := TStringStream.Create('');
JsonBody := TStringStream.Create('');
try
// Prepare the JSON body
JsonRequest := TJSONObject.Create;
try
JsonRequest.Add('model', 'text-davinci-003'); // or whichever model you are using
JsonRequest.Add('prompt', Prompt);
JsonRequest.Add('temperature', Temperature);
JsonRequest.Add('max_tokens', MaxTokens);
JsonBody.WriteString(JsonRequest.AsJSON);
// Set HTTP headers
HttpClient.AddHeader('Content-Type', 'application/json');
HttpClient.AddHeader('Authorization', 'Bearer ' + API_KEY);
// HttpClient.Post(API_URL, JsonBody, Response);
// ResponseText := Response.DataString;
HttpClient.Post(API_URL, JsonBody);
ResponseText := JsonBody.DataString;
// Parse the response JSON
JsonResponse := TJSONObject(GetJSON(ResponseText));
try
memo1.lines.add(JsonResponse.Get('choices[0].text', 'No response text.'));
finally
JsonResponse.Free;
end;
finally
JsonRequest.Free;
end;
except
on E: Exception do
ShowMessage('Error: ' + E.Message);
end;
// Clean up
HttpClient.Free;
Response.Free;
JsonBody.Free;
end;
end.