-
Notifications
You must be signed in to change notification settings - Fork 58
/
OpenAI.Chat.pas
1521 lines (1381 loc) · 50.9 KB
/
OpenAI.Chat.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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit OpenAI.Chat;
interface
uses
System.SysUtils, OpenAI.API.Params, OpenAI.API, OpenAI.Chat.Functions,
System.Classes, REST.JsonReflect, System.JSON, OpenAI.Types;
{$SCOPEDENUMS ON}
type
/// <summary>
/// Type of message role
/// </summary>
TMessageRole = (
/// <summary>
/// System message
/// </summary>
System,
/// <summary>
/// User message
/// </summary>
User,
/// <summary>
/// Assistant message
/// </summary>
Assistant,
/// <summary>
/// Func message. For models avaliable functions
/// </summary>
Func,
/// <summary>
/// Tool message
/// </summary>
Tool);
TMessageRoleHelper = record helper for TMessageRole
function ToString: string;
class function FromString(const Value: string): TMessageRole; static;
end;
/// <summary>
/// Finish reason
/// </summary>
TFinishReason = (
/// <summary>
/// API returned complete model output
/// </summary>
Stop,
/// <summary>
/// Incomplete model output due to max_tokens parameter or token limit
/// </summary>
Length,
/// <summary>
/// The model decided to call a function
/// </summary>
FunctionCall,
/// <summary>
/// Omitted content due to a flag from our content filters
/// </summary>
ContentFilter,
/// <summary>
/// API response still in progress or incomplete
/// </summary>
Null,
/// <summary>
/// If the model called a tool
/// </summary>
ToolCalls);
TFinishReasonHelper = record helper for TFinishReason
function ToString: string;
class function Create(const Value: string): TFinishReason; static;
end;
TFinishReasonInterceptor = class(TJSONInterceptorStringToString)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
TFunctionCallType = (None, Auto, Func);
TFunctionCall = record
private
FFuncName: string;
FType: TFunctionCallType;
public
/// <summary>
/// The model does not call a function, and responds to the end-user
/// </summary>
class function None: TFunctionCall; static;
/// <summary>
/// The model can pick between an end-user or calling a function
/// </summary>
class function Auto: TFunctionCall; static;
/// <summary>
/// Forces the model to call that function
/// </summary>
class function Func(const Name: string): TFunctionCall; static;
function ToString: string;
end;
TFunctionCallBuild = record
Name: string;
/// <summary>
/// JSON, example '{ \"location\": \"Boston, MA\"}'
/// </summary>
Arguments: string;
// helpers
class function Create(const Name, Arguments: string): TFunctionCallBuild; static;
end;
TChatToolCallBuild = record
/// <summary>
/// The ID of the tool call.
/// </summary>
Id: string;
/// <summary>
/// The type of the tool. Currently, only function is supported.
/// </summary>
&Type: string;
/// <summary>
/// The function that the model called.
/// </summary>
&Function: TFunctionCallBuild;
// helpers
class function Create(const Id, &Type: string; &Function: TFunctionCallBuild): TChatToolCallBuild; static;
end;
TMessageContentType = (Text, ImageUrl);
TImageDetail = (
/// <summary>
/// By default, the model will use the auto setting which will look at the image input size
/// and decide if it should use the low or high setting
/// </summary>
Auto,
/// <summary>
/// Will disable the “high res” model. The model will receive a low-res 512px x 512px version of the image,
/// and represent the image with a budget of 65 tokens. This allows the API to return faster responses and
/// consume fewer input tokens for use cases that do not require high detail.
/// </summary>
Low,
/// <summary>
/// Will enable “high res” mode, which first allows the model to see the low res image and then
/// creates detailed crops of input images as 512px squares based on the input image size.
/// Each of the detailed crops uses twice the token budget (65 tokens) for a total of 129 tokens.
/// </summary>
High);
TImageDetailHelper = record helper for TImageDetail
function ToString: string; inline;
end;
TMessageContent = record
/// <summary>
/// The type of the content part.
/// </summary>
ContentType: TMessageContentType;
/// <summary>
/// The text content.
/// </summary>
Text: string;
/// <summary>
/// Either a URL of the image or the base64 encoded image data.
/// </summary>
Url: string;
/// <summary>
/// Specifies the detail level of the image. Learn more in the Vision guide.
/// </summary>
/// <seealso>https://platform.openai.com/docs/guides/vision/low-or-high-fidelity-image-understanding</seealso>
Detail: TImageDetail;
//helpers
class function CreateText(const Text: string): TMessageContent; static;
/// <summary>
/// The Chat Completions API, unlike the Assistants API, is not stateful.
/// That means you have to manage the messages (including images) you pass to the model yourself.
/// If you want to pass the same image to the model multiple times, you will have to pass the image each time
/// you make a request to the API.
///
/// For long running conversations, we suggest passing images via URL's instead of base64.
/// The latency of the model can also be improved by downsizing your images ahead of time to be less than
/// the maximum size they are expected them to be. For low res mode, we expect a 512px x 512px image.
/// For high rest mode, the short side of the image should be less than 768px and the long side should be less
/// than 2,000px.
/// </summary>
class function CreateImage(const Url: string; const Detail: TImageDetail = TImageDetail.Auto): TMessageContent; overload; static;
/// <summary>
/// The Chat Completions API, unlike the Assistants API, is not stateful.
/// That means you have to manage the messages (including images) you pass to the model yourself.
/// If you want to pass the same image to the model multiple times, you will have to pass the image each time
/// you make a request to the API.
///
/// For long running conversations, we suggest passing images via URL's instead of base64.
/// The latency of the model can also be improved by downsizing your images ahead of time to be less than
/// the maximum size they are expected them to be. For low res mode, we expect a 512px x 512px image.
/// For high rest mode, the short side of the image should be less than 768px and the long side should be less
/// than 2,000px.
/// </summary>
class function CreateImage(const Data: TBase64Data; const Detail: TImageDetail = TImageDetail.Auto): TMessageContent; overload; static;
/// <summary>
/// The Chat Completions API, unlike the Assistants API, is not stateful.
/// That means you have to manage the messages (including images) you pass to the model yourself.
/// If you want to pass the same image to the model multiple times, you will have to pass the image each time
/// you make a request to the API.
///
/// For long running conversations, we suggest passing images via URL's instead of base64.
/// The latency of the model can also be improved by downsizing your images ahead of time to be less than
/// the maximum size they are expected them to be. For low res mode, we expect a 512px x 512px image.
/// For high rest mode, the short side of the image should be less than 768px and the long side should be less
/// than 2,000px.
/// </summary>
class function CreateImage(const Data: TStream; const FileContentType: string; const Detail: TImageDetail = TImageDetail.Auto): TMessageContent; overload; static;
end;
TChatMessageBuild = record
private
FRole: TMessageRole;
FContent: string;
FTool_call_id: string;
FFunction_call: TFunctionCallBuild;
FTool_calls: TArray<TChatToolCallBuild>;
FTag: string;
FName: string;
FContents: TArray<TMessageContent>;
FRefusal: string;
public
/// <summary>
/// The role of the messages author. One of "system", "user", "assistant", "tool".
/// </summary>
property Role: TMessageRole read FRole write FRole;
/// <summary>
/// The contents of the message. content is required for all messages, and may be null
/// for assistant messages with function calls.
/// </summary>
property Content: string read FContent write FContent;
/// <summary>
/// An array of content parts with a defined type, each can be of type "text" or "image_url"
/// when passing in images.
/// You can pass multiple images by adding multiple "image_url" content parts.
/// Image input is only supported when using the "gpt-4-vision-preview" model.
/// </summary>
property Contents: TArray<TMessageContent> read FContents write FContents;
/// <summary>
/// The name of the author of this message. "name" is required if role is "function",
/// and it should be the name of the function whose response is in the content.
/// May contain a-z, A-Z, 0-9, and underscores, with a maximum length of 64 characters.
/// </summary>
property Name: string read FName write FName;
/// <summary>
/// The name and arguments of a function that should be called, as generated by the model.
/// </summary>
property FunctionCall: TFunctionCallBuild read FFunction_call write FFunction_call;
/// <summary>
/// Tag - custom field for convenience. Not used in requests!
/// </summary>
property Tag: string read FTag write FTag;
/// <summary>
/// Tool call that this message is responding to.
/// </summary>
property ToolCallId: string read FTool_call_id write FTool_call_id;
/// <summary>
/// The tool calls generated by the model, such as function calls.
/// </summary>
property ToolCalls: TArray<TChatToolCallBuild> read FTool_calls write FTool_calls;
/// <summary>
/// The refusal message by the assistant.
/// </summary>
property Refusal: string read FRefusal write FRefusal;
// helpers
class function Create(Role: TMessageRole; const Content: string; const Name: string = ''): TChatMessageBuild; static;
//Help functions
/// <summary>
/// From user
/// </summary>
class function User(const Content: string; const Name: string = ''): TChatMessageBuild; overload; static;
/// <summary>
/// From user
/// </summary>
class function User(const Content: TArray<TMessageContent>; const Name: string = ''): TChatMessageBuild; overload; static;
/// <summary>
/// From system
/// </summary>
class function System(const Content: string; const Name: string = ''): TChatMessageBuild; static;
/// <summary>
/// From assistant
/// </summary>
class function Assistant(const Content: string; const Name: string = ''): TChatMessageBuild; static;
/// <summary>
/// Function result
/// </summary>
class function Func(const Content: string; const Name: string = ''): TChatMessageBuild; static;
/// <summary>
/// Tool result
/// </summary>
class function Tool(const Content, ToolCallId: string; const Name: string = ''): TChatMessageBuild; static;
/// <summary>
/// Assistant want call function
/// </summary>
class function AssistantFunc(const Name, Arguments: string): TChatMessageBuild; static;
/// <summary>
/// Assistant want call tool
/// </summary>
class function AssistantTool(const Content: string; const ToolCalls: TArray<TChatToolCallBuild>): TChatMessageBuild; static;
end;
TChatFunctionBuild = record
private
FName: string;
FDescription: string;
FParameters: string;
public
/// <summary>
/// The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes,
/// with a maximum length of 64.
/// </summary>
property Name: string read FName write FName;
/// <summary>
/// The description of what the function does.
/// </summary>
property Description: string read FDescription write FDescription;
/// <summary>
/// The parameters the functions accepts, described as a JSON Schema object
/// </summary>
property Parameters: string read FParameters write FParameters;
class function Create(const Name, Description: string; const ParametersJSON: string): TChatFunctionBuild; static;
end;
TChatResponseFormat = (Text, JSONObject, JSONSchema);
TChatResponseFormatHelper = record helper for TChatResponseFormat
function ToString: string; inline;
end;
TChatToolParam = class(TJSONParam)
protected
/// <summary>
/// The type of the tool. Currently, only function is supported.
/// </summary>
function &Type(const Value: string): TChatToolParam;
end;
TChatToolFunctionParam = class(TChatToolParam)
/// <summary>
/// The type of the tool. Currently, only function is supported.
/// </summary>
function &Function(const Value: IChatFunction): TChatToolFunctionParam;
constructor Create; reintroduce; overload;
constructor Create(const Value: IChatFunction); reintroduce; overload;
end;
TChatToolChoiceParam = record
private
FFuncName: string;
FType: TFunctionCallType;
public
/// <summary>
/// The model does not call a function, and responds to the end-user
/// </summary>
class function None: TChatToolChoiceParam; static;
/// <summary>
/// The model can pick between an end-user or calling a function
/// </summary>
class function Auto: TChatToolChoiceParam; static;
/// <summary>
/// Forces the model to call that function
/// </summary>
class function Func(const Name: string): TChatToolChoiceParam; static;
end;
TJSONSchemaFormat = class(TJSONParam)
/// <summary>
/// Optional
/// A description of what the response format is for, used by the model to determine how to respond in the format.
/// </summary>
function Description(const Value: string): TJSONSchemaFormat;
/// <summary>
/// The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
/// </summary>
function Name(const Value: string): TJSONSchemaFormat;
/// <summary>
/// Optional
/// The schema for the response format, described as a JSON Schema object.
/// </summary>
function Schema(const Value: TJSONValue): TJSONSchemaFormat;
/// <summary>
/// Optional
/// Whether to enable strict schema adherence when generating the output.
/// If set to true, the model will always follow the exact schema defined in the schema field.
/// Only a subset of JSON Schema is supported when strict is true. To learn more, read the Structured Outputs guide.
/// </summary>
/// <seealso>https://platform.openai.com/docs/guides/structured-outputs</seealso>
function strict(const Value: Boolean = True): TJSONSchemaFormat;
end;
TChatParams = class(TJSONParam)
/// <summary>
/// ID of the model to use. See the model endpoint compatibility table for details on which models
/// work with the Chat API.
/// </summary>
/// <seealso>https://platform.openai.com/docs/models/model-endpoint-compatibility</seealso>
function Model(const Value: string): TChatParams;
/// <summary>
/// A list of messages comprising the conversation so far.
/// </summary>
function Messages(const Value: TArray<TChatMessageBuild>): TChatParams; overload;
/// <summary>
/// A list of functions the model may generate JSON inputs for.
/// </summary>
function Functions(const Value: TArray<IChatFunction>): TChatParams; deprecated 'Use Tools';
/// <summary>
/// Controls how the model responds to function calls. none means the model does not call a function,
/// and responds to the end-user. auto means the model can pick between an end-user or calling a function.
/// Specifying a particular function via {"name": "my_function"} forces the model to call that function.
/// none is the default when no functions are present. auto is the default if functions are present.
/// </summary>
function FunctionCall(const Value: TFunctionCall): TChatParams; deprecated 'Use ToolChoice';
/// <summary>
/// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random,
/// while lower values like 0.2 will make it more focused and deterministic.
/// We generally recommend altering this or top_p but not both.
/// </summary>
function Temperature(const Value: Single): TChatParams;
/// <summary>
/// A list of tools the model may call. Currently, only functions are supported as a tool.
/// Use this to provide a list of functions the model may generate JSON inputs for.
/// A max of 128 functions are supported.
/// </summary>
function Tools(const Value: TArray<TChatToolParam>): TChatParams;
/// <summary>
/// Controls which (if any) function is called by the model.
/// "none" means the model will not call a function and instead generates a message.
/// "auto" means the model can pick between generating a message or calling a function.
/// Specifying a particular function via {"type: "function", "function": {"name": "my_function"}}
/// forces the model to call that function.
/// "none" is the default when no functions are present. "auto" is the default if functions are present.
/// </summary>
function ToolChoice(const Value: TChatToolChoiceParam): TChatParams;
/// <summary>
/// Whether to enable parallel function calling during tool use.
/// </summary>
/// <seealso>https://platform.openai.com/docs/guides/function-calling/parallel-function-calling</seealso>
function ParallelToolCalls(const Value: Boolean): TChatParams;
/// <summary>
/// An alternative to sampling with temperature, called nucleus sampling, where the model considers the
/// results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10%
/// probability mass are considered.
/// We generally recommend altering this or temperature but not both.
/// </summary>
function TopP(const Value: Single): TChatParams;
/// <summary>
/// How many chat completion choices to generate for each input message.
/// Note that you will be charged based on the number of generated tokens across all of the choices.
/// Keep n as 1 to minimize costs.
/// </summary>
function N(const Value: Integer): TChatParams;
/// <summary>
/// If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as
/// data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.
/// </summary>
function Stream(const Value: Boolean = True): TChatParams;
/// <summary>
/// Options for streaming response. Only set this when you set stream: true.
/// </summary>
/// <param name="IncludeUsage: Boolean = True">If set, an additional chunk will be streamed before the data:
/// [DONE] message. The usage field on this chunk shows the token usage statistics for the entire request,
/// and the choices field will always be an empty array. All other chunks will also include a usage field,
/// but with a null value.
/// </param>
function StreamOptions(const IncludeUsage: Boolean = True): TChatParams;
/// <summary>
/// An object specifying the format that the model must output.
/// Compatible with GPT-4 Turbo and all GPT-3.5 Turbo models newer than gpt-3.5-turbo-1106.
/// Setting to { "type": "json_object" } enables JSON mode, which guarantees the message the model
/// generates is valid JSON.
/// Important: when using JSON mode, you must also instruct the model to produce JSON yourself via a
/// system or user message. Without this, the model may generate an unending stream of whitespace until
/// the generation reaches the token limit, resulting in a long-running and seemingly "stuck" request.
/// Also note that the message content may be partially cut off if finish_reason="length",
/// which indicates the generation exceeded max_tokens or the conversation exceeded the max context length.
/// </summary>
function ResponseFormat(const Value: TChatResponseFormat; SchemaFormat: TJSONSchemaFormat = nil): TChatParams;
/// <summary>
/// This feature is in Beta. If specified, our system will make a best effort to sample
/// deterministically, such that repeated requests with the same seed and parameters
/// should return the same result. Determinism is not guaranteed, and you should refer
/// to the system_fingerprint response parameter to monitor changes in the backend.
/// </summary>
function Seed(const Value: Integer): TChatParams;
/// <summary>
/// Specifies the latency tier to use for processing the request.
/// This parameter is relevant for customers subscribed to the scale tier service:
/// </br>- If set to 'auto', the system will utilize scale tier credits until they are exhausted.
/// </br>- If set to 'default', the request will be processed using the default service tier with
/// a lower uptime SLA and no latency guarentee.
/// </br>- When not set, the default behavior is 'auto'.
/// </br> When this parameter is set, the response body will include the service_tier utilized.
/// </summary>
function ServiceTier(const Value: string): TChatParams; overload;
/// <summary>
/// Up to 4 sequences where the API will stop generating further tokens.
/// </summary>
function Stop(const Value: string): TChatParams; overload;
/// <summary>
/// Up to 4 sequences where the API will stop generating further tokens.
/// </summary>
function Stop(const Value: TArray<string>): TChatParams; overload;
/// <summary>
/// The maximum number of tokens that can be generated in the chat completion.
/// The total length of input tokens and generated tokens is limited by the model's context length.
/// </summary>
function MaxTokens(const Value: Integer): TChatParams;
/// <summary>
/// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear
/// in the text so far, increasing the model's likelihood to talk about new topics.
/// </summary>
function PresencePenalty(const Value: Single = 0): TChatParams;
/// <summary>
/// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency
/// in the text so far,
/// decreasing the model's likelihood to repeat the same line verbatim.
/// </summary>
function FrequencyPenalty(const Value: Single = 0): TChatParams;
/// <summary>
/// Modify the likelihood of specified tokens appearing in the completion.
///
/// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias
/// value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior
/// to sampling.
/// The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood
/// of selection;
/// values like -100 or 100 should result in a ban or exclusive selection of the relevant token.
/// </summary>
function LogitBias(const Value: TJSONObject): TChatParams;
/// <summary>
/// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
/// </summary>
function User(const Value: string): TChatParams;
/// <summary>
/// Whether to return log probabilities of the output tokens or not.
/// If true, returns the log probabilities of each output token returned in the content of message.
/// This option is currently not available on the gpt-4-vision-preview model.
/// </summary>
function Logprobs(const Value: Boolean = True): TChatParams;
/// <summary>
/// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position,
/// each with an associated log probability. logprobs must be set to true if this parameter is used.
/// </summary>
function TopLogprobs(const Value: Integer): TChatParams;
constructor Create; override;
end;
TChatUsage = class
private
FCompletion_tokens: Int64;
FPrompt_tokens: Int64;
FTotal_tokens: Int64;
public
/// <summary>
/// Number of tokens in the prompt.
/// </summary>
property PromptTokens: Int64 read FPrompt_tokens write FPrompt_tokens;
/// <summary>
/// Number of tokens in the generated completion.
/// </summary>
property CompletionTokens: Int64 read FCompletion_tokens write FCompletion_tokens;
/// <summary>
/// Total number of tokens used in the request (prompt + completion).
/// </summary>
property TotalTokens: Int64 read FTotal_tokens write FTotal_tokens;
end;
TChatFunctionCall = class
private
FName: string;
FArguments: string;
public
/// <summary>
/// The name of the function to call.
/// </summary>
property Name: string read FName write FName;
/// <summary>
/// The arguments to call the function with, as generated by the model in JSON format.
/// Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your
/// function schema. Validate the arguments in your code before calling your function.
/// JSON, example '{ \"location\": \"Boston, MA\"}'
/// </summary>
property Arguments: string read FArguments write FArguments;
end;
TChatToolCall = class
private
FId: string;
FType: string;
FFunction: TChatFunctionCall;
public
/// <summary>
/// The ID of the tool call.
/// </summary>
property Id: string read FId write FId;
/// <summary>
/// The type of the tool. Currently, only function is supported.
/// </summary>
property &Type: string read FType write FType;
/// <summary>
/// The function that the model called.
/// </summary>
property &Function: TChatFunctionCall read FFunction write FFunction;
destructor Destroy; override;
end;
TChatMessage = class
private
FRole: string;
FContent: string;
FFunction_call: TChatFunctionCall;
FTool_calls: TArray<TChatToolCall>;
FRefusal: string;
public
/// <summary>
/// The refusal message generated by the model.
/// </summary>
property Refusal: string read FRefusal write FRefusal;
/// <summary>
/// The role of the author of this message.
/// </summary>
property Role: string read FRole write FRole;
/// <summary>
/// The contents of the message.
/// </summary>
property Content: string read FContent write FContent;
/// <summary>
/// Deprecated and replaced by ToolCalls.
/// The name and arguments of a function that should be called, as generated by the model.
/// </summary>
property FunctionCall: TChatFunctionCall read FFunction_call write FFunction_call;
/// <summary>
/// The tool calls generated by the model, such as function calls.
/// </summary>
property ToolCalls: TArray<TChatToolCall> read FTool_calls write FTool_calls;
destructor Destroy; override;
end;
TLogprobContent = class
private
FToken: string;
FLogprob: Extended;
FBytes: TArray<Integer>;
FTop_logprobs: TArray<TLogprobContent>;
public
/// <summary>
/// The token.
/// </summary>
property Token: string read FToken write FToken;
/// <summary>
/// The log probability of this token, if it is within the top 20 most likely tokens.
/// Otherwise, the value -9999.0 is used to signify that the token is very unlikely.
/// </summary>
property Logprob: Extended read FLogprob write FLogprob;
/// <summary>
/// A list of integers representing the UTF-8 bytes representation of the token.
/// Useful in instances where characters are represented by multiple tokens and their byte
/// representations must be combined to generate the correct text representation.
/// Can be null if there is no bytes representation for the token.
/// </summary>
property Bytes: TArray<Integer> read FBytes write FBytes;
/// <summary>
/// List of the most likely tokens and their log probability, at this token position.
/// In rare cases, there may be fewer than the number of requested top_logprobs returned.
/// </summary>
property TopLogprobs: TArray<TLogprobContent> read FTop_logprobs write FTop_logprobs;
destructor Destroy; override;
end;
TLogprobs = class
private
FContent: TArray<TLogprobContent>;
public
/// <summary>
/// A list of message content tokens with log probability information.
/// </summary>
property Content: TArray<TLogprobContent> read FContent write FContent;
destructor Destroy; override;
end;
TChatChoices = class
private
FIndex: Int64;
FMessage: TChatMessage;
[JsonReflectAttribute(ctString, rtString, TFinishReasonInterceptor)]
FFinish_reason: TFinishReason;
FDelta: TChatMessage;
FLogprobs: TLogprobs;
public
/// <summary>
/// The index of the choice in the list of choices.
/// </summary>
property Index: Int64 read FIndex write FIndex;
/// <summary>
/// A chat completion message generated by the model.
/// </summary>
property Message: TChatMessage read FMessage write FMessage;
/// <summary>
/// A chat completion delta generated by streamed model responses.
/// </summary>
property Delta: TChatMessage read FDelta write FDelta;
/// <summary>
/// The reason the model stopped generating tokens.
/// This will be stop if the model hit a natural stop point or a provided stop sequence,
/// length if the maximum number of tokens specified in the request was reached,
/// content_filter if content was omitted due to a flag from our content filters,
/// tool_calls if the model called a tool, or function_call (deprecated) if the model called a function.
/// </summary>
property FinishReason: TFinishReason read FFinish_reason write FFinish_reason;
/// <summary>
/// Log probability information for the choice.
/// </summary>
property Logprobs: TLogprobs read FLogprobs write FLogprobs;
destructor Destroy; override;
end;
TChat = class
private
FChoices: TArray<TChatChoices>;
FCreated: Int64;
FId: string;
FObject: string;
FUsage: TChatUsage;
FModel: string;
FSystem_fingerprint: string;
FService_tier: string;
public
/// <summary>
/// A unique identifier for the chat completion.
/// </summary>
property Id: string read FId write FId;
/// <summary>
/// The object type, which is always chat.completion.
/// </summary>
property &Object: string read FObject write FObject;
/// <summary>
/// The Unix timestamp (in seconds) of when the chat completion was created.
/// </summary>
property Created: Int64 read FCreated write FCreated;
/// <summary>
/// The model used for the chat completion.
/// </summary>
property Model: string read FModel write FModel;
/// <summary>
/// The service tier used for processing the request.
/// This field is only included if the service_tier parameter is specified in the request.
/// </summary>
property ServiceTier: string read FService_tier write FService_tier;
/// <summary>
/// A list of chat completion choices. Can be more than one if N is greater than 1.
/// </summary>
property Choices: TArray<TChatChoices> read FChoices write FChoices;
/// <summary>
/// Usage statistics for the completion request.
/// </summary>
property Usage: TChatUsage read FUsage write FUsage;
/// <summary>
/// This fingerprint represents the backend configuration that the model runs with.
/// Can be used in conjunction with the seed request parameter to understand when backend
/// changes have been made that might impact determinism.
/// </summary>
property SystemFingerprint: string read FSystem_fingerprint write FSystem_fingerprint;
destructor Destroy; override;
end;
TChatEvent = reference to procedure(var Chat: TChat; IsDone: Boolean; var Cancel: Boolean);
/// <summary>
/// Given a chat conversation, the model will return a chat completion response.
/// </summary>
TChatRoute = class(TOpenAIAPIRoute)
public
/// <summary>
/// Creates a completion for the chat message
/// </summary>
/// <exception cref="OpenAIExceptionAPI"></exception>
/// <exception cref="OpenAIExceptionInvalidRequestError"></exception>
function Create(ParamProc: TProc<TChatParams>): TChat;
/// <summary>
/// Creates a completion for the chat message
/// </summary>
/// <remarks>
/// The Chat object will be nil if all data is received!
/// </remarks>
function CreateStream(ParamProc: TProc<TChatParams>; Event: TChatEvent): Boolean;
end;
implementation
uses
Rest.Json, System.Rtti, System.Net.HttpClient, OpenAI.Utils.Base64;
{ TChatRoute }
function TChatRoute.Create(ParamProc: TProc<TChatParams>): TChat;
begin
Result := API.Post<TChat, TChatParams>('chat/completions', ParamProc);
end;
function TChatRoute.CreateStream(ParamProc: TProc<TChatParams>; Event: TChatEvent): Boolean;
var
Response: TStringStream;
RetPos: Integer;
begin
Response := TStringStream.Create('', TEncoding.UTF8);
try
RetPos := 0;
Result := API.Post<TChatParams>('chat/completions', ParamProc, Response,
TReceiveDataCallback(
procedure(const Sender: TObject; AContentLength: Int64; AReadCount: Int64; var AAbort: Boolean)
var
IsDone: Boolean;
Data: string;
Chat: TChat;
TextBuffer: string;
Line: string;
Ret: Integer;
begin
try
TextBuffer := Response.DataString;
except
// If there is an encoding error, then the data is definitely not all.
// This is necessary because the data from the server may not be complete for successful encoding
on E: EEncodingError do
Exit;
end;
repeat
Ret := TextBuffer.IndexOf(#10, RetPos);
if Ret < 0 then
Continue;
Line := TextBuffer.Substring(RetPos, Ret - RetPos);
RetPos := Ret + 1;
if Line.IsEmpty or Line.StartsWith(#10) then
Continue;
Chat := nil;
Data := Line.Replace('data: ', '').Trim([' ', #13, #10]);
IsDone := Data = '[DONE]';
if not IsDone then
try
Chat := TJson.JsonToObject<TChat>(Data);
except
Chat := nil;
end;
try
Event(Chat, IsDone, AAbort);
finally
Chat.Free;
end;
until Ret < 0;
end));
finally
Response.Free;
end;
end;
{ TChat }
destructor TChat.Destroy;
var
Item: TChatChoices;
begin
if Assigned(FUsage) then
FUsage.Free;
for Item in FChoices do
Item.Free;
inherited;
end;
{ TChatParams }
constructor TChatParams.Create;
begin
inherited;
Model('gpt-3.5-turbo');
// Model('gpt-3.5-turbo-0613');
// Model('gpt-3.5-turbo-16k');
end;
function TChatParams.Functions(const Value: TArray<IChatFunction>): TChatParams;
var
Items: TJSONArray;
Item: IChatFunction;
begin
Items := TJSONArray.Create;
for Item in Value do
Items.Add(TChatFunction.ToJson(Item));
Result := TChatParams(Add('functions', Items));
end;
function TChatParams.LogitBias(const Value: TJSONObject): TChatParams;
begin
Result := TChatParams(Add('logit_bias', Value));
end;
function TChatParams.Logprobs(const Value: Boolean): TChatParams;
begin
Result := TChatParams(Add('logprobs', Value));
end;
function TChatParams.FunctionCall(const Value: TFunctionCall): TChatParams;
begin
Result := TChatParams(Add('function_call', Value.ToString));
end;
function TChatParams.FrequencyPenalty(const Value: Single): TChatParams;
begin
Result := TChatParams(Add('frequency_penalty', Value));
end;
function TChatParams.MaxTokens(const Value: Integer): TChatParams;
begin
Result := TChatParams(Add('max_tokens', Value));
end;
function TChatParams.Model(const Value: string): TChatParams;
begin
Result := TChatParams(Add('model', Value));
end;
function TChatParams.N(const Value: Integer): TChatParams;
begin
Result := TChatParams(Add('n', Value));
end;
function TChatParams.ParallelToolCalls(const Value: Boolean): TChatParams;
begin
Result := TChatParams(Add('parallel_tool_calls', Value));
end;
function TChatParams.PresencePenalty(const Value: Single): TChatParams;
begin
Result := TChatParams(Add('presence_penalty', Value));
end;
function TChatParams.ResponseFormat(const Value: TChatResponseFormat; SchemaFormat: TJSONSchemaFormat): TChatParams;
var
VJO: TJSONParam;
begin
VJO := TJSONParam.Create;
try
VJO.Add('type', Value.ToString);
if Value = TChatResponseFormat.JSONSchema then
begin
VJO.Add('json_schema', SchemaFormat);
SchemaFormat := nil;
end;
Result := TChatParams(Add('response_format', VJO));
finally
SchemaFormat.Free;
end;
end;
function TChatParams.Messages(const Value: TArray<TChatMessageBuild>): TChatParams;
var
Item: TChatMessageBuild;
ToolItem: TChatToolCallBuild;
JSON, ContentItem, ImageUrl: TJSONObject;
Content: TMessageContent;
Items, Tools, Contents: TJSONArray;
FuncData, ToolData: TJSONObject;
begin
Items := TJSONArray.Create;
try
for Item in Value do
begin
JSON := TJSONObject.Create;
//role
JSON.AddPair('role', Item.Role.ToString);
//content
if not Item.Content.IsEmpty then
JSON.AddPair('content', Item.Content)
else if Length(Item.Contents) > 0 then
begin
Contents := TJSONArray.Create;
JSON.AddPair('content', Contents);
for Content in Item.Contents do
begin
ContentItem := TJSONObject.Create;
Contents.Add(ContentItem);
case Content.ContentType of
TMessageContentType.Text:
begin
ContentItem.AddPair('type', 'text');
ContentItem.AddPair('text', Content.Text);
end;
TMessageContentType.ImageUrl:
begin
ContentItem.AddPair('type', 'image_url');
ImageUrl := TJSONObject.Create;
ContentItem.AddPair('image_url', ImageUrl);
ImageUrl.AddPair('url', Content.Url);
if Content.Detail <> TImageDetail.Auto then