Chilkat Examples

ChilkatHOME.NET Core C#Android™AutoItCC#C++Chilkat2-PythonCkPythonClassic ASPDataFlexDelphi ActiveXDelphi DLLGoJavaLianjaMono C#Node.jsObjective-CPHP ActiveXPHP ExtensionPerlPowerBuilderPowerShellPureBasicRubySQL ServerSwift 2Swift 3,4,5...TclUnicode CUnicode C++VB.NETVBScriptVisual Basic 6.0Visual FoxProXojo Plugin

Delphi DLL Web API Examples

Primary Categories

ABN AMRO
AWS Secrets Manager
AWS Security Token Service
AWS Translate
Activix CRM
Adyen
Alibaba Cloud OSS
Amazon Cognito
Amazon DynamoDB
Amazon MWS
Amazon Pay
Amazon Rekognition
Amazon SP-API
Amazon Voice ID
Aruba Fatturazione
Azure Maps
Azure Monitor
Azure OAuth2
Azure Storage Accounts
Backblaze S3
Banco Inter
Belgian eHealth Platform
Bitfinex v2 REST
Bluzone
BrickLink
Bunny CDN
CallRail
CardConnect
Cerved
ClickBank
Clickatell
Cloudfare
Constant Contact
DocuSign
Duo Auth MFA
ETrade
Ecwid
Egypt ITIDA
Egypt eReceipt
Etsy
Facebook
Faire
Frame.io
GeoOp
GetHarvest
Global Payments
Google People
Google Search Console
Google Translate
Hungary NAV Invoicing
IBM Text to Speech
Ibanity
IntakeQ
Jira
Lightspeed
MYOB
Magento
Mailgun
Mastercard

MedTunnel
MercadoLibre
MessageMedia
Microsoft Calendar
Microsoft Group
Microsoft Tasks and Plans
Microsoft Teams
Moody's
Okta OAuth/OIDC
OneLogin OIDC
OneNote
OpenAI ChatGPT
PRODA
PayPal
Paynow.pl
Peoplevox
Populi
QuickBooks
Rabobank
Refinitiv
Royal Mail OBA
SCiS Schools Catalogue
SII Chile
SMSAPI
SOAP finkok.com
SendGrid
Shippo
Shopify
Shopware
Shopware 6
SimpleTexting
Square
Stripe
SugarCRM
TicketBAI
Trello
Twilio
Twitter API v2
Twitter v1
UPS
UniPin
VoiceBase
Vonage
WaTrend
Walmart
Walmart v3
Wasabi
WhatsApp
WiX
WooCommerce
WordPress
Xero
Yahoo Mail
Yapily
Yousign
ZATCA
Zendesk
Zoom
_Miscellaneous_
eBay
effectconnect
hacienda.go.cr

 

 

 

(Delphi DLL) OpenAI (ChatGTP) Create Chat Completion

See more OpenAI ChatGPT Examples

Shows how to create a model response for a given chat conversation.

For more information, see https://platform.openai.com/docs/api-reference/chat/create

Chilkat for Delphi Downloads

Chilkat non-ActiveX DLL for Delphi

Chilkat ActiveX DLL for Delphi

* The examples here use the non-ActiveX DLL.

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Http, StringBuilder, HttpResponse, JsonObject;

...

procedure TForm1.Button1Click(Sender: TObject);
var
http: HCkHttp;
success: Boolean;
json: HCkJsonObject;
resp: HCkHttpResponse;
sbResponseBody: HCkStringBuilder;
jResp: HCkJsonObject;
respStatusCode: Integer;
index: Integer;
Role: PWideChar;
Content: PWideChar;
finish_reason: PWideChar;
id: PWideChar;
v_object: PWideChar;
created: Integer;
Prompt_tokens: Integer;
Completion_tokens: Integer;
Total_tokens: Integer;
i: Integer;
count_i: Integer;

begin
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

http := CkHttp_Create();

// Implements the following CURL command:

// curl https://api.openai.com/v1/chat/completions \
//   -H "Content-Type: application/json" \
//   -H "Authorization: Bearer $OPENAI_API_KEY" \
//   -d '{
//     "model": "gpt-3.5-turbo",
//     "messages": [{"role": "user", "content": "Hello!"}]
//   }'

// Use the following online tool to generate HTTP code from a CURL command
// Convert a cURL Command to HTTP Source Code

// Use this online tool to generate code from sample JSON:
// Generate Code to Create JSON

// The following JSON is sent in the request body.

// {
//   "model": "gpt-3.5-turbo",
//   "messages": [
//     {
//       "role": "user",
//       "content": "Hello!"
//     }
//   ]
// }

json := CkJsonObject_Create();
CkJsonObject_UpdateString(json,'model','gpt-3.5-turbo');
CkJsonObject_UpdateString(json,'messages[0].role','user');
CkJsonObject_UpdateString(json,'messages[0].content','Hello!');

// Adds the "Authorization: Bearer $OPENAI_API_KEY" header.
// This is NOT a real key.  Change the "sk-vi...." to your own key.
CkHttp_putAuthToken(http,'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');
CkHttp_SetRequestHeader(http,'Content-Type','application/json');

resp := CkHttp_PostJson3(http,'https://api.openai.com/v1/chat/completions','application/json',json);
if (CkHttp_getLastMethodSuccess(http) = False) then
  begin
    Memo1.Lines.Add(CkHttp__lastErrorText(http));
    Exit;
  end;

sbResponseBody := CkStringBuilder_Create();
CkHttpResponse_GetBodySb(resp,sbResponseBody);

jResp := CkJsonObject_Create();
CkJsonObject_LoadSb(jResp,sbResponseBody);
CkJsonObject_putEmitCompact(jResp,False);

Memo1.Lines.Add('Response Body:');
Memo1.Lines.Add(CkJsonObject__emit(jResp));

respStatusCode := CkHttpResponse_getStatusCode(resp);
Memo1.Lines.Add('Response Status Code = ' + IntToStr(respStatusCode));
if (respStatusCode >= 400) then
  begin
    Memo1.Lines.Add('Response Header:');
    Memo1.Lines.Add(CkHttpResponse__header(resp));
    Memo1.Lines.Add('Failed.');
    CkHttpResponse_Dispose(resp);
    Exit;
  end;
CkHttpResponse_Dispose(resp);

// Sample JSON response:
// (Sample code for parsing the JSON response is shown below)

// {
//   "id": "chatcmpl-123",
//   "object": "chat.completion",
//   "created": 1677652288,
//   "choices": [
//     {
//       "index": 0,
//       "message": {
//         "role": "assistant",
//         "content": "\n\nHello there, how may I assist you today?"
//       },
//       "finish_reason": "stop"
//     }
//   ],
//   "usage": {
//     "prompt_tokens": 9,
//     "completion_tokens": 12,
//     "total_tokens": 21
//   }
// }

// Sample code for parsing the JSON response...
// Use the following online tool to generate parsing code from sample JSON:
// Generate Parsing Code from JSON

id := CkJsonObject__stringOf(jResp,'id');
v_object := CkJsonObject__stringOf(jResp,'object');
created := CkJsonObject_IntOf(jResp,'created');
Prompt_tokens := CkJsonObject_IntOf(jResp,'usage.prompt_tokens');
Completion_tokens := CkJsonObject_IntOf(jResp,'usage.completion_tokens');
Total_tokens := CkJsonObject_IntOf(jResp,'usage.total_tokens');
i := 0;
count_i := CkJsonObject_SizeOfArray(jResp,'choices');
while i < count_i do
  begin
    CkJsonObject_putI(jResp,i);
    index := CkJsonObject_IntOf(jResp,'choices[i].index');
    Role := CkJsonObject__stringOf(jResp,'choices[i].message.role');
    Content := CkJsonObject__stringOf(jResp,'choices[i].message.content');
    finish_reason := CkJsonObject__stringOf(jResp,'choices[i].finish_reason');
    i := i + 1;
  end;

CkHttp_Dispose(http);
CkJsonObject_Dispose(json);
CkStringBuilder_Dispose(sbResponseBody);
CkJsonObject_Dispose(jResp);

end;

 

© 2000-2023 Chilkat Software, Inc. All Rights Reserved.