forked from HemulGM/DelphiOpenAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOpenAI.API.pas
469 lines (419 loc) · 13.4 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
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
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
const
URL_BASE = 'https://api.openai.com/v1';
private
FHTTPClient: THTTPClient;
FToken: string;
FBaseUrl: string;
FOrganization: string;
FIsAzure: Boolean;
FAzureApiVersion: string;
FAzureDeployment: string;
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);
protected
function GetHeaders: TNetHeaders;
function GetRequestURL(const Path: string): string;
function Get(const Path: string; Response: TStringStream): Integer; overload;
function Delete(const Path: string; Response: TStringStream): Integer; overload;
function Post(const Path: string; Response: TStringStream): Integer; overload;
function Post(const Path: string; Body: TJSONObject; Response: TStringStream; OnReceiveData: TReceiveDataCallback = nil): Integer; overload;
function Post(const Path: string; Body: TMultipartFormData; Response: TStringStream): 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;
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: TStringStream; Event: TReceiveDataCallback): 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 Client: THTTPClient read FHTTPClient;
property IsAzure: Boolean read FIsAzure write FIsAzure;
property AzureApiVersion: string read FAzureApiVersion write FAzureApiVersion;
property AzureDeployment: string read FAzureDeployment write FAzureDeployment;
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;
constructor TOpenAIAPI.Create;
begin
inherited;
FHTTPClient := THTTPClient.Create;
// Defaults
FToken := '';
FBaseUrl := URL_BASE;
FIsAzure := false;
FAzureApiVersion := '';
FAzureDeployment := '';
end;
constructor TOpenAIAPI.Create(const AToken: string);
begin
Create;
Token := AToken;
end;
destructor TOpenAIAPI.Destroy;
begin
FHTTPClient.Free;
inherited;
end;
function TOpenAIAPI.Post(const Path: string; Body: TJSONObject; Response: TStringStream; OnReceiveData: TReceiveDataCallback): Integer;
var
Headers: TNetHeaders;
Stream: TStringStream;
begin
CheckAPI;
Headers := GetHeaders + [TNetHeader.Create('Content-Type', 'application/json')];
Stream := TStringStream.Create;
FHTTPClient.ReceiveDataCallBack := OnReceiveData;
try
Stream.WriteString(Body.ToJSON);
Stream.Position := 0;
Result := FHTTPClient.Post(GetRequestURL(Path), Stream, Response, Headers).StatusCode;
finally
FHTTPClient.OnReceiveData := nil;
Stream.Free;
end;
end;
function TOpenAIAPI.Get(const Path: string; Response: TStringStream): Integer;
var
Headers: TNetHeaders;
begin
CheckAPI;
Headers := GetHeaders;
Result := FHTTPClient.Get(GetRequestURL(Path), Response, Headers).StatusCode;
end;
function TOpenAIAPI.Post(const Path: string; Body: TMultipartFormData; Response: TStringStream): Integer;
var
Headers: TNetHeaders;
begin
CheckAPI;
Headers := GetHeaders;
Result := FHTTPClient.Post(GetRequestURL(Path), Body, Response, Headers).StatusCode;
end;
function TOpenAIAPI.Post(const Path: string; Response: TStringStream): Integer;
var
Headers: TNetHeaders;
Stream: TStringStream;
begin
CheckAPI;
Headers := GetHeaders;
Stream := nil;
try
Result := FHTTPClient.Post(GetRequestURL(Path), Stream, Response, Headers).StatusCode;
finally
//Stream.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: TStringStream; Event: TReceiveDataCallback): Boolean;
var
Params: TParams;
Code: Integer;
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;
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: TStringStream): Integer;
var
Headers: TNetHeaders;
begin
CheckAPI;
Headers := GetHeaders;
Result := FHTTPClient.Delete(GetRequestURL(Path), Response, Headers).StatusCode;
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>(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;
procedure TOpenAIAPI.GetFile(const Path: string; Response: TStream);
var
Headers: TNetHeaders;
Code: Integer;
Strings: TStringStream;
begin
CheckAPI;
Headers := GetHeaders;
Code := FHTTPClient.Get(GetRequestURL(Path), Response, Headers).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;
end;
function TOpenAIAPI.GetHeaders: TNetHeaders;
begin
// Additional headers are not required when using azure
if IsAzure then
exit;
Result := [TNetHeader.Create('Authorization', 'Bearer ' + FToken)];
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
begin
Result := Result + Format('?api-version=%s&api-key=%s', [AzureApiVersion, Token]);
end;
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
{$IFDEF ANDROID}
Error := TJson.JsonToObject<TErrorResponse>(ResponseText);
{$ELSE}
Error := TJson.JsonToObject<TErrorResponse>(UTF8ToString(RawByteString(ResponseText)));
{$ENDIF}
except
Error := nil;
end;
if Assigned(Error) and Assigned(Error.Error) then
ParseAndRaiseError(Error.Error, Code)
else
raise OpenAIException.Create('Unknown error', '', '', Code);
finally
if Assigned(Error) then
Error.Free;
end;
end;
function TOpenAIAPI.ParseResponse<T>(const Code: Int64; const ResponseText: string): T;
begin
case Code of
200..299:
try
{$IFDEF ANDROID}
Result := TJson.JsonToObject<T>(ResponseText);
{$ELSE}
//Result := TJson.JsonToObject<T>(UTF8ToString(RawByteString(ResponseText)));
Result := TJson.JsonToObject<T>(ResponseText);
{$ENDIF}
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.SetOrganization(const Value: string);
begin
FOrganization := 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.