-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
5465 lines (5080 loc) · 240 KB
/
main.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
import argparse
import json
import os
import platform
import re
import shutil
import time
from itertools import combinations
from typing import List, Tuple
import cohere
import gradio as gr
import oci
import oracledb
import pandas as pd
import requests
from dotenv import load_dotenv, find_dotenv, set_key, get_key
from langchain_anthropic import ChatAnthropic
from langchain_community.chat_models import ChatOCIGenAI
from langchain_community.embeddings import OCIGenAIEmbeddings
from langchain_community.vectorstores.utils import DistanceStrategy
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI, AzureChatOpenAI
from langfuse.callback import CallbackHandler
from oracledb import DatabaseError
from unstructured.chunking.title import chunk_by_title
from unstructured.partition.auto import partition
from my_langchain_community.vectorstores import MyOracleVS
from utils.common_util import get_dict_value
from utils.generator_util import generate_unique_id
custom_css = """
@font-face {
font-family: 'Noto Sans JP';
src: url('fonts/NotoSansJP-Regular.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Noto Sans SC';
src: url('fonts/NotoSansSC-Regular.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Noto Sans TC';
src: url('fonts/NotoSansSC-Regular.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Noto Sans HK';
src: url('fonts/NotoSansHK-Regular.otf') format('opentype');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Roboto';
src: url('fonts/Roboto-Regular.ttf') format('opentype');
font-weight: normal;
font-style: normal;
}
:root {
--global-font-family: "Noto Sans JP", "Noto Sans SC", "Noto Sans TC", "Noto Sans HK", "Roboto", Arial, sans-serif;
}
html, body, div, table, tr, td, p, strong, button {
font-family: var(--global-font-family) !important;
}
/* Hide sort buttons at gr.DataFrame */
.sort-button {
display: none !important;
}
body gradio-app .tabitem .block{
background: #fff !important;
}
.gradio-container{
background: #c4c4c440;
}
.tabitem .form{
border-radius: 3px;
}
.main_Header>span>h1{
color: #fff;
text-align: center;
margin: 0 auto;
display: block;
}
.tab-nav{
# border-bottom: none !important;
}
.tab-nav button[role="tab"]{
color: rgb(96, 96, 96);
font-weight: 500;
background: rgb(255, 255, 255);
padding: 10px 20px;
border-radius: 4px 4px 0px 0px;
border: none;
border-right: 4px solid gray;
border-radius: 0px;
min-width: 150px;
}
.tabs .tabitem .tabs .tab-nav button[role="tab"]{
min-width: 90px;
padding: 5px;
border-right: 1px solid #186fb4;
border-top: 1px solid #186fb4;
border-bottom: 0.2px solid #fff;
margin-bottom: -2px;
z-index: 3;
}
.tabs .tabitem .tabs .tab-nav button[role="tab"]:first-child{
border-left: 1px solid #186fb4;
border-top-left-radius: 3px;
}
.tabs .tabitem .tabs .tab-nav button[role="tab"]:last-child{
border-right: 1px solid #186fb4;
}
.tab-nav button[role="tab"]:first-child{
border-top-left-radius: 3px;
}
.tab-nav button[role="tab"]:last-child{
border-top-right-radius: 3px;
border-right: none;
}
.tabitem{
background: #fff;
border-radius: 0px 3px 3px 3px !important;
box-shadow: rgba(50, 50, 93, 0.25) 0px 2px 5px -1px, rgba(0, 0, 0, 0.3) 0px 1px 3px -1px;
}
.tabitem .tabitem{
border: 1px solid #196fb4;
background: #fff;
border-radius: 0px 3px 3px 3px !important;
}
.tabitem textarea, div.tabitem div.container>.wrap{
background: #f4f8ffc4;
}
.tabitem .container .wrap {
border-radius: 3px;
}
.tab-nav button[role="tab"].selected{
color: #fff;
background: #196fb4;
border-bottom: none;
}
.tabitem .inner_tab button[role="tab"]{
border: 1px solid rgb(25, 111, 180);
border-bottom: none;
}
.app.gradio-container {
max-width: 1440px;
}
gradio-app{
background-image: url("https://objectstorage.ap-tokyo-1.oraclecloud.com/n/sehubjapacprod/b/km_newsletter/o/tmp%2Fmain_bg.png") !important;
background-size: 100vw 100vh !important;
}
input, textarea{
border-radius: 3px;
}
.container>input:focus, .container>textarea:focus, .block .wrap .wrap-inner:focus{
border-radius: 3px;
box-shadow: rgb(255 246 228 / 63%) 0px 0px 0px 3px, rgb(255 248 236 / 12%) 0px 2px 4px 0px inset !important;
border-color: rgb(249 169 125 / 87%) !important;
}
.tabitem div>button.primary{
border: none;
background: linear-gradient(to bottom right, #ffc679, #f38141);
color: #fff;
box-shadow: 2px 2px 2px #0000001f;
border-radius: 3px;
}
.tabitem div>button.primary:hover{
border: none;
background: #f38141;
color: #fff;
border-radius: 3px;
box-shadow: 2px 2px 2px #0000001f;
}
.tabitem div>button.secondary{
border: none;
background: linear-gradient(to right bottom, rgb(215 215 217), rgb(194 197 201));
color: rgb(107 106 106);
box-shadow: rgba(0, 0, 0, 0.12) 2px 2px 2px;
border-radius: 3px;
}
.tabitem div>button.secondary:hover{
border: none;
background: rgb(175 175 175);
color: rgb(255 255 255);
border-radius: 3px;
box-shadow: rgba(0, 0, 0, 0.12) 2px 2px 2px;
}
.cus_ele1_select .container .wrap:focus-within{
border-radius: 3px;
box-shadow: rgb(255 246 228 / 63%) 0px 0px 0px 3px, rgb(255 248 236 / 12%) 0px 2px 4px 0px inset !important;
border-color: rgb(249 169 125 / 87%) !important;
}
input[type="checkbox"]:checked, input[type="checkbox"]:checked:hover, input[type="checkbox"]:checked:focus {
border-color: #186fb4;
background-color: #186fb4;
}
#event_tbl{
border-radius:3px;
}
#event_tbl .table-wrap{
border-radius:3px;
}
#event_tbl table thead>tr>th{
background: #bfd1e0;
min-width: 90px;
}
#event_tbl table thead>tr>th:first-child{
border-radius:3px 0px 0px 0px;
}
#event_tbl table thead>tr>th:last-child{
border-radius:0px 3px 0px 0px;
}
#event_tbl table .cell-wrap span{
font-size: 0.8rem;
}
#event_tbl table{
overflow-y: auto;
overflow-x: auto;
}
#event_exp_tbl .table-wrap{
border-radius:3px;
}
#event_exp_tbl table thead>tr>th{
background: #bfd1e0;
}
.count_t1_text .prose{
padding: 5px 0px 0px 6px;
}
.count_t1_text .prose>span{
padding: 0px;
}
.cus_ele1_select .container .wrap:focus-within{
border-radius: 3px;
box-shadow: rgb(255 246 228 / 63%) 0px 0px 0px 3px, rgb(255 248 236 / 12%) 0px 2px 4px 0px inset !important;
border-color: rgb(249 169 125 / 87%) !important;
}
.count_t1_text .prose>span{
font-size: 0.9rem;
}
footer{
display: none !important;
}
.sub_Header>span>h3,.sub_Header>span>h2,.sub_Header>span>h4{
color: #fff;
font-size: 0.8rem;
font-weight: normal;
text-align: center;
margin: 0 auto;
padding: 5px;
}
@media (min-width: 1280px) {
.app.svelte-wpkpf6.svelte-wpkpf6:not(.fill_width) {
max-width: 1400px;
}
}
.gap.svelte-vt1mxs{
gap: unset;
}
.tabitem .gap.svelte-vt1mxs{
gap: var(--layout-gap);
}
@media (min-width: 1280px) {
.app.svelte-wpkpf6.svelte-wpkpf6:not(.fill_width) {
max-width: 1400px;
}
}
"""
# read local .env file
load_dotenv(find_dotenv())
DEFAULT_COLLECTION_NAME = os.environ["DEFAULT_COLLECTION_NAME"]
if platform.system() == 'Linux':
oracledb.init_oracle_client(lib_dir=os.environ["ORACLE_CLIENT_LIB_DIR"])
# 初始化一个数据库连接
pool = oracledb.create_pool(
dsn=os.environ["ORACLE_23AI_CONNECTION_STRING"],
min=2,
max=5,
increment=1
)
def do_auth(username, password):
dsn = os.environ["ORACLE_23AI_CONNECTION_STRING"]
pattern = r"^([^/]+)/([^@]+)@"
match = re.match(pattern, dsn)
if match:
if username.lower() == match.group(1).lower() and password == match.group(2):
return True
return False
def get_region():
oci_config_path = find_dotenv("/root/.oci/config")
region = get_key(oci_config_path, "region")
return region
def generate_embedding_response(inputs: List[str]):
config = oci.config.from_file('/root/.oci/config', "DEFAULT")
region = get_region()
generative_ai_inference_client = oci.generative_ai_inference.GenerativeAiInferenceClient(config=config,
service_endpoint=f"https://inference.generativeai.{region}.oci.oraclecloud.com",
retry_strategy=oci.retry.NoneRetryStrategy(),
timeout=(10, 240))
batch_size = 96
all_embeddings = []
for i in range(0, len(inputs), batch_size):
batch = inputs[i:i + batch_size]
embed_text_detail = oci.generative_ai_inference.models.EmbedTextDetails()
embed_text_detail.serving_mode = oci.generative_ai_inference.models.OnDemandServingMode(
model_id=os.environ["OCI_COHERE_EMBED_MODEL"])
embed_text_detail.inputs = batch
embed_text_detail.truncate = "NONE"
embed_text_detail.compartment_id = os.environ["OCI_COMPARTMENT_OCID"]
embed_text_response = generative_ai_inference_client.embed_text(embed_text_detail)
print(f"Processed batch {i // batch_size + 1} of {(len(inputs) - 1) // batch_size + 1}")
all_embeddings.extend(embed_text_response.data.embeddings)
return all_embeddings
def get_doc_list() -> List[Tuple[str, str]]:
with pool.acquire() as conn:
with conn.cursor() as cursor:
try:
cursor.execute(f"""
SELECT
json_value(cmetadata, '$.file_name') name,
id
FROM
{DEFAULT_COLLECTION_NAME}_collection
ORDER BY name """)
return [(f"{row[0]}", row[1]) for row in cursor.fetchall()]
except DatabaseError as de:
return []
def refresh_doc_list():
doc_list = get_doc_list()
return (
gr.Radio(choices=doc_list, value=""),
gr.CheckboxGroup(choices=doc_list, value=""),
gr.CheckboxGroup(choices=doc_list, value="")
)
def get_server_path(doc_id: str) -> str:
with pool.acquire() as conn:
with conn.cursor() as cursor:
cursor.execute(f"""
SELECT json_value(cmetadata, '$.server_path') AS server_path
FROM {DEFAULT_COLLECTION_NAME}_collection
WHERE id = :doc_id """, doc_id=doc_id)
return cursor.fetchone()[0]
def process_text_chunks(unstructured_chunks):
chunks = []
chunk_id = 1
start_offset = 1
for chunk in unstructured_chunks:
chunk_length = len(chunk.text)
if chunk_length == 0:
continue
chunks.append({
'CHUNK_ID': chunk_id,
'CHUNK_OFFSET': start_offset,
'CHUNK_LENGTH': chunk_length,
'CHUNK_DATA': chunk.text
})
# 更新 ID 和偏移量
chunk_id += 1
start_offset += chunk_length
return chunks
async def command_r_task(system_text, query_text, command_r_checkbox):
region = get_region()
if command_r_checkbox:
command_r_16k = ChatOCIGenAI(
model_id="cohere.command-r-08-2024",
service_endpoint=f"https://inference.generativeai.{region}.oci.oraclecloud.com",
compartment_id=os.environ["OCI_COMPARTMENT_OCID"],
model_kwargs={"temperature": 0.0, "max_tokens": 2048},
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in command_r_16k.astream(messages, config={"callbacks": [langfuse_handler],
"metadata": {
"ls_model_name": "cohere.command-r-08-2024"}}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def command_r_plus_task(system_text, query_text, command_r_plus_checkbox):
region = get_region()
if command_r_plus_checkbox:
command_r_plus = ChatOCIGenAI(
model_id="cohere.command-r-plus",
service_endpoint=f"https://inference.generativeai.{region}.oci.oraclecloud.com",
compartment_id=os.environ["OCI_COMPARTMENT_OCID"],
model_kwargs={"temperature": 0.0, "max_tokens": 2048},
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in command_r_plus.astream(messages, config={"callbacks": [langfuse_handler],
"metadata": {
"ls_model_name": "cohere.command-r-plus"}}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def openai_gpt4o_task(system_text, query_text, openai_gpt4o_checkbox):
if openai_gpt4o_checkbox:
load_dotenv(find_dotenv())
openai_gpt4o = ChatOpenAI(
model="gpt-4o",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
api_key=os.environ["OPENAI_API_KEY"],
base_url=os.environ["OPENAI_BASE_URL"]
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in openai_gpt4o.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def openai_gpt4_task(system_text, query_text, openai_gpt4_checkbox):
if openai_gpt4_checkbox:
load_dotenv(find_dotenv())
openai_gpt4 = ChatOpenAI(
model="gpt-4",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
api_key=os.environ["OPENAI_API_KEY"],
base_url=os.environ["OPENAI_BASE_URL"]
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in openai_gpt4.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def azure_openai_gpt4o_task(system_text, query_text, azure_openai_gpt4o_checkbox):
if azure_openai_gpt4o_checkbox:
load_dotenv(find_dotenv())
azure_openai_gpt4o = AzureChatOpenAI(
deployment_name="gpt-4o",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT_GPT_4O"],
openai_api_key=os.environ["AZURE_OPENAI_API_KEY"],
openai_api_version=os.environ["AZURE_OPENAI_API_VERSION_GPT_4O"]
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in azure_openai_gpt4o.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def azure_openai_gpt4_task(system_text, query_text, azure_openai_gpt4_checkbox):
if azure_openai_gpt4_checkbox:
load_dotenv(find_dotenv())
azure_openai_gpt4 = AzureChatOpenAI(
deployment_name="gpt-4",
temperature=0,
max_tokens=None,
timeout=None,
max_retries=2,
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT_GPT_4"],
openai_api_key=os.environ["AZURE_OPENAI_API_KEY"],
openai_api_version=os.environ["AZURE_OPENAI_API_VERSION_GPT_4"]
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in azure_openai_gpt4.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def claude_3_opus_task(system_text, query_text, claude_3_opus_checkbox):
if claude_3_opus_checkbox:
load_dotenv(find_dotenv())
claude_3_opus = ChatAnthropic(
model="claude-3-opus-20240229",
temperature=0,
max_tokens=1024,
timeout=None,
max_retries=2,
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in claude_3_opus.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def claude_3_sonnet_task(system_text, query_text, claude_3_sonnet_checkbox):
if claude_3_sonnet_checkbox:
load_dotenv(find_dotenv())
claude_3_sonnet = ChatAnthropic(
model="claude-3-5-sonnet-20240620",
temperature=0,
max_tokens=1024,
timeout=None,
max_retries=2,
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in claude_3_sonnet.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def claude_3_haiku_task(system_text, query_text, claude_3_haiku_checkbox):
if claude_3_haiku_checkbox:
load_dotenv(find_dotenv())
claude_3_haiku = ChatAnthropic(
model="claude-3-haiku-20240307",
temperature=0,
max_tokens=1024,
timeout=None,
max_retries=2,
)
messages = [
SystemMessage(content=system_text),
HumanMessage(content=query_text),
]
start_time = time.time()
print(f"{start_time=}")
langfuse_handler = CallbackHandler(
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
host=os.environ["LANGFUSE_HOST"],
)
async for chunk in claude_3_haiku.astream(messages, config={"callbacks": [langfuse_handler]}):
yield chunk.content
end_time = time.time()
print(f"{end_time=}")
inference_time = end_time - start_time
print(f"\n推論時間: {inference_time:.2f}秒")
yield f"\n推論時間: {inference_time:.2f}秒"
yield "TASK_DONE"
else:
yield "TASK_DONE"
async def chat(
system_text,
command_r_user_text,
command_r_plus_user_text,
openai_gpt4o_user_text,
openai_gpt4_user_text,
azure_openai_gpt4o_user_text,
azure_openai_gpt4_user_text,
claude_3_opus_user_text,
claude_3_sonnet_user_text,
claude_3_haiku_user_text,
command_r_checkbox,
command_r_plus_checkbox,
openai_gpt4o_gen_checkbox,
openai_gpt4_gen_checkbox,
azure_openai_gpt4o_gen_checkbox,
azure_openai_gpt4_gen_checkbox,
claude_3_opus_checkbox,
claude_3_sonnet_checkbox,
claude_3_haiku_checkbox
):
command_r_gen = command_r_task(system_text, command_r_user_text, command_r_checkbox)
command_r_plus_gen = command_r_plus_task(system_text, command_r_plus_user_text, command_r_plus_checkbox)
openai_gpt4o_gen = openai_gpt4o_task(system_text, openai_gpt4o_user_text, openai_gpt4o_gen_checkbox)
openai_gpt4_gen = openai_gpt4_task(system_text, openai_gpt4_user_text, openai_gpt4_gen_checkbox)
azure_openai_gpt4o_gen = azure_openai_gpt4o_task(system_text, azure_openai_gpt4o_user_text,
azure_openai_gpt4o_gen_checkbox)
azure_openai_gpt4_gen = azure_openai_gpt4_task(system_text, azure_openai_gpt4_user_text,
azure_openai_gpt4_gen_checkbox)
claude_3_opus_gen = claude_3_opus_task(system_text, claude_3_opus_user_text, claude_3_opus_checkbox)
claude_3_sonnet_gen = claude_3_sonnet_task(system_text, claude_3_sonnet_user_text, claude_3_sonnet_checkbox)
claude_3_haiku_gen = claude_3_haiku_task(system_text, claude_3_haiku_user_text, claude_3_haiku_checkbox)
responses_status = ["", "", "", "", "", "", "", "", ""]
while True:
responses = ["", "", "", "", "", "", "", "", ""]
generators = [command_r_gen, command_r_plus_gen, openai_gpt4o_gen, openai_gpt4_gen,
azure_openai_gpt4o_gen, azure_openai_gpt4_gen,
claude_3_opus_gen, claude_3_sonnet_gen, claude_3_haiku_gen]
for i, gen in enumerate(generators):
try:
response = await anext(gen)
if response:
if response == "TASK_DONE":
responses_status[i] = response
else:
responses[i] = response
except StopAsyncIteration:
pass
yield tuple(responses)
if all(response_status == "TASK_DONE" for response_status in responses_status):
print("All tasks completed with DONE")
break
def set_chat_llm_answer(llm_answer_checkbox):
command_r_answer_visible = False
command_r_plus_answer_visible = False
openai_gpt4o_answer_visible = False
openai_gpt4_answer_visible = False
azure_openai_gpt4o_answer_visible = False
azure_openai_gpt4_answer_visible = False
claude_3_opus_answer_visible = False
claude_3_sonnet_answer_visible = False
claude_3_haiku_answer_visible = False
if "cohere/command-r" in llm_answer_checkbox:
command_r_answer_visible = True
if "cohere/command-r-plus" in llm_answer_checkbox:
command_r_plus_answer_visible = True
if "openai/gpt-4o" in llm_answer_checkbox:
openai_gpt4o_answer_visible = True
if "openai/gpt-4" in llm_answer_checkbox:
openai_gpt4_answer_visible = True
if "azure_openai/gpt-4o" in llm_answer_checkbox:
azure_openai_gpt4o_answer_visible = True
if "azure_openai/gpt-4" in llm_answer_checkbox:
azure_openai_gpt4_answer_visible = True
if "claude/opus" in llm_answer_checkbox:
claude_3_opus_answer_visible = True
if "claude/sonnet" in llm_answer_checkbox:
claude_3_sonnet_answer_visible = True
if "claude/haiku" in llm_answer_checkbox:
claude_3_haiku_answer_visible = True
return (gr.Accordion(visible=command_r_answer_visible),
gr.Accordion(visible=command_r_plus_answer_visible),
gr.Accordion(visible=openai_gpt4o_answer_visible),
gr.Accordion(visible=openai_gpt4_answer_visible),
gr.Accordion(visible=azure_openai_gpt4o_answer_visible),
gr.Accordion(visible=azure_openai_gpt4_answer_visible),
gr.Accordion(visible=claude_3_opus_answer_visible),
gr.Accordion(visible=claude_3_sonnet_answer_visible),
gr.Accordion(visible=claude_3_haiku_answer_visible))
def set_chat_llm_evaluation(llm_evaluation_checkbox):
command_r_evaluation_visible = False
command_r_plus_evaluation_visible = False
openai_gpt4o_evaluation_visible = False
openai_gpt4_evaluation_visible = False
azure_openai_gpt4o_evaluation_visible = False
azure_openai_gpt4_evaluation_visible = False
claude_3_opus_evaluation_visible = False
claude_3_sonnet_evaluation_visible = False
claude_3_haiku_evaluation_visible = False
if llm_evaluation_checkbox:
command_r_evaluation_visible = True
command_r_plus_evaluation_visible = True
openai_gpt4o_evaluation_visible = True
openai_gpt4_evaluation_visible = True
azure_openai_gpt4o_evaluation_visible = True
azure_openai_gpt4_evaluation_visible = True
claude_3_opus_evaluation_visible = True
claude_3_sonnet_evaluation_visible = True
claude_3_haiku_evaluation_visible = True
return (gr.Accordion(visible=command_r_evaluation_visible),
gr.Accordion(visible=command_r_plus_evaluation_visible),
gr.Accordion(visible=openai_gpt4o_evaluation_visible),
gr.Accordion(visible=openai_gpt4_evaluation_visible),
gr.Accordion(visible=azure_openai_gpt4o_evaluation_visible),
gr.Accordion(visible=azure_openai_gpt4_evaluation_visible),
gr.Accordion(visible=claude_3_opus_evaluation_visible),
gr.Accordion(visible=claude_3_sonnet_evaluation_visible),
gr.Accordion(visible=claude_3_haiku_evaluation_visible))
async def chat_stream(system_text, query_text, llm_answer_checkbox):
if not llm_answer_checkbox or len(llm_answer_checkbox) == 0:
raise gr.Error("LLM モデルを選択してください")
if not query_text:
raise gr.Error("ユーザー・メッセージを入力してください")
command_r_user_text = query_text
command_r_plus_user_text = query_text
openai_gpt4o_user_text = query_text
openai_gpt4_user_text = query_text
azure_openai_gpt4o_user_text = query_text
azure_openai_gpt4_user_text = query_text
claude_3_opus_user_text = query_text
claude_3_sonnet_user_text = query_text
claude_3_haiku_user_text = query_text
command_r_checkbox = False
command_r_plus_checkbox = False
openai_gpt4o_checkbox = False
openai_gpt4_checkbox = False
azure_openai_gpt4o_checkbox = False
azure_openai_gpt4_checkbox = False
claude_3_opus_checkbox = False
claude_3_sonnet_checkbox = False
claude_3_haiku_checkbox = False
if "cohere/command-r" in llm_answer_checkbox:
command_r_checkbox = True
if "cohere/command-r-plus" in llm_answer_checkbox:
command_r_plus_checkbox = True
if "openai/gpt-4o" in llm_answer_checkbox:
openai_gpt4o_checkbox = True
if "openai/gpt-4" in llm_answer_checkbox:
openai_gpt4_checkbox = True
if "azure_openai/gpt-4o" in llm_answer_checkbox:
azure_openai_gpt4o_checkbox = True
if "azure_openai/gpt-4" in llm_answer_checkbox:
azure_openai_gpt4_checkbox = True
if "claude/opus" in llm_answer_checkbox:
claude_3_opus_checkbox = True
if "claude/sonnet" in llm_answer_checkbox:
claude_3_sonnet_checkbox = True
if "claude/haiku" in llm_answer_checkbox:
claude_3_haiku_checkbox = True
# ChatOCIGenAI
command_r_response = ""
command_r_plus_response = ""
openai_gpt4o_response = ""
openai_gpt4_response = ""
azure_openai_gpt4o_response = ""
azure_openai_gpt4_response = ""
claude_3_opus_response = ""
claude_3_sonnet_response = ""
claude_3_haiku_response = ""
async for r, r_plus, gpt4o, gpt4, azure_gpt4o, azure_gpt4, opus, sonnet, haiku in chat(
system_text,
command_r_user_text,
command_r_plus_user_text,
openai_gpt4o_user_text,
openai_gpt4_user_text,
azure_openai_gpt4o_user_text,
azure_openai_gpt4_user_text,
claude_3_opus_user_text,
claude_3_sonnet_user_text,
claude_3_haiku_user_text,
command_r_checkbox,
command_r_plus_checkbox,
openai_gpt4o_checkbox,
openai_gpt4_checkbox,
azure_openai_gpt4o_checkbox,
azure_openai_gpt4_checkbox,
claude_3_opus_checkbox,
claude_3_sonnet_checkbox,
claude_3_haiku_checkbox
):
command_r_response += r
command_r_plus_response += r_plus
openai_gpt4o_response += gpt4o
openai_gpt4_response += gpt4
azure_openai_gpt4o_response += azure_gpt4o
azure_openai_gpt4_response += azure_gpt4
claude_3_opus_response += opus
claude_3_sonnet_response += sonnet
claude_3_haiku_response += haiku
yield (
command_r_response,
command_r_plus_response,
openai_gpt4o_response,
openai_gpt4_response,
azure_openai_gpt4o_response,
azure_openai_gpt4_response,
claude_3_opus_response,
claude_3_sonnet_response,
claude_3_haiku_response
)
def reset_eval_by_human_result():
return (
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),
gr.Radio(value="good"),
gr.Textbox(value=""),