Skip to content

Instantly share code, notes, and snippets.

@jarroddavis68
Last active April 28, 2023 05:48
Show Gist options
  • Save jarroddavis68/3058cb186a46f3eb739d2583ec4253ea to your computer and use it in GitHub Desktop.
Save jarroddavis68/3058cb186a46f3eb739d2583ec4253ea to your computer and use it in GitHub Desktop.
Use ChatGPT from Delphi
(****************************************************************************
___ _ _ _ ___ _ _ ___ ___ _____
| \ ___ | | _ __ | |_ (_) / __|| |_ __ _ | |_ / __|| _ \|_ _|
| |) |/ -_)| || '_ \| ' \ | || (__ | ' \ / _` || _|| (_ || _/ | |
|___/ \___||_|| .__/|_||_||_| \___||_||_|\__,_| \__| \___||_| |_|
|_|
Copyright © 2022-present tinyBigGAMES™ LLC
All Rights Reserved.
Website: https://tinybiggames.com
Email : [email protected]
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
3. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
4. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
5. All video, audio, graphics and other content accessed through the
software in this distro is the property of the applicable content owner
and may be protected by applicable copyright law. This License gives
Customer no rights to such content, and Company disclaims any liability
for misuse of content.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
Update #5: add support to select GPT model 3 or 4
Update #4: renamed to AskChatGTPv30 (text-davinci-003),
AskChatGTPv35 (gpt-3.5-turbo)
Update #3: Added support for gpt-3.5-turbo modal (most up todate, 1/10 cost)
Update #2: Support for non-English languages (thanks Bear Xu)
Update #1: Fixed Json memory leak
-----------------------------------------------------------------------------
How to use:
Get your API Key:
https://platform.openai.com/account/api-keys
...
uses
DelphiChatGPT;
var
LResponse: string;
begin
LResponse := AskChatGTP(GPT4, YOU_API_KEY, 'What is Embarcadero Delphi');
WriteLn(LResponse);
end;
Response:
"Embarcadero Delphi is a rapid application development (RAD) tool for
Windows, macOS, iOS, and Android. It is a programming language and software
development kit (SDK) for creating applications for several platforms.
Delphi is based on Object Pascal and is one of the oldest programming
languages still in active use. It is used to create applications for
desktop, mobile, web, and console."
*****************************************************************************)
unit DelphiChatGPT;
interface
type
TChatGPTModel = (GPT3, GPT4);
function AskChatGPT(const aModel: TChatGPTModel; const aApiKey, aQuestion: string): string;
implementation
uses
System.Generics.Collections,
System.SysUtils,
System.Classes,
System.Net.HttpClient,
System.Net.Mime,
System.JSON;
function AskChatGPT(const aModel: TChatGPTModel; const aApiKey, aQuestion: string): string;
const
cModel: array[GPT3 .. GPT4] of string = ('gpt-3.5-turbo', 'gpt-4');
var
LHttpClient: THTTPClient;
LString: string;
LJson: TJsonObject;
LMessages: TJsonArray;
LMessage: TJsonObject;
LChoices: TJsonArray;
LChoice: TJsonObject;
LText: TJsonObject;
LPostDataStream: TStringStream;
LResponse: IHTTPResponse;
begin
LHttpClient := THTTPClient.Create;
try
LHttpClient.CustomHeaders['Authorization'] := 'Bearer ' + aApiKey;
LHttpClient.CustomHeaders['Content-Type'] := 'application/json';
LJson := TJsonObject.Create;
try
LMessages := TJsonArray.Create;
try
LMessage := TJsonObject.Create;
try
LMessage.AddPair('role', 'user');
LMessage.AddPair('content', aQuestion);
LMessages.Add(LMessage.Clone as TJsonObject);
finally
LMessage.Free;
end;
LJson.AddPair('model', cModel[aModel]);
LJson.AddPair('messages', LMessages.Clone as TJsonArray);
LString := LJson.ToString;
finally
LMessages.Free;
end;
finally
LJson.Free;
end;
LPostDataStream := TStringStream.Create(LString, TEncoding.UTF8);
try
LPostDataStream.Position := 0;
LResponse := LHttpClient.Post('https://api.openai.com/v1/chat/completions', LPostDataStream);
LString := LResponse.ContentAsString;
finally
LPostDataStream.Free;
end;
LJson := TJsonObject.ParseJSONValue(LString) as TJsonObject;
try
if LResponse.StatusCode = 200 then
begin
LChoices := LJson.GetValue('choices') as TJsonArray;
LChoice := LChoices.Items[0] as TJsonObject;
LText := LChoice.GetValue('message') as TJsonObject;
Result := LText.GetValue('content').Value;
end
else
begin
LChoice := LJson.GetValue('error') as TJsonObject;
Result := 'Error: ' + LChoice.GetValue('message').Value;
end;
finally
LJson.Free;
end;
finally
LHttpClient.Free;
end;
end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment