-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathllm_utils.py
1000 lines (928 loc) · 55.7 KB
/
llm_utils.py
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
# imports
import random
import time
import openai
import os
import re
from copy import deepcopy
import tiktoken
import asyncio
# from openai.embeddings_utils import get_embedding, cosine_similarity
# Tokenizer
CL100K_ENCODER = tiktoken.get_encoding("cl100k_base")
P50K_ENCODER = tiktoken.get_encoding("p50k_base")
AZURE_SOUTH_ENDPOINT = ""
AZURE_MAIN_ENDPOINT = ""
AZURE_OPENAI_KEY_SOUTH = os.getenv("AZURE_OPENAI_KEY_SOUTH")
AZURE_OPENAI_KEY = os.getenv("AZURE_OPENAI_KEY")
AZURE_SWISS_ENDPOINT = ""
AZURE_NEW_UK_SOUTH_ENDPOINT = ""
KEY_SWISS = os.getenv("AZURE_OPENAI_KEY_SWISS_LATEST")
KEY_NEW_UK_SOUTH = os.getenv("AZURE_OPENAI_KEY_NEWUKSOUTH")
O1_KEY = os.getenv("AZURE_OPENAI_O1_KEY")
O1_API_BASE = "https://vdslabten-oai-eus.openai.azure.com/"
API_VERSION = "2024-02-15-preview"
AZURE_MODEL_DETAILS_MAP = {
"gpt4o-mini-202409": {'engine': "gpt4o-mini-202409",
'api_key': O1_KEY,
'api_version': "2023-07-01-preview",
'api_base': O1_API_BASE,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '1106-Preview',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
# 'max_tokens': 8192
'max_tokens': 128000
}},
"gpt-3.5-turbo": {'engine': "gpt35turbo0613_20230925",
'api_key': os.getenv("AZURE_OPENAI_KEY_SOUTH"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {'model_name': 'gpt-35-turbo',
'model_version': '0613',
'version_update_policy': 'Once the current version expires.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 80,
'rate_limit_(Tokens per minute)': 80000,
'rate_limit_(Requests per minute)': 480,
'max_tokens': 4097
}},
"gpt-3.5-turbo-16k": {'engine': "gpt35turbo-16k_20230904",
'api_key': os.getenv("AZURE_OPENAI_KEY_SOUTH"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {'model_name': 'gpt-35-turbo-16k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 120,
'rate_limit_(Tokens per minute)': 120000,
'rate_limit_(Requests per minute)': 720,
'max_tokens': 16385
}},
"gpt-3.5-turbo-old": {'engine': "gpt35turbo_20230727",
'api_key': os.getenv("AZURE_OPENAI_KEY"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_MAIN_ENDPOINT,
'api_type': "azure",
'properties': {'model_name': 'gpt-35-turbo',
'model_version': '0301',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 120,
'rate_limit_(Tokens per minute)': 120000,
'rate_limit_(Requests per minute)': 720,
'max_tokens': 4097
}},
"gpt-3.5-turbo-2": {'engine': "gpt35turbo_20230818",
'api_key': os.getenv("AZURE_OPENAI_KEY"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_MAIN_ENDPOINT,
'api_type': "azure",
'properties': {'model_name': 'gpt-35-turbo',
'model_version': '0301',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 120,
'rate_limit_(Tokens per minute)': 120000,
'rate_limit_(Requests per minute)': 720,
'max_tokens': 4097
}},
"text-embedding-ada-002": {'engine': "embAda002_20230727",
'api_key': os.getenv("AZURE_OPENAI_KEY"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_MAIN_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'text-embedding-ada-002',
'model_version': '2',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 120,
'rate_limit_(Tokens per minute)': 120000,
'rate_limit_(Requests per minute)': 720,
'max_tokens': 8191,
'max_batch_size': 16, # 2048 Should be, microsoft says 16 at this time
},},
"gpt-4": {'engine': "gpt4_20230815",
'api_key': os.getenv("AZURE_OPENAI_KEY_SOUTH"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 10,
'rate_limit_(Tokens per minute)': 10000,
'rate_limit_(Requests per minute)': 60,
'max_tokens': 8192
}}, # OLD GPT-4
"gpt-4-0": {'engine': "SWNorth-gpt-4-0613-20231016-4",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 10,
'rate_limit_(Tokens per minute)': 10000,
'rate_limit_(Requests per minute)': 60,
'max_tokens': 8192
}},
"gpt-4-1": {'engine': "SWNorth-gpt-4-0613-20231016-3",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 10,
'rate_limit_(Tokens per minute)': 10000,
'rate_limit_(Requests per minute)': 60,
'max_tokens': 8192
}},
"gpt-4-2": {'engine': "SWNorth-gpt-4-0613-20231016-2",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 10,
'rate_limit_(Tokens per minute)': 10000,
'rate_limit_(Requests per minute)': 60,
'max_tokens': 8192
}},
"gpt-4-latest-A": {'engine': "gpt4_20231230_1106preview",
'api_key': AZURE_OPENAI_KEY_SOUTH,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '1106-Preview',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
# 'max_tokens': 8192
'max_tokens': 128000
}},
"gpt-4-latest-B": {'engine': "gpt4_20240119_1106preview_B",
'api_key': AZURE_OPENAI_KEY_SOUTH,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '1106-Preview',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
# 'max_tokens': 8192
'max_tokens': 128000
}},
"gpt-4-latest-C": {'engine': "gpt4_20240119_1106preview_C",
'api_key': AZURE_OPENAI_KEY_SOUTH,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '1106-Preview',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
# 'max_tokens': 8192
'max_tokens': 128000
}},
"gpt-4-3": {'engine': "SWNorth-gpt-4-0613-20231016",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 10,
'rate_limit_(Tokens per minute)': 10000,
'rate_limit_(Requests per minute)': 60,
'max_tokens': 8192
}},
"gpt-4-32k-0": {'engine': "SWNorth-gpt-4-32k-0613-20231016-4",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4-32k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
'max_tokens': 32768
}},
"gpt-4-32k-1": {'engine': "SWNorth-gpt-4-32k-0613-20231016-3",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4-32k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
'max_tokens': 32768
}},
"gpt-4-32k-2": {'engine': "SWNorth-gpt-4-32k-0613-20231016-2",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4-32k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
'max_tokens': 32768
}},
"gpt-4-32k-3": {'engine': "SWNorth-gpt-4-32k-0613-20231016",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4-32k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 20,
'rate_limit_(Tokens per minute)': 20000,
'rate_limit_(Requests per minute)': 120,
'max_tokens': 32768
}},
"gpt-35-turbo-16k-0": {'engine': "SWNorth-gpt-35-turbo-16k-0613-20231016-5",
'api_key': KEY_SWISS,
'api_version': "2023-07-01-preview",
'api_base': AZURE_SWISS_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-35-turbo-16k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 60,
'rate_limit_(Tokens per minute)': 60000,
'rate_limit_(Requests per minute)': 360,
'max_tokens': 16385
}},
# "gpt-3-16k-misslabelled": {'engine': "gpt4-32k_20230815",
# 'api_key': os.getenv("AZURE_OPENAI_KEY_SOUTH"),
# 'api_version': "2023-07-01-preview",
# 'api_base': AZURE_SOUTH_ENDPOINT,
# 'api_type': "azure",
# 'properties': {
# 'model_name': 'gpt-35-turbo-16k',
# 'model_version': '0613',
# 'version_update_policy': 'Once a new default version is available.',
# 'deployment_type': 'Standard',
# 'content_filter': 'Default',
# 'tokens_per_minute_rate_limit_(thousands)': 120,
# 'rate_limit_(Tokens per minute)': 120000,
# 'rate_limit_(Requests per minute)': 720,
# 'max_tokens': 16385
# }}
"gpt-4-32k": {'engine': "gpt4-32k_20230830",
'api_key': os.getenv("AZURE_OPENAI_KEY_SOUTH"),
'api_version': "2023-07-01-preview",
'api_base': AZURE_SOUTH_ENDPOINT,
'api_type': "azure",
'properties': {
'model_name': 'gpt-4-32k',
'model_version': '0613',
'version_update_policy': 'Once a new default version is available.',
'deployment_type': 'Standard',
'content_filter': 'Default',
'tokens_per_minute_rate_limit_(thousands)': 30,
'rate_limit_(Tokens per minute)': 30000,
'rate_limit_(Requests per minute)': 180,
'max_tokens': 32768
}}
}
OPENAI_MODEL_DETAILS_MAP = {
'default': {
'tpm': 250000,
'rpm': 3000
},
'gpt-3.5-turbo': {
'tpm': 90000,
'rpm': 3500,
'max_tokens': 4097
},
'gpt-3.5-turbo-0301': {
'tpm': 90000,
'rpm': 3500,
'max_tokens': 4097
},
'gpt-3.5-turbo-0613': {
'tpm': 90000,
'rpm': 3500,
'max_tokens': 4097
},
'gpt-3.5-turbo-16k': {
'tpm': 180000,
'rpm': 3500,
'max_tokens': 16385
},
'gpt-3.5-turbo-16k-0613': {
'tpm': 180000,
'rpm': 3500,
'max_tokens': 16385
},
'gpt-4': {
'tpm': 40000,
'rpm': 200,
'max_tokens': 8192
},
'gpt-4-0314': {
'tpm': 40000,
'rpm': 200,
'max_tokens': 8192
},
'gpt-4-0613': {
'tpm': 40000,
'rpm': 200,
'max_tokens': 8192
}
}
def get_llm_config(config, logger, name, rate_limiter):
return deepcopy({'model': config.run.model,
'temperature': config.run.temperature,
'top_p': config.run.top_p,
'frequency_penalty': config.run.frequency_penalty,
'presence_penalty': config.run.presence_penalty,
'stop': config.run.stop,
'request_timeout': config.setup.api_request_timeout,
'stream': config.setup.api_stream,
'_open_ai_rate_limit_requests_per_minute': config.setup.open_ai_rate_limit_requests_per_minute,
'_use_azure_api': config.setup.use_azure_api,
'_logger': logger,
'_name': name,
'_rate_limiter': rate_limiter,
'_retry_with_exponential_backoff__initial_delay': config.setup.api_retry_with_exponential_backoff__initial_delay,
'_retry_with_exponential_backoff__exponential_base': config.setup.api_retry_with_exponential_backoff__exponential_base,
'_retry_with_exponential_backoff__jitter': config.setup.api_retry_with_exponential_backoff__jitter,
'_retry_with_exponential_backoff__max_retries': config.setup.api_retry_with_exponential_backoff__max_retries})
def setup_chat_rate_limiter(config: dict):
if config.setup.use_azure_api:
model = config.run.model
model_details = AZURE_MODEL_DETAILS_MAP[model]
request_limit = model_details['properties']['rate_limit_(Requests per minute)']
token_limit = model_details['properties']['rate_limit_(Tokens per minute)']
else:
model = config.run.model
model_details = OPENAI_MODEL_DETAILS_MAP[model]
request_limit = model_details['rpm']
token_limit = model_details['tpm']
return request_limit, token_limit
def get_model_max_tokens(config: dict):
if config.setup.use_azure_api:
model = config.run.model
model_details = AZURE_MODEL_DETAILS_MAP[model]
max_tokens = model_details['properties']['max_tokens']
else:
model = config.run.model
model_details = OPENAI_MODEL_DETAILS_MAP[model]
max_tokens = model_details['properties']['max_tokens']
return max_tokens
def pretty_print_chat_messages(messages, num_tokens=None, max_tokens=None, logger=None, response_msg=False, step_idx=None, total_steps=None, max_re_tries=None, re_tries=None):
COLORS = {
"system": "\033[95m", # Light Magenta
"user": "\033[94m", # Light Blue
"assistant": "\033[92m", # Light Green
"tokens": "\033[91m" # Light Red
}
if response_msg:
print("[LLM RESPONSE MESSAGE]") # Reset color at the end
if logger:
logger.info("[LLM RESPONSE MESSAGE]")
for msg in messages:
role = msg['role']
color = COLORS.get(role, COLORS["system"]) # Default to system color if role not found
formatted_role = role.capitalize()
content = msg['content']
if role == "assistant" and 'function_call' in msg:
formatted_role = "Function Call"
print(f"{color}[{formatted_role}] [{msg['function_call']['name']}] {msg['function_call']['arguments']}\033[0m") # Reset color at the end
if logger:
logger.info(f"[{formatted_role}] [{msg['function_call']['name']}] {msg['function_call']['arguments']}")
else:
print(f"{color}[{formatted_role}] {content}\033[0m") # Reset color at the end
if logger:
logger.info(f"[{formatted_role}] {content}")
if not response_msg:
if step_idx is not None and total_steps is not None:
if num_tokens and max_tokens:
if max_re_tries is not None and re_tries is not None:
print(f"{COLORS['tokens']}[Progress: Step {step_idx + 1}/{total_steps} | Retries: {re_tries}/{max_re_tries} | Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]\033[0m")
if logger:
logger.info(f"[Progress: Step {step_idx + 1}/{total_steps} | Retries: {re_tries}/{max_re_tries} | Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]")
else:
print(f"{COLORS['tokens']}[Progress: Step {step_idx + 1}/{total_steps} | Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]\033[0m")
if logger:
logger.info(f"[Progress: Step {step_idx + 1}/{total_steps} | Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]")
else:
if num_tokens and max_tokens:
print(f"{COLORS['tokens']}[Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]\033[0m")
if logger:
logger.info(f"[Token Capacity Used: {((num_tokens / max_tokens) * 100.0):.2f}% | Tokens remaining {max_tokens - num_tokens}]")
def chat_completion_rl(**kwargs):
# Implements retry_with_exponential_backoff
initial_delay = kwargs.get('_retry_with_exponential_backoff__initial_delay', 1)
exponential_base = kwargs.get('_retry_with_exponential_backoff__exponential_base', 2)
jitter = kwargs.get('_retry_with_exponential_backoff__jitter', True)
max_retries = kwargs.get('_retry_with_exponential_backoff__max_retries', 10)
use_azure_api = kwargs.get('_use_azure_api', True)
stream = kwargs.get('stream', False)
kwargs.pop('_retry_with_exponential_backoff__initial_delay', None)
kwargs.pop('_retry_with_exponential_backoff__exponential_base', None)
kwargs.pop('_retry_with_exponential_backoff__jitter', None)
kwargs.pop('_retry_with_exponential_backoff__max_retries', None)
kwargs.pop('_use_azure_api', None)
logger = kwargs.get('_logger', None)
name = kwargs.get('_name', None)
errors: tuple = (openai.error.RateLimitError,openai.error.APIError,openai.error.Timeout)
# Initialize variables
num_retries = 0
delay = initial_delay
# Loop until a successful response or max_retries is hit or an exception is raised
while True:
try:
if stream:
return asyncio.run(async_chat_completion_rl_inner(**kwargs))
else:
return chat_completion_rl_inner(**kwargs)
# Retry on specified errors
except errors as e:
# Increment retries
if logger:
logger.info(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries}")
else:
print(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries}")
num_retries += 1
# Check if max retries has been reached
if num_retries > max_retries:
if logger:
logger.info(f"[{name}][OpenAI API Request Error] Exception Maximum number of retries ({max_retries}) exceeded. | num_retries: {num_retries} / {max_retries}")
else:
print(f"[{name}][OpenAI API Request Error] Exception Maximum number of retries ({max_retries}) exceeded. | num_retries: {num_retries} / {max_retries}")
raise Exception(
f"Maximum number of retries ({max_retries}) exceeded."
)
# Increment the delay
delay *= exponential_base * (1 + jitter * random.random())
# Sleep for the delay
if use_azure_api:
match = re.search(r'Please retry after (\d+) seconds', e.args[0])
if match:
delay = int(match.group(1))
# delay = int(match.group(1))
if logger:
logger.info(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries} | Now sleeping for {delay} seconds")
else:
print(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries} | Now sleeping for {delay} seconds")
# time.sleep(delay // 2.0)
if delay > 60:
delay = 60
time.sleep(delay)
# Raise exceptions for any errors not specified
except Exception as e:
raise e
async def async_chat_completion_rl_inner(**kwargs):
logger = kwargs.get('_logger', None)
name = kwargs.get('_name', None)
use_azure_api = kwargs.get('_use_azure_api', True)
rate_limiter = kwargs.get('_rate_limiter', None)
model = kwargs.get('model', 'gpt-3.5-turbo')
if use_azure_api:
model_details = AZURE_MODEL_DETAILS_MAP[model]
kwargs.pop('model', None)
kwargs['engine'] = model_details['engine']
kwargs['api_key'] = model_details['api_key']
kwargs['api_version'] = model_details['api_version']
kwargs['api_base'] = model_details['api_base']
kwargs['api_type'] = model_details['api_type']
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs['_open_ai_rate_limit_requests_per_minute'] = model_details['properties']['rate_limit_(Requests per minute)']
# requests_per_minute = kwargs.get('_open_ai_rate_limit_requests_per_minute', 3000)
# delay_in_seconds = 60.0 / requests_per_minute
# time.sleep(delay_in_seconds)
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs.pop('_logger', None)
kwargs.pop('_name', None)
kwargs.pop('_rate_limiter', None)
kwargs.pop('_rate_limiter', None)
t0 = time.perf_counter()
# if logger:
# logger.info(f"[{name}][OpenAI API Request] {kwargs}")
# pretty_print_chat_messages(kwargs['messages'])
if rate_limiter:
rate_limiter.consume(**kwargs)
responses = await openai.ChatCompletion.acreate(**kwargs)
else:
responses = await openai.ChatCompletion.acreate(**kwargs)
response = {}
chunks = []
async for chunk in responses:
print(chunk)
if 'choices' not in chunk or len(chunk['choices']) == 0:
continue
chunk_message = chunk['choices'][0]['delta'].to_dict_recursive() # extract the message
chunks.append(chunk_message)
print(chunk_message)
for k, v in chunk_message.items():
if k in response:
if isinstance(response[k], dict):
for k2, v2 in v.items():
if k2 in response[k]:
response[k][k2] += v2
else:
response[k][k2] = v2
else:
response[k] += v
else:
response[k] = v
print(response)
return_response = {"choices": [{"message": response}]}
# if logger:
# logger.info(f"[{name}][OpenAI API Returned] Elapsed request time: {time.perf_counter() - t0}s | response: {response}")
return return_response
def chat_completion_rl_inner(**kwargs):
logger = kwargs.get('_logger', None)
name = kwargs.get('_name', None)
use_azure_api = kwargs.get('_use_azure_api', True)
rate_limiter = kwargs.get('_rate_limiter', None)
model = kwargs.get('model', 'gpt-3.5-turbo')
if use_azure_api:
model_details = AZURE_MODEL_DETAILS_MAP[model]
kwargs.pop('model', None)
kwargs['engine'] = model_details['engine']
kwargs['api_key'] = model_details['api_key']
kwargs['api_version'] = model_details['api_version']
kwargs['api_base'] = model_details['api_base']
kwargs['api_type'] = model_details['api_type']
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs['_open_ai_rate_limit_requests_per_minute'] = model_details['properties']['rate_limit_(Requests per minute)']
# requests_per_minute = kwargs.get('_open_ai_rate_limit_requests_per_minute', 3000)
# delay_in_seconds = 60.0 / requests_per_minute
# time.sleep(delay_in_seconds)
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs.pop('_logger', None)
kwargs.pop('_name', None)
kwargs.pop('_rate_limiter', None)
kwargs.pop('_rate_limiter', None)
kwargs.pop('stream', None)
t0 = time.perf_counter()
# if logger:
# logger.info(f"[{name}][OpenAI API Request] {kwargs}")
# pretty_print_chat_messages(kwargs['messages'])
if rate_limiter:
rate_limiter.consume(**kwargs)
response = openai.ChatCompletion.create(**kwargs)
else:
response = openai.ChatCompletion.create(**kwargs)
# if logger:
# logger.info(f"[{name}][OpenAI API Returned] Elapsed request time: {time.perf_counter() - t0}s | response: {response}")
return response
# =================================================================================================
# Embedding
def replace_newlines(input_data):
if isinstance(input_data, str):
return input_data.replace("\n", " ")
elif isinstance(input_data, list):
return [item.replace("\n", " ") for item in input_data]
else:
raise ValueError("Input should be either a string or a list of strings")
# Unit tests
def test_replace_newlines():
assert replace_newlines("Hello\nWorld") == "Hello World"
assert replace_newlines(["Hello\nWorld", "Python\nRocks"]) == ["Hello World", "Python Rocks"]
assert replace_newlines("No newline here") == "No newline here"
assert replace_newlines(["No newline here", "Neither here"]) == ["No newline here", "Neither here"]
assert replace_newlines("\n\n") == " "
assert replace_newlines(["\n", "\n\n"]) == [" ", " "]
print("All tests passed!")
def embedding_rl(input, **kwargs):
# Implements retry_with_exponential_backoff
initial_delay = kwargs.get('_retry_with_exponential_backoff__initial_delay', 1)
exponential_base = kwargs.get('_retry_with_exponential_backoff__exponential_base', 2)
jitter = kwargs.get('_retry_with_exponential_backoff__jitter', True)
max_retries = kwargs.get('_retry_with_exponential_backoff__max_retries', 10)
use_azure_api = kwargs.get('_use_azure_api', True)
kwargs.pop('_retry_with_exponential_backoff__initial_delay', None)
kwargs.pop('_retry_with_exponential_backoff__exponential_base', None)
kwargs.pop('_retry_with_exponential_backoff__jitter', None)
kwargs.pop('_retry_with_exponential_backoff__max_retries', None)
kwargs.pop('_use_azure_api', None)
logger = kwargs.get('_logger', None)
name = kwargs.get('_name', None)
errors: tuple = (openai.error.RateLimitError,)
# Initialize variables
num_retries = 0
delay = initial_delay
# Loop until a successful response or max_retries is hit or an exception is raised
while True:
try:
return embedding_rl_inner(input, **kwargs)
# Retry on specified errors
except errors as e:
# Increment retries
if logger:
logger.info(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries}")
else:
print(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries}")
num_retries += 1
# Check if max retries has been reached
if num_retries > max_retries:
if logger:
logger.info(f"[{name}][OpenAI API Request Error] Exception Maximum number of retries ({max_retries}) exceeded. | num_retries: {num_retries} / {max_retries}")
else:
print(f"[{name}][OpenAI API Request Error] Exception Maximum number of retries ({max_retries}) exceeded. | num_retries: {num_retries} / {max_retries}")
raise Exception(
f"Maximum number of retries ({max_retries}) exceeded."
)
# Increment the delay
delay *= exponential_base * (1 + jitter * random.random())
# Sleep for the delay
if use_azure_api:
match = re.search(r'Please retry after (\d+) seconds', e.args[0])
if match:
delay = int(match.group(1)) + 1.5
# delay = int(match.group(1))
if logger:
logger.info(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries} | Now sleeping for {delay} seconds")
else:
print(f"[{name}][OpenAI API Request Error] {type(e)} {e.args} | num_retries: {num_retries} / {max_retries} | Now sleeping for {delay} seconds")
time.sleep(delay // 2.0)
# Raise exceptions for any errors not specified
except Exception as e:
raise e
def embedding_rl_inner(input, **kwargs):
logger = kwargs.get('_logger', None)
name = kwargs.get('_name', None)
use_azure_api = kwargs.get('_use_azure_api', True)
rate_limiter = kwargs.get('_rate_limiter', None)
model = kwargs.get('model', 'text-embedding-ada-002')
if use_azure_api:
model_details = AZURE_MODEL_DETAILS_MAP[model]
kwargs.pop('model', None)
kwargs['engine'] = model_details['engine']
kwargs['api_key'] = model_details['api_key']
kwargs['api_version'] = model_details['api_version']
kwargs['api_base'] = model_details['api_base']
kwargs['api_type'] = model_details['api_type']
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs['_open_ai_rate_limit_requests_per_minute'] = model_details['properties']['rate_limit_(Requests per minute)']
# requests_per_minute = kwargs.get('_open_ai_rate_limit_requests_per_minute', 3000)
# delay_in_seconds = 60.0 / requests_per_minute
# time.sleep(delay_in_seconds)
kwargs.pop('_open_ai_rate_limit_requests_per_minute', None)
kwargs.pop('_logger', None)
kwargs.pop('_name', None)
kwargs.pop('_rate_limiter', None)
kwargs['input'] = replace_newlines(input)
t0 = time.perf_counter()
# if logger:
# logger.info(f"[{name}][OpenAI API Request] {kwargs}")
# pretty_print_chat_messages(kwargs['messages'])
embeddings = []
if rate_limiter:
# rate_limiter.consume(**kwargs)
response = openai.Embedding.create(**kwargs)
# response = get_embedding(**kwargs)
else:
response = openai.Embedding.create(**kwargs)
# response = get_embedding(**kwargs)
for i, be in enumerate(response["data"]):
assert i == be["index"] # double check embeddings are in same order as input
batch_embeddings = [e["embedding"] for e in response["data"]]
embeddings.extend(batch_embeddings)
# if logger:
# logger.info(f"[{name}][OpenAI API Returned] Elapsed request time: {time.perf_counter() - t0}s | response: {response}")
return embeddings
def num_tokens_consumed_by_chat_request(messages, max_tokens=15, n=1, functions='', **kwargs):
# num_tokens = n * max_tokens
# for message in messages:
# num_tokens += 4 # Every message follows <im_start>{role/name}\n{content}<im_end>\n
# for key, value in message.items():
# num_tokens += len(CL100K_ENCODER.encode(str(value)))
# if key == "name": # If there's a name, the role is omitted
# num_tokens -= 1
# num_tokens += 2 # Every reply is primed with <im_start>assistant
num_tokens = num_tokens_from_messages(messages)
if functions:
function_tokens = num_tokens_from_functions(functions)
num_tokens += function_tokens
return num_tokens
def num_tokens_from_messages(messages, model="gpt-4-0613"):
"""Return the number of tokens used by a list of messages."""
try:
encoding = tiktoken.encoding_for_model(model)
except KeyError:
print("Warning: model not found. Using cl100k_base encoding.")
encoding = tiktoken.get_encoding("cl100k_base")
if model in {
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-16k-0613",
"gpt-4-0314",
"gpt-4-32k-0314",
"gpt-4-0613",
"gpt-4-32k-0613",
}:
tokens_per_message = 3
tokens_per_name = 1
elif model == "gpt-3.5-turbo-0301":
tokens_per_message = 4 # every message follows <|start|>{role/name}\n{content}<|end|>\n
tokens_per_name = -1 # if there's a name, the role is omitted
elif "gpt-3.5-turbo" in model:
print("Warning: gpt-3.5-turbo may update over time. Returning num tokens assuming gpt-3.5-turbo-0613.")
return num_tokens_from_messages(messages, model="gpt-3.5-turbo-0613")
elif "gpt-4" in model:
print("Warning: gpt-4 may update over time. Returning num tokens assuming gpt-4-0613.")
return num_tokens_from_messages(messages, model="gpt-4-0613")
else:
raise NotImplementedError(
f"""num_tokens_from_messages() is not implemented for model {model}. See https://github.com/openai/openai-python/blob/main/chatml.md for information on how messages are converted to tokens."""
)
num_tokens = 0
for message in messages:
num_tokens += tokens_per_message
for key, value in message.items():
try:
num_tokens += len(encoding.encode(value))
except TypeError:
num_tokens += len(encoding.encode(str(value)))
if key == "name":
num_tokens += tokens_per_name
num_tokens += 3 # every reply is primed with <|start|>assistant<|message|>
return num_tokens
def num_tokens_from_functions(functions, model="gpt-3.5-turbo-0613"):
"""Return the number of tokens used by a list of functions."""
num_tokens = 0
for function in functions:
function_tokens = len(CL100K_ENCODER.encode(function['name']))
function_tokens += len(CL100K_ENCODER.encode(function['description']))
if 'parameters' in function:
parameters = function['parameters']
if 'properties' in parameters:
for propertiesKey in parameters['properties']:
function_tokens += len(CL100K_ENCODER.encode(propertiesKey))
v = parameters['properties'][propertiesKey]
for field in v:
if field == 'type':
function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(v['type']))
elif field == 'description':
function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(v['description']))
elif field == 'enum':
function_tokens -= 3
for o in v['enum']:
function_tokens += 3
function_tokens += len(CL100K_ENCODER.encode(o))
elif field == 'items':
# function_tokens += 2
# function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(v['type']))
if 'properties' in v[field]:
NestedParameters = v[field]
for NestedpropertiesKey in NestedParameters['properties']:
function_tokens += len(CL100K_ENCODER.encode(NestedpropertiesKey))
Nestedv = NestedParameters['properties'][NestedpropertiesKey]
for Nestedfield in Nestedv:
if Nestedfield == 'type':
# function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(Nestedv['type']))
elif Nestedfield == 'description':
# function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(Nestedv['description']))
elif Nestedfield == 'enum':
function_tokens -= 3
for Nestedo in Nestedv['enum']:
# function_tokens += 3
function_tokens += len(CL100K_ENCODER.encode(Nestedo))
elif field == 'items':
# function_tokens += 2
# function_tokens += 2
function_tokens += len(CL100K_ENCODER.encode(Nestedv['type']))
print('')
else:
print(f"Warning: not supported field {field} : {v[field]}")
function_tokens += 11
num_tokens += function_tokens
num_tokens += 12
return num_tokens
if __name__ == "__main__":
# Test OpenAI API
if False:
print(chat_completion_rl(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
],
max_tokens=5,
temperature=0.9,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n", "Human:", "AI:"]
))
# Test Azure API
if True:
from rate_limiter import ChatRateLimiter
rate_limiter = ChatRateLimiter(request_limit=200, token_limit=40000)
print(chat_completion_rl(
# model="gpt-3.5-turbo",
model="gpt-4-3",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"}
],
max_tokens=5,
temperature=0.9,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
stop=["\n", "Human:", "AI:"],
_use_azure_api=True,
_rate_limiter=rate_limiter
))
print('Done')
if False:
# Test Embedding from Azure API
# print(embedding_rl(text="The food was delicious and the waiter...",
# model="text-embedding-ada-002",
# _use_azure_api=True))
# print(embedding_rl(text="The food was delicious and the waiter...",
# model="text-embedding-ada-002",
# _use_azure_api=True))
# print('test batches')
# print(embedding_rl(["The food was delicious and the waiter...", "had to see what was made for dinner", "then the waiter came back and said"]))
print('test batches')
print(embedding_rl('asdas'))