forked from HemulGM/DelphiOpenAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OpenAI.API.pas
579 lines (522 loc) · 16.9 KB
/
OpenAI.API.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
unit OpenAI.API;
interface
uses
System.Classes, System.Net.HttpClient, System.Net.URLClient, System.Net.Mime,
System.JSON, OpenAI.Errors, OpenAI.API.Params, System.SysUtils;
type
{$IF RTLVersion < 35.0}
TURLClientHelper = class helper for TURLClient
public const
DefaultConnectionTimeout = 60000;
DefaultSendTimeout = 60000;
DefaultResponseTimeout = 60000;
end;
{$ENDIF}
OpenAIException = class(Exception)
private
FCode: Int64;
FParam: string;
FType: string;
public
property &Type: string read FType write FType;
property Code: Int64 read FCode write FCode;
property Param: string read FParam write FParam;
constructor Create(const Text, &Type: string; const Param: string = ''; Code: Int64 = -1); reintroduce;
end;
OpenAIExceptionAPI = class(Exception);
/// <summary>
/// An InvalidRequestError indicates that your request was malformed or
// missing some required parameters, such as a token or an input.
// This could be due to a typo, a formatting error, or a logic error in your code.
/// </summary>
OpenAIExceptionInvalidRequestError = class(OpenAIException);
/// <summary>
/// A `RateLimitError` indicates that you have hit your assigned rate limit.
/// This means that you have sent too many tokens or requests in a given period of time,
/// and our services have temporarily blocked you from sending more.
/// </summary>
OpenAIExceptionRateLimitError = class(OpenAIException);
/// <summary>
/// An `AuthenticationError` indicates that your API key or token was invalid,
/// expired, or revoked. This could be due to a typo, a formatting error, or a security breach.
/// </summary>
OpenAIExceptionAuthenticationError = class(OpenAIException);
/// <summary>
/// This error message indicates that your account is not part of an organization
/// </summary>
OpenAIExceptionPermissionError = class(OpenAIException);
/// <summary>
/// This error message indicates that our servers are experiencing high
/// traffic and are unable to process your request at the moment
/// </summary>
OpenAIExceptionTryAgain = class(OpenAIException);
OpenAIExceptionInvalidResponse = class(OpenAIException);
{$WARNINGS OFF}
TOpenAIAPI = class
public
const
URL_BASE = 'https://api.openai.com/v1';
private
FToken: string;
FBaseUrl: string;
FOrganization: string;
FIsAzure: Boolean;
FAzureApiVersion: string;
FAzureDeployment: string;
FCustomHeaders: TNetHeaders;
FProxySettings: TProxySettings;
FConnectionTimeout: Integer;
FSendTimeout: Integer;
FResponseTimeout: Integer;
procedure SetToken(const Value: string);
procedure SetBaseUrl(const Value: string);
procedure SetOrganization(const Value: string);
procedure ParseAndRaiseError(Error: TError; Code: Int64);
procedure ParseError(const Code: Int64; const ResponseText: string);
procedure SetCustomHeaders(const Value: TNetHeaders);
procedure SetProxySettings(const Value: TProxySettings);
procedure SetConnectionTimeout(const Value: Integer);
procedure SetResponseTimeout(const Value: Integer);
procedure SetSendTimeout(const Value: Integer);
protected
function GetHeaders: TNetHeaders; virtual;
function GetClient: THTTPClient; virtual;
function GetRequestURL(const Path: string): string;
function Get(const Path: string; Response: TStream): Integer; overload;
function Delete(const Path: string; Response: TStream): Integer; overload;
function Post(const Path: string; Response: TStream): Integer; overload;
function Post(const Path: string; Body: TJSONObject; Response: TStream; OnReceiveData: TReceiveDataCallback = nil): Integer; overload;
function Post(const Path: string; Body: TMultipartFormData; Response: TStream): Integer; overload;
function ParseResponse<T: class, constructor>(const Code: Int64; const ResponseText: string): T;
procedure CheckAPI;
public
function Get<TResult: class, constructor>(const Path: string): TResult; overload;
function Get<TResult: class, constructor; TParams: TJSONParam>(const Path: string; ParamProc: TProc<TParams>): TResult; overload;
procedure GetFile(const Path: string; Response: TStream); overload;
function Delete<TResult: class, constructor>(const Path: string): TResult; overload;
function Post<TParams: TJSONParam>(const Path: string; ParamProc: TProc<TParams>; Response: TStream; Event: TReceiveDataCallback = nil): Boolean; overload;
function Post<TResult: class, constructor; TParams: TJSONParam>(const Path: string; ParamProc: TProc<TParams>): TResult; overload;
function Post<TResult: class, constructor>(const Path: string): TResult; overload;
function PostForm<TResult: class, constructor; TParams: TMultipartFormData, constructor>(const Path: string; ParamProc: TProc<TParams>): TResult; overload;
public
constructor Create; overload;
constructor Create(const AToken: string); overload;
destructor Destroy; override;
property Token: string read FToken write SetToken;
property BaseUrl: string read FBaseUrl write SetBaseUrl;
property Organization: string read FOrganization write SetOrganization;
property ProxySettings: TProxySettings read FProxySettings write SetProxySettings;
/// <summary> Property to set/get the ConnectionTimeout. Value is in milliseconds.
/// -1 - Infinite timeout. 0 - platform specific timeout. Supported by Windows, Linux, Android platforms. </summary>
property ConnectionTimeout: Integer read FConnectionTimeout write SetConnectionTimeout;
/// <summary> Property to set/get the SendTimeout. Value is in milliseconds.
/// -1 - Infinite timeout. 0 - platform specific timeout. Supported by Windows, macOS platforms. </summary>
property SendTimeout: Integer read FSendTimeout write SetSendTimeout;
/// <summary> Property to set/get the ResponseTimeout. Value is in milliseconds.
/// -1 - Infinite timeout. 0 - platform specific timeout. Supported by all platforms. </summary>
property ResponseTimeout: Integer read FResponseTimeout write SetResponseTimeout;
property IsAzure: Boolean read FIsAzure write FIsAzure;
property AzureApiVersion: string read FAzureApiVersion write FAzureApiVersion;
property AzureDeployment: string read FAzureDeployment write FAzureDeployment;
property CustomHeaders: TNetHeaders read FCustomHeaders write SetCustomHeaders;
end;
{$WARNINGS ON}
TOpenAIAPIRoute = class
private
FAPI: TOpenAIAPI;
procedure SetAPI(const Value: TOpenAIAPI);
public
property API: TOpenAIAPI read FAPI write SetAPI;
constructor CreateRoute(AAPI: TOpenAIAPI); reintroduce;
end;
implementation
uses
REST.Json, System.NetConsts;
constructor TOpenAIAPI.Create;
begin
inherited;
// Defaults
FConnectionTimeout := TURLClient.DefaultConnectionTimeout;
FSendTimeout := TURLClient.DefaultSendTimeout;
FResponseTimeout := TURLClient.DefaultResponseTimeout;
FToken := '';
FBaseUrl := URL_BASE;
FIsAzure := False;
FAzureApiVersion := '';
FAzureDeployment := '';
end;
constructor TOpenAIAPI.Create(const AToken: string);
begin
Create;
Token := AToken;
end;
destructor TOpenAIAPI.Destroy;
begin
inherited;
end;
function TOpenAIAPI.Post(const Path: string; Body: TJSONObject; Response: TStream; OnReceiveData: TReceiveDataCallback): Integer;
var
Headers: TNetHeaders;
Stream: TStringStream;
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Headers := GetHeaders + [TNetHeader.Create('Content-Type', 'application/json')];
Stream := TStringStream.Create;
Client.ReceiveDataCallBack := OnReceiveData;
try
Stream.WriteString(Body.ToJSON);
Stream.Position := 0;
Result := Client.Post(GetRequestURL(Path), Stream, Response, Headers).StatusCode;
finally
Client.OnReceiveData := nil;
Stream.Free;
end;
finally
Client.Free;
end;
end;
function TOpenAIAPI.Get(const Path: string; Response: TStream): Integer;
var
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Result := Client.Get(GetRequestURL(Path), Response, GetHeaders).StatusCode;
finally
Client.Free;
end;
end;
function TOpenAIAPI.Post(const Path: string; Body: TMultipartFormData; Response: TStream): Integer;
var
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Result := Client.Post(GetRequestURL(Path), Body, Response, GetHeaders).StatusCode;
finally
Client.Free;
end;
end;
function TOpenAIAPI.Post(const Path: string; Response: TStream): Integer;
var
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Result := Client.Post(GetRequestURL(Path), TStream(nil), Response, GetHeaders).StatusCode;
finally
Client.Free;
end;
end;
function TOpenAIAPI.Post<TResult, TParams>(const Path: string; ParamProc: TProc<TParams>): TResult;
var
Response: TStringStream;
Params: TParams;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
Params := TParams.Create;
try
if Assigned(ParamProc) then
ParamProc(Params);
Code := Post(Path, Params.JSON, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Params.Free;
Response.Free;
end;
end;
function TOpenAIAPI.Post<TParams>(const Path: string; ParamProc: TProc<TParams>; Response: TStream; Event: TReceiveDataCallback): Boolean;
var
Params: TParams;
Code: Integer;
Strings: TStringStream;
begin
Params := TParams.Create;
try
if Assigned(ParamProc) then
ParamProc(Params);
Code := Post(Path, Params.JSON, Response, Event);
case Code of
200..299:
Result := True;
else
Result := False;
Strings := TStringStream.Create;
try
Response.Position := 0;
Strings.LoadFromStream(Response);
ParseError(Code, Strings.DataString);
finally
Strings.Free;
end;
end;
finally
Params.Free;
end;
end;
function TOpenAIAPI.Post<TResult>(const Path: string): TResult;
var
Response: TStringStream;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
try
Code := Post(Path, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Response.Free;
end;
end;
function TOpenAIAPI.Delete(const Path: string; Response: TStream): Integer;
var
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Result := Client.Delete(GetRequestURL(Path), Response, GetHeaders).StatusCode;
finally
Client.Free;
end;
end;
function TOpenAIAPI.Delete<TResult>(const Path: string): TResult;
var
Response: TStringStream;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
try
Code := Delete(Path, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Response.Free;
end;
end;
function TOpenAIAPI.PostForm<TResult, TParams>(const Path: string; ParamProc: TProc<TParams>): TResult;
var
Response: TStringStream;
Params: TParams;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
Params := TParams.Create;
try
if Assigned(ParamProc) then
ParamProc(Params);
Code := Post(Path, Params, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Params.Free;
Response.Free;
end;
end;
function TOpenAIAPI.Get<TResult, TParams>(const Path: string; ParamProc: TProc<TParams>): TResult;
var
Response: TStringStream;
Params: TParams;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
Params := TParams.Create;
try
if Assigned(ParamProc) then
ParamProc(Params);
var Pairs: TArray<string> := [];
for var Pair in Params.ToStringPairs do
Pairs := Pairs + [Pair.Key + '=' + Pair.Value];
var QPath := Path;
if Length(Pairs) > 0 then
QPath := QPath + '?' + string.Join('&', Pairs);
Code := Get(QPath, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Params.Free;
Response.Free;
end;
end;
function TOpenAIAPI.Get<TResult>(const Path: string): TResult;
var
Response: TStringStream;
Code: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
try
Code := Get(Path, Response);
Result := ParseResponse<TResult>(Code, Response.DataString);
finally
Response.Free;
end;
end;
function TOpenAIAPI.GetClient: THTTPClient;
begin
Result := THTTPClient.Create;
Result.ProxySettings := FProxySettings;
Result.ConnectionTimeout := FConnectionTimeout;
Result.ResponseTimeout := FResponseTimeout;
{$IF RTLVersion >= 35.0}
Result.SendTimeout := FSendTimeout;
{$ENDIF}
Result.AcceptCharSet := 'utf-8';
end;
procedure TOpenAIAPI.GetFile(const Path: string; Response: TStream);
var
Code: Integer;
Strings: TStringStream;
Client: THTTPClient;
begin
CheckAPI;
Client := GetClient;
try
Code := Client.Get(GetRequestURL(Path), Response, GetHeaders).StatusCode;
case Code of
200..299:
; {success}
else
Strings := TStringStream.Create;
try
Response.Position := 0;
Strings.LoadFromStream(Response);
ParseError(Code, Strings.DataString);
finally
Strings.Free;
end;
end;
finally
Client.Free;
end;
end;
function TOpenAIAPI.GetHeaders: TNetHeaders;
begin
// Additional headers are not required when using azure
if IsAzure then
Exit;
Result := [TNetHeader.Create('Authorization', 'Bearer ' + FToken)] + FCustomHeaders;
if not FOrganization.IsEmpty then
Result := Result + [TNetHeader.Create('OpenAI-Organization', FOrganization)];
end;
function TOpenAIAPI.GetRequestURL(const Path: string): string;
begin
Result := FBaseURL + '/';
if IsAzure then
Result := Result + AzureDeployment + '/';
Result := Result + Path;
// API-Key and API-Version have to be included in the request not header when using azure
if IsAzure then
Result := Result + Format('?api-version=%s&api-key=%s', [AzureApiVersion, Token]);
end;
procedure TOpenAIAPI.CheckAPI;
begin
if FToken.IsEmpty then
raise OpenAIExceptionAPI.Create('Token is empty!');
if FBaseUrl.IsEmpty then
raise OpenAIExceptionAPI.Create('Base url is empty!');
end;
procedure TOpenAIAPI.ParseAndRaiseError(Error: TError; Code: Int64);
begin
case Code of
429:
raise OpenAIExceptionRateLimitError.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
400, 404, 415:
raise OpenAIExceptionInvalidRequestError.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
401:
raise OpenAIExceptionAuthenticationError.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
403:
raise OpenAIExceptionPermissionError.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
409:
raise OpenAIExceptionTryAgain.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
else
raise OpenAIException.Create(Error.Message, Error.&Type, Error.Param, Error.Code);
end;
end;
procedure TOpenAIAPI.ParseError(const Code: Int64; const ResponseText: string);
var
Error: TErrorResponse;
begin
Error := nil;
try
try
Error := TJson.JsonToObject<TErrorResponse>(ResponseText);
except
Error := nil;
end;
if Assigned(Error) and Assigned(Error.Error) then
ParseAndRaiseError(Error.Error, Code)
else
raise OpenAIException.Create('Unknown error. Code: ' + Code.ToString, '', '', Code);
finally
Error.Free;
end;
end;
function TOpenAIAPI.ParseResponse<T>(const Code: Int64; const ResponseText: string): T;
begin
case Code of
200..299:
try
Result := TJson.JsonToObject<T>(ResponseText);
except
Result := nil;
end;
else
ParseError(Code, ResponseText);
end;
if not Assigned(Result) then
raise OpenAIExceptionInvalidResponse.Create('Empty or invalid response', '', '', Code);
end;
procedure TOpenAIAPI.SetBaseUrl(const Value: string);
begin
FBaseUrl := Value;
end;
procedure TOpenAIAPI.SetConnectionTimeout(const Value: Integer);
begin
FConnectionTimeout := Value;
end;
procedure TOpenAIAPI.SetCustomHeaders(const Value: TNetHeaders);
begin
FCustomHeaders := Value;
end;
procedure TOpenAIAPI.SetOrganization(const Value: string);
begin
FOrganization := Value;
end;
procedure TOpenAIAPI.SetProxySettings(const Value: TProxySettings);
begin
FProxySettings := Value;
end;
procedure TOpenAIAPI.SetResponseTimeout(const Value: Integer);
begin
FResponseTimeout := Value;
end;
procedure TOpenAIAPI.SetSendTimeout(const Value: Integer);
begin
FSendTimeout := Value;
end;
procedure TOpenAIAPI.SetToken(const Value: string);
begin
FToken := Value;
end;
{ OpenAIException }
constructor OpenAIException.Create(const Text, &Type, Param: string; Code: Int64);
begin
inherited Create(Text);
Self.&Type := &Type;
Self.Code := Code;
Self.Param := Param;
end;
{ TOpenAIAPIRoute }
constructor TOpenAIAPIRoute.CreateRoute(AAPI: TOpenAIAPI);
begin
inherited Create;
FAPI := AAPI;
end;
procedure TOpenAIAPIRoute.SetAPI(const Value: TOpenAIAPI);
begin
FAPI := Value;
end;
end.