Spaces:
Runtime error
Runtime error
JohnSmith9982
commited on
Commit
•
1f45019
1
Parent(s):
158e377
Upload 85 files
Browse files- ChuanhuChatbot.py +8 -0
- README.md +1 -1
- assets/custom.css +80 -72
- assets/custom.js +4 -4
- modules/__pycache__/config.cpython-311.pyc +0 -0
- modules/__pycache__/config.cpython-39.pyc +0 -0
- modules/__pycache__/index_func.cpython-311.pyc +0 -0
- modules/__pycache__/index_func.cpython-39.pyc +0 -0
- modules/__pycache__/llama_func.cpython-39.pyc +0 -0
- modules/__pycache__/overwrites.cpython-311.pyc +0 -0
- modules/__pycache__/overwrites.cpython-39.pyc +0 -0
- modules/__pycache__/pdf_func.cpython-311.pyc +0 -0
- modules/__pycache__/pdf_func.cpython-39.pyc +0 -0
- modules/__pycache__/presets.cpython-311.pyc +0 -0
- modules/__pycache__/presets.cpython-39.pyc +0 -0
- modules/__pycache__/shared.cpython-311.pyc +0 -0
- modules/__pycache__/shared.cpython-39.pyc +0 -0
- modules/__pycache__/utils.cpython-311.pyc +0 -0
- modules/__pycache__/utils.cpython-39.pyc +0 -0
- modules/config.py +6 -4
- modules/index_func.py +3 -3
- modules/models/ChuanhuAgent.py +30 -4
- modules/models/__pycache__/ChuanhuAgent.cpython-311.pyc +0 -0
- modules/models/__pycache__/ChuanhuAgent.cpython-39.pyc +0 -0
- modules/models/__pycache__/base_model.cpython-311.pyc +0 -0
- modules/models/__pycache__/base_model.cpython-39.pyc +0 -0
- modules/models/__pycache__/minimax.cpython-39.pyc +0 -0
- modules/models/__pycache__/models.cpython-311.pyc +0 -0
- modules/models/__pycache__/models.cpython-39.pyc +0 -0
- modules/models/base_model.py +54 -13
- modules/models/minimax.py +161 -0
- modules/models/models.py +5 -4
- modules/presets.py +4 -3
- modules/shared.py +14 -8
- modules/utils.py +3 -0
- requirements.txt +4 -5
ChuanhuChatbot.py
CHANGED
@@ -97,6 +97,7 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
|
|
97 |
)
|
98 |
index_files = gr.Files(label=i18n("上传"), type="file")
|
99 |
two_column = gr.Checkbox(label=i18n("双栏pdf"), value=advance_docs["pdf"].get("two_column", False))
|
|
|
100 |
# TODO: 公式ocr
|
101 |
# formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False))
|
102 |
|
@@ -333,6 +334,7 @@ with gr.Blocks(css=customCSS, theme=small_and_beautiful_theme) as demo:
|
|
333 |
submitBtn.click(**get_usage_args)
|
334 |
|
335 |
index_files.change(handle_file_upload, [current_model, index_files, chatbot, language_select_dropdown], [index_files, chatbot, status_display])
|
|
|
336 |
|
337 |
emptyBtn.click(
|
338 |
reset,
|
@@ -466,7 +468,13 @@ demo.title = i18n("川虎Chat 🚀")
|
|
466 |
if __name__ == "__main__":
|
467 |
reload_javascript()
|
468 |
demo.queue(concurrency_count=CONCURRENT_COUNT).launch(
|
|
|
|
|
|
|
|
|
|
|
469 |
favicon_path="./assets/favicon.ico",
|
|
|
470 |
)
|
471 |
# demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口
|
472 |
# demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码
|
|
|
97 |
)
|
98 |
index_files = gr.Files(label=i18n("上传"), type="file")
|
99 |
two_column = gr.Checkbox(label=i18n("双栏pdf"), value=advance_docs["pdf"].get("two_column", False))
|
100 |
+
summarize_btn = gr.Button(i18n("总结"))
|
101 |
# TODO: 公式ocr
|
102 |
# formula_ocr = gr.Checkbox(label=i18n("识别公式"), value=advance_docs["pdf"].get("formula_ocr", False))
|
103 |
|
|
|
334 |
submitBtn.click(**get_usage_args)
|
335 |
|
336 |
index_files.change(handle_file_upload, [current_model, index_files, chatbot, language_select_dropdown], [index_files, chatbot, status_display])
|
337 |
+
summarize_btn.click(handle_summarize_index, [current_model, index_files, chatbot, language_select_dropdown], [chatbot, status_display])
|
338 |
|
339 |
emptyBtn.click(
|
340 |
reset,
|
|
|
468 |
if __name__ == "__main__":
|
469 |
reload_javascript()
|
470 |
demo.queue(concurrency_count=CONCURRENT_COUNT).launch(
|
471 |
+
blocked_paths=["config.json"],
|
472 |
+
server_name=server_name,
|
473 |
+
server_port=server_port,
|
474 |
+
share=share,
|
475 |
+
auth=auth_list if authflag else None,
|
476 |
favicon_path="./assets/favicon.ico",
|
477 |
+
inbrowser=not dockerflag, # 禁止在docker下开启inbrowser
|
478 |
)
|
479 |
# demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860, share=False) # 可自定义端口
|
480 |
# demo.queue(concurrency_count=CONCURRENT_COUNT).launch(server_name="0.0.0.0", server_port=7860,auth=("在这里填写用户名", "在这里填写密码")) # 可设置用户名与密码
|
README.md
CHANGED
@@ -4,7 +4,7 @@ emoji: 🐯
|
|
4 |
colorFrom: green
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
-
sdk_version: 3.
|
8 |
app_file: ChuanhuChatbot.py
|
9 |
pinned: false
|
10 |
license: gpl-3.0
|
|
|
4 |
colorFrom: green
|
5 |
colorTo: red
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.30.0
|
8 |
app_file: ChuanhuChatbot.py
|
9 |
pinned: false
|
10 |
license: gpl-3.0
|
assets/custom.css
CHANGED
@@ -405,7 +405,7 @@ thead th {
|
|
405 |
padding: .5em .2em;
|
406 |
}
|
407 |
/* 行内代码 */
|
408 |
-
code {
|
409 |
display: inline;
|
410 |
white-space: break-spaces;
|
411 |
border-radius: 6px;
|
@@ -414,13 +414,13 @@ code {
|
|
414 |
background-color: rgba(175,184,193,0.2);
|
415 |
}
|
416 |
/* 代码块 */
|
417 |
-
pre code {
|
418 |
display: block;
|
419 |
overflow: auto;
|
420 |
white-space: pre;
|
421 |
background-color: hsla(0, 0%, 0%, 80%)!important;
|
422 |
border-radius: 10px;
|
423 |
-
padding: 1.
|
424 |
margin: 0.6em 2em 1em 0.2em;
|
425 |
color: #FFF;
|
426 |
box-shadow: 6px 6px 16px hsla(0, 0%, 0%, 0.2);
|
@@ -428,73 +428,81 @@ pre code {
|
|
428 |
.message pre {
|
429 |
padding: 0 !important;
|
430 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
431 |
/* 代码高亮样式 */
|
432 |
-
.highlight .hll { background-color: #49483e }
|
433 |
-
.highlight .c { color: #75715e } /* Comment */
|
434 |
-
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
|
435 |
-
.highlight .k { color: #66d9ef
|
436 |
-
.highlight .l { color: #ae81ff
|
437 |
-
.highlight .n { color: #f8f8f2
|
438 |
-
.highlight .o { color: #f92672
|
439 |
-
.highlight .p { color: #f8f8f2
|
440 |
-
.highlight .ch { color: #75715e
|
441 |
-
.highlight .cm { color: #75715e
|
442 |
-
.highlight .cp { color: #75715e
|
443 |
-
.highlight .cpf { color: #75715e
|
444 |
-
.highlight .c1 { color: #75715e
|
445 |
-
.highlight .cs { color: #75715e
|
446 |
-
.highlight .gd { color: #f92672
|
447 |
-
.highlight .ge { font-style: italic
|
448 |
-
.highlight .gi { color: #a6e22e
|
449 |
-
.highlight .gs { font-weight: bold
|
450 |
-
.highlight .gu { color: #75715e
|
451 |
-
.highlight .kc { color: #66d9ef
|
452 |
-
.highlight .kd { color: #66d9ef
|
453 |
-
.highlight .kn { color: #f92672
|
454 |
-
.highlight .kp { color: #66d9ef
|
455 |
-
.highlight .kr { color: #66d9ef
|
456 |
-
.highlight .kt { color: #66d9ef
|
457 |
-
.highlight .ld { color: #e6db74
|
458 |
-
.highlight .m { color: #ae81ff
|
459 |
-
.highlight .s { color: #e6db74
|
460 |
-
.highlight .na { color: #a6e22e
|
461 |
-
.highlight .nb { color: #f8f8f2
|
462 |
-
.highlight .nc { color: #a6e22e
|
463 |
-
.highlight .no { color: #66d9ef
|
464 |
-
.highlight .nd { color: #a6e22e
|
465 |
-
.highlight .ni { color: #f8f8f2
|
466 |
-
.highlight .ne { color: #a6e22e
|
467 |
-
.highlight .nf { color: #a6e22e
|
468 |
-
.highlight .nl { color: #f8f8f2
|
469 |
-
.highlight .nn { color: #f8f8f2
|
470 |
-
.highlight .nx { color: #a6e22e
|
471 |
-
.highlight .py { color: #f8f8f2
|
472 |
-
.highlight .nt { color: #f92672
|
473 |
-
.highlight .nv { color: #f8f8f2
|
474 |
-
.highlight .ow { color: #f92672
|
475 |
-
.highlight .w { color: #f8f8f2
|
476 |
-
.highlight .mb { color: #ae81ff
|
477 |
-
.highlight .mf { color: #ae81ff
|
478 |
-
.highlight .mh { color: #ae81ff
|
479 |
-
.highlight .mi { color: #ae81ff
|
480 |
-
.highlight .mo { color: #ae81ff
|
481 |
-
.highlight .sa { color: #e6db74
|
482 |
-
.highlight .sb { color: #e6db74
|
483 |
-
.highlight .sc { color: #e6db74
|
484 |
-
.highlight .dl { color: #e6db74
|
485 |
-
.highlight .sd { color: #e6db74
|
486 |
-
.highlight .s2 { color: #e6db74
|
487 |
-
.highlight .se { color: #ae81ff
|
488 |
-
.highlight .sh { color: #e6db74
|
489 |
-
.highlight .si { color: #e6db74
|
490 |
-
.highlight .sx { color: #e6db74
|
491 |
-
.highlight .sr { color: #e6db74
|
492 |
-
.highlight .s1 { color: #e6db74
|
493 |
-
.highlight .ss { color: #e6db74
|
494 |
-
.highlight .bp { color: #f8f8f2
|
495 |
-
.highlight .fm { color: #a6e22e
|
496 |
-
.highlight .vc { color: #f8f8f2
|
497 |
-
.highlight .vg { color: #f8f8f2
|
498 |
-
.highlight .vi { color: #f8f8f2
|
499 |
-
.highlight .vm { color: #f8f8f2
|
500 |
-
.highlight .il { color: #ae81ff
|
|
|
405 |
padding: .5em .2em;
|
406 |
}
|
407 |
/* 行内代码 */
|
408 |
+
.message :not(pre) code {
|
409 |
display: inline;
|
410 |
white-space: break-spaces;
|
411 |
border-radius: 6px;
|
|
|
414 |
background-color: rgba(175,184,193,0.2);
|
415 |
}
|
416 |
/* 代码块 */
|
417 |
+
.message pre code {
|
418 |
display: block;
|
419 |
overflow: auto;
|
420 |
white-space: pre;
|
421 |
background-color: hsla(0, 0%, 0%, 80%)!important;
|
422 |
border-radius: 10px;
|
423 |
+
padding: 1.2em 1em 0em .5em;
|
424 |
margin: 0.6em 2em 1em 0.2em;
|
425 |
color: #FFF;
|
426 |
box-shadow: 6px 6px 16px hsla(0, 0%, 0%, 0.2);
|
|
|
428 |
.message pre {
|
429 |
padding: 0 !important;
|
430 |
}
|
431 |
+
.message pre code div.highlight {
|
432 |
+
background-color: unset !important;
|
433 |
+
}
|
434 |
+
|
435 |
+
button.copy-button {
|
436 |
+
display: none;
|
437 |
+
}
|
438 |
+
|
439 |
/* 代码高亮样式 */
|
440 |
+
.highlight .hll { background-color: #49483e !important }
|
441 |
+
.highlight .c { color: #75715e !important } /* Comment */
|
442 |
+
.highlight .err { color: #960050 !important; background-color: #1e0010 } /* Error */
|
443 |
+
.highlight .k { color: #66d9ef !important} /* Keyword */
|
444 |
+
.highlight .l { color: #ae81ff !important} /* Literal */
|
445 |
+
.highlight .n { color: #f8f8f2 !important} /* Name */
|
446 |
+
.highlight .o { color: #f92672 !important} /* Operator */
|
447 |
+
.highlight .p { color: #f8f8f2 !important} /* Punctuation */
|
448 |
+
.highlight .ch { color: #75715e !important} /* Comment.Hashbang */
|
449 |
+
.highlight .cm { color: #75715e !important} /* Comment.Multiline */
|
450 |
+
.highlight .cp { color: #75715e !important} /* Comment.Preproc */
|
451 |
+
.highlight .cpf { color: #75715e !important} /* Comment.PreprocFile */
|
452 |
+
.highlight .c1 { color: #75715e !important} /* Comment.Single */
|
453 |
+
.highlight .cs { color: #75715e !important} /* Comment.Special */
|
454 |
+
.highlight .gd { color: #f92672 !important} /* Generic.Deleted */
|
455 |
+
.highlight .ge { font-style: italic !important} /* Generic.Emph */
|
456 |
+
.highlight .gi { color: #a6e22e !important} /* Generic.Inserted */
|
457 |
+
.highlight .gs { font-weight: bold !important} /* Generic.Strong */
|
458 |
+
.highlight .gu { color: #75715e !important} /* Generic.Subheading */
|
459 |
+
.highlight .kc { color: #66d9ef !important} /* Keyword.Constant */
|
460 |
+
.highlight .kd { color: #66d9ef !important} /* Keyword.Declaration */
|
461 |
+
.highlight .kn { color: #f92672 !important} /* Keyword.Namespace */
|
462 |
+
.highlight .kp { color: #66d9ef !important} /* Keyword.Pseudo */
|
463 |
+
.highlight .kr { color: #66d9ef !important} /* Keyword.Reserved */
|
464 |
+
.highlight .kt { color: #66d9ef !important} /* Keyword.Type */
|
465 |
+
.highlight .ld { color: #e6db74 !important} /* Literal.Date */
|
466 |
+
.highlight .m { color: #ae81ff !important} /* Literal.Number */
|
467 |
+
.highlight .s { color: #e6db74 !important} /* Literal.String */
|
468 |
+
.highlight .na { color: #a6e22e !important} /* Name.Attribute */
|
469 |
+
.highlight .nb { color: #f8f8f2 !important} /* Name.Builtin */
|
470 |
+
.highlight .nc { color: #a6e22e !important} /* Name.Class */
|
471 |
+
.highlight .no { color: #66d9ef !important} /* Name.Constant */
|
472 |
+
.highlight .nd { color: #a6e22e !important} /* Name.Decorator */
|
473 |
+
.highlight .ni { color: #f8f8f2 !important} /* Name.Entity */
|
474 |
+
.highlight .ne { color: #a6e22e !important} /* Name.Exception */
|
475 |
+
.highlight .nf { color: #a6e22e !important} /* Name.Function */
|
476 |
+
.highlight .nl { color: #f8f8f2 !important} /* Name.Label */
|
477 |
+
.highlight .nn { color: #f8f8f2 !important} /* Name.Namespace */
|
478 |
+
.highlight .nx { color: #a6e22e !important} /* Name.Other */
|
479 |
+
.highlight .py { color: #f8f8f2 !important} /* Name.Property */
|
480 |
+
.highlight .nt { color: #f92672 !important} /* Name.Tag */
|
481 |
+
.highlight .nv { color: #f8f8f2 !important} /* Name.Variable */
|
482 |
+
.highlight .ow { color: #f92672 !important} /* Operator.Word */
|
483 |
+
.highlight .w { color: #f8f8f2 !important} /* Text.Whitespace */
|
484 |
+
.highlight .mb { color: #ae81ff !important} /* Literal.Number.Bin */
|
485 |
+
.highlight .mf { color: #ae81ff !important} /* Literal.Number.Float */
|
486 |
+
.highlight .mh { color: #ae81ff !important} /* Literal.Number.Hex */
|
487 |
+
.highlight .mi { color: #ae81ff !important} /* Literal.Number.Integer */
|
488 |
+
.highlight .mo { color: #ae81ff !important} /* Literal.Number.Oct */
|
489 |
+
.highlight .sa { color: #e6db74 !important} /* Literal.String.Affix */
|
490 |
+
.highlight .sb { color: #e6db74 !important} /* Literal.String.Backtick */
|
491 |
+
.highlight .sc { color: #e6db74 !important} /* Literal.String.Char */
|
492 |
+
.highlight .dl { color: #e6db74 !important} /* Literal.String.Delimiter */
|
493 |
+
.highlight .sd { color: #e6db74 !important} /* Literal.String.Doc */
|
494 |
+
.highlight .s2 { color: #e6db74 !important} /* Literal.String.Double */
|
495 |
+
.highlight .se { color: #ae81ff !important} /* Literal.String.Escape */
|
496 |
+
.highlight .sh { color: #e6db74 !important} /* Literal.String.Heredoc */
|
497 |
+
.highlight .si { color: #e6db74 !important} /* Literal.String.Interpol */
|
498 |
+
.highlight .sx { color: #e6db74 !important} /* Literal.String.Other */
|
499 |
+
.highlight .sr { color: #e6db74 !important} /* Literal.String.Regex */
|
500 |
+
.highlight .s1 { color: #e6db74 !important} /* Literal.String.Single */
|
501 |
+
.highlight .ss { color: #e6db74 !important} /* Literal.String.Symbol */
|
502 |
+
.highlight .bp { color: #f8f8f2 !important} /* Name.Builtin.Pseudo */
|
503 |
+
.highlight .fm { color: #a6e22e !important} /* Name.Function.Magic */
|
504 |
+
.highlight .vc { color: #f8f8f2 !important} /* Name.Variable.Class */
|
505 |
+
.highlight .vg { color: #f8f8f2 !important} /* Name.Variable.Global */
|
506 |
+
.highlight .vi { color: #f8f8f2 !important} /* Name.Variable.Instance */
|
507 |
+
.highlight .vm { color: #f8f8f2 !important} /* Name.Variable.Magic */
|
508 |
+
.highlight .il { color: #ae81ff !important} /* Literal.Number.Integer.Long */
|
assets/custom.js
CHANGED
@@ -245,11 +245,11 @@ function showOrHideUserInfo() {
|
|
245 |
|
246 |
function toggleDarkMode(isEnabled) {
|
247 |
if (isEnabled) {
|
248 |
-
|
249 |
-
document.body.style.setProperty("background-color", "var(--neutral-950)", "important");
|
250 |
} else {
|
251 |
-
|
252 |
-
document.body.style.backgroundColor = "";
|
253 |
}
|
254 |
}
|
255 |
function adjustDarkMode() {
|
|
|
245 |
|
246 |
function toggleDarkMode(isEnabled) {
|
247 |
if (isEnabled) {
|
248 |
+
document.body.classList.add("dark");
|
249 |
+
// document.body.style.setProperty("background-color", "var(--neutral-950)", "important");
|
250 |
} else {
|
251 |
+
document.body.classList.remove("dark");
|
252 |
+
// document.body.style.backgroundColor = "";
|
253 |
}
|
254 |
}
|
255 |
function adjustDarkMode() {
|
modules/__pycache__/config.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/config.cpython-311.pyc and b/modules/__pycache__/config.cpython-311.pyc differ
|
|
modules/__pycache__/config.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/config.cpython-39.pyc and b/modules/__pycache__/config.cpython-39.pyc differ
|
|
modules/__pycache__/index_func.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/index_func.cpython-311.pyc and b/modules/__pycache__/index_func.cpython-311.pyc differ
|
|
modules/__pycache__/index_func.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/index_func.cpython-39.pyc and b/modules/__pycache__/index_func.cpython-39.pyc differ
|
|
modules/__pycache__/llama_func.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/llama_func.cpython-39.pyc and b/modules/__pycache__/llama_func.cpython-39.pyc differ
|
|
modules/__pycache__/overwrites.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/overwrites.cpython-311.pyc and b/modules/__pycache__/overwrites.cpython-311.pyc differ
|
|
modules/__pycache__/overwrites.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/overwrites.cpython-39.pyc and b/modules/__pycache__/overwrites.cpython-39.pyc differ
|
|
modules/__pycache__/pdf_func.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/pdf_func.cpython-311.pyc and b/modules/__pycache__/pdf_func.cpython-311.pyc differ
|
|
modules/__pycache__/pdf_func.cpython-39.pyc
ADDED
Binary file (6.13 kB). View file
|
|
modules/__pycache__/presets.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/presets.cpython-311.pyc and b/modules/__pycache__/presets.cpython-311.pyc differ
|
|
modules/__pycache__/presets.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/presets.cpython-39.pyc and b/modules/__pycache__/presets.cpython-39.pyc differ
|
|
modules/__pycache__/shared.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/shared.cpython-311.pyc and b/modules/__pycache__/shared.cpython-311.pyc differ
|
|
modules/__pycache__/shared.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/shared.cpython-39.pyc and b/modules/__pycache__/shared.cpython-39.pyc differ
|
|
modules/__pycache__/utils.cpython-311.pyc
CHANGED
Binary files a/modules/__pycache__/utils.cpython-311.pyc and b/modules/__pycache__/utils.cpython-311.pyc differ
|
|
modules/__pycache__/utils.cpython-39.pyc
CHANGED
Binary files a/modules/__pycache__/utils.cpython-39.pyc and b/modules/__pycache__/utils.cpython-39.pyc differ
|
|
modules/config.py
CHANGED
@@ -77,8 +77,10 @@ my_api_key = os.environ.get("OPENAI_API_KEY", my_api_key)
|
|
77 |
xmchat_api_key = config.get("xmchat_api_key", "")
|
78 |
os.environ["XMCHAT_API_KEY"] = xmchat_api_key
|
79 |
|
80 |
-
|
81 |
-
os.environ["
|
|
|
|
|
82 |
|
83 |
render_latex = config.get("render_latex", True)
|
84 |
|
@@ -102,8 +104,8 @@ auth_list = config.get("users", []) # 实际上是使用者的列表
|
|
102 |
authflag = len(auth_list) > 0 # 是否开启认证的状态值,改为判断auth_list长度
|
103 |
|
104 |
# 处理自定义的api_host,优先读环境变量的配置,如果存在则自动装配
|
105 |
-
api_host = os.environ.get("
|
106 |
-
if api_host:
|
107 |
shared.state.set_api_host(api_host)
|
108 |
|
109 |
default_chuanhu_assistant_model = config.get("default_chuanhu_assistant_model", "gpt-3.5-turbo")
|
|
|
77 |
xmchat_api_key = config.get("xmchat_api_key", "")
|
78 |
os.environ["XMCHAT_API_KEY"] = xmchat_api_key
|
79 |
|
80 |
+
minimax_api_key = config.get("minimax_api_key", "")
|
81 |
+
os.environ["MINIMAX_API_KEY"] = minimax_api_key
|
82 |
+
minimax_group_id = config.get("minimax_group_id", "")
|
83 |
+
os.environ["MINIMAX_GROUP_ID"] = minimax_group_id
|
84 |
|
85 |
render_latex = config.get("render_latex", True)
|
86 |
|
|
|
104 |
authflag = len(auth_list) > 0 # 是否开启认证的状态值,改为判断auth_list长度
|
105 |
|
106 |
# 处理自定义的api_host,优先读环境变量的配置,如果存在则自动装配
|
107 |
+
api_host = os.environ.get("OPENAI_API_BASE", config.get("openai_api_base", None))
|
108 |
+
if api_host is not None:
|
109 |
shared.state.set_api_host(api_host)
|
110 |
|
111 |
default_chuanhu_assistant_model = config.get("default_chuanhu_assistant_model", "gpt-3.5-turbo")
|
modules/index_func.py
CHANGED
@@ -83,7 +83,7 @@ def get_documents(file_src):
|
|
83 |
logging.error(f"Error loading file: {filename}")
|
84 |
traceback.print_exc()
|
85 |
|
86 |
-
texts = text_splitter.split_documents(texts)
|
87 |
documents.extend(texts)
|
88 |
logging.debug("Documents loaded.")
|
89 |
return documents
|
@@ -118,7 +118,7 @@ def construct_index(
|
|
118 |
embeddings = HuggingFaceEmbeddings(model_name = "sentence-transformers/distiluse-base-multilingual-cased-v2")
|
119 |
else:
|
120 |
from langchain.embeddings import OpenAIEmbeddings
|
121 |
-
embeddings = OpenAIEmbeddings()
|
122 |
if os.path.exists(index_path):
|
123 |
logging.info("找到了缓存的索引文件,加载中……")
|
124 |
return FAISS.load_local(index_path, embeddings)
|
@@ -136,6 +136,6 @@ def construct_index(
|
|
136 |
|
137 |
except Exception as e:
|
138 |
import traceback
|
139 |
-
logging.error("
|
140 |
traceback.print_exc()
|
141 |
return None
|
|
|
83 |
logging.error(f"Error loading file: {filename}")
|
84 |
traceback.print_exc()
|
85 |
|
86 |
+
texts = text_splitter.split_documents([texts])
|
87 |
documents.extend(texts)
|
88 |
logging.debug("Documents loaded.")
|
89 |
return documents
|
|
|
118 |
embeddings = HuggingFaceEmbeddings(model_name = "sentence-transformers/distiluse-base-multilingual-cased-v2")
|
119 |
else:
|
120 |
from langchain.embeddings import OpenAIEmbeddings
|
121 |
+
embeddings = OpenAIEmbeddings(openai_api_base=os.environ.get("OPENAI_API_BASE", None), openai_api_key=os.environ.get("OPENAI_EMBEDDING_API_KEY", api_key))
|
122 |
if os.path.exists(index_path):
|
123 |
logging.info("找到了缓存的索引文件,加载中……")
|
124 |
return FAISS.load_local(index_path, embeddings)
|
|
|
136 |
|
137 |
except Exception as e:
|
138 |
import traceback
|
139 |
+
logging.error("索引构建失败!%s", e)
|
140 |
traceback.print_exc()
|
141 |
return None
|
modules/models/ChuanhuAgent.py
CHANGED
@@ -14,6 +14,7 @@ from langchain.tools import BaseTool, StructuredTool, Tool, tool
|
|
14 |
from langchain.callbacks.stdout import StdOutCallbackHandler
|
15 |
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
16 |
from langchain.callbacks.manager import BaseCallbackManager
|
|
|
17 |
|
18 |
from typing import Any, Dict, List, Optional, Union
|
19 |
|
@@ -38,6 +39,9 @@ import os
|
|
38 |
import gradio as gr
|
39 |
import logging
|
40 |
|
|
|
|
|
|
|
41 |
class WebBrowsingInput(BaseModel):
|
42 |
url: str = Field(description="URL of a webpage")
|
43 |
|
@@ -51,8 +55,8 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
51 |
super().__init__(model_name=model_name, user=user_name)
|
52 |
self.text_splitter = TokenTextSplitter(chunk_size=500, chunk_overlap=30)
|
53 |
self.api_key = openai_api_key
|
54 |
-
self.llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=0, model_name=default_chuanhu_assistant_model)
|
55 |
-
self.cheap_llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=0, model_name="gpt-3.5-turbo")
|
56 |
PROMPT = PromptTemplate(template=SUMMARIZE_PROMPT, input_variables=["text"])
|
57 |
self.summarize_chain = load_summarize_chain(self.cheap_llm, chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)
|
58 |
self.index_summary = None
|
@@ -61,6 +65,14 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
61 |
self.tools = load_tools(["google-search-results-json", "llm-math", "arxiv", "wikipedia", "wolfram-alpha"], llm=self.llm)
|
62 |
else:
|
63 |
self.tools = load_tools(["ddg-search", "llm-math", "arxiv", "wikipedia"], llm=self.llm)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
self.tools.append(
|
66 |
Tool.from_function(
|
@@ -80,6 +92,10 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
80 |
)
|
81 |
)
|
82 |
|
|
|
|
|
|
|
|
|
83 |
def handle_file_upload(self, files, chatbot, language):
|
84 |
"""if the model accepts multi modal input, implement this function"""
|
85 |
status = gr.Markdown.update()
|
@@ -102,6 +118,7 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
102 |
summary = chain({"input_documents": list(index.docstore.__dict__["_dict"].values())}, return_only_outputs=True)["output_text"]
|
103 |
logging.info(f"Summary: {summary}")
|
104 |
self.index_summary = summary
|
|
|
105 |
logging.info(cb)
|
106 |
return gr.Files.update(), chatbot, status
|
107 |
|
@@ -129,6 +146,8 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
129 |
|
130 |
def summary_url(self, url):
|
131 |
text = self.fetch_url_content(url)
|
|
|
|
|
132 |
text_summary = self.summary(text)
|
133 |
url_content = "webpage content summary:\n" + text_summary
|
134 |
|
@@ -136,10 +155,12 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
136 |
|
137 |
def ask_url(self, url, question):
|
138 |
text = self.fetch_url_content(url)
|
|
|
|
|
139 |
texts = Document(page_content=text)
|
140 |
texts = self.text_splitter.split_documents([texts])
|
141 |
# use embedding
|
142 |
-
embeddings = OpenAIEmbeddings(openai_api_key=self.api_key)
|
143 |
|
144 |
# create vectorstore
|
145 |
db = FAISS.from_documents(texts, embeddings)
|
@@ -170,7 +191,12 @@ class ChuanhuAgent_Client(BaseLLMModel):
|
|
170 |
)
|
171 |
)
|
172 |
agent = initialize_agent(self.tools, self.llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, callback_manager=manager)
|
173 |
-
|
|
|
|
|
|
|
|
|
|
|
174 |
it.callback(reply)
|
175 |
it.finish()
|
176 |
t = Thread(target=thread_func)
|
|
|
14 |
from langchain.callbacks.stdout import StdOutCallbackHandler
|
15 |
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
|
16 |
from langchain.callbacks.manager import BaseCallbackManager
|
17 |
+
from googlesearch import search
|
18 |
|
19 |
from typing import Any, Dict, List, Optional, Union
|
20 |
|
|
|
39 |
import gradio as gr
|
40 |
import logging
|
41 |
|
42 |
+
class GoogleSearchInput(BaseModel):
|
43 |
+
keywords: str = Field(description="keywords to search")
|
44 |
+
|
45 |
class WebBrowsingInput(BaseModel):
|
46 |
url: str = Field(description="URL of a webpage")
|
47 |
|
|
|
55 |
super().__init__(model_name=model_name, user=user_name)
|
56 |
self.text_splitter = TokenTextSplitter(chunk_size=500, chunk_overlap=30)
|
57 |
self.api_key = openai_api_key
|
58 |
+
self.llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=0, model_name=default_chuanhu_assistant_model, openai_api_base=os.environ.get("OPENAI_API_BASE", None))
|
59 |
+
self.cheap_llm = ChatOpenAI(openai_api_key=openai_api_key, temperature=0, model_name="gpt-3.5-turbo", openai_api_base=os.environ.get("OPENAI_API_BASE", None))
|
60 |
PROMPT = PromptTemplate(template=SUMMARIZE_PROMPT, input_variables=["text"])
|
61 |
self.summarize_chain = load_summarize_chain(self.cheap_llm, chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)
|
62 |
self.index_summary = None
|
|
|
65 |
self.tools = load_tools(["google-search-results-json", "llm-math", "arxiv", "wikipedia", "wolfram-alpha"], llm=self.llm)
|
66 |
else:
|
67 |
self.tools = load_tools(["ddg-search", "llm-math", "arxiv", "wikipedia"], llm=self.llm)
|
68 |
+
self.tools.append(
|
69 |
+
Tool.from_function(
|
70 |
+
func=self.google_search_simple,
|
71 |
+
name="Google Search JSON",
|
72 |
+
description="useful when you need to search the web.",
|
73 |
+
args_schema=GoogleSearchInput
|
74 |
+
)
|
75 |
+
)
|
76 |
|
77 |
self.tools.append(
|
78 |
Tool.from_function(
|
|
|
92 |
)
|
93 |
)
|
94 |
|
95 |
+
def google_search_simple(self, query):
|
96 |
+
results = [{"title": i.title, "link": i.url, "snippet": i.description} for i in search(query, advanced=True)]
|
97 |
+
return str(results)
|
98 |
+
|
99 |
def handle_file_upload(self, files, chatbot, language):
|
100 |
"""if the model accepts multi modal input, implement this function"""
|
101 |
status = gr.Markdown.update()
|
|
|
118 |
summary = chain({"input_documents": list(index.docstore.__dict__["_dict"].values())}, return_only_outputs=True)["output_text"]
|
119 |
logging.info(f"Summary: {summary}")
|
120 |
self.index_summary = summary
|
121 |
+
chatbot.append((f"Uploaded {len(files)} files", summary))
|
122 |
logging.info(cb)
|
123 |
return gr.Files.update(), chatbot, status
|
124 |
|
|
|
146 |
|
147 |
def summary_url(self, url):
|
148 |
text = self.fetch_url_content(url)
|
149 |
+
if text == "":
|
150 |
+
return "URL unavailable."
|
151 |
text_summary = self.summary(text)
|
152 |
url_content = "webpage content summary:\n" + text_summary
|
153 |
|
|
|
155 |
|
156 |
def ask_url(self, url, question):
|
157 |
text = self.fetch_url_content(url)
|
158 |
+
if text == "":
|
159 |
+
return "URL unavailable."
|
160 |
texts = Document(page_content=text)
|
161 |
texts = self.text_splitter.split_documents([texts])
|
162 |
# use embedding
|
163 |
+
embeddings = OpenAIEmbeddings(openai_api_key=self.api_key, openai_api_base=os.environ.get("OPENAI_API_BASE", None))
|
164 |
|
165 |
# create vectorstore
|
166 |
db = FAISS.from_documents(texts, embeddings)
|
|
|
191 |
)
|
192 |
)
|
193 |
agent = initialize_agent(self.tools, self.llm, agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True, callback_manager=manager)
|
194 |
+
try:
|
195 |
+
reply = agent.run(input=f"{question} Reply in 简体中文")
|
196 |
+
except Exception as e:
|
197 |
+
import traceback
|
198 |
+
traceback.print_exc()
|
199 |
+
reply = str(e)
|
200 |
it.callback(reply)
|
201 |
it.finish()
|
202 |
t = Thread(target=thread_func)
|
modules/models/__pycache__/ChuanhuAgent.cpython-311.pyc
CHANGED
Binary files a/modules/models/__pycache__/ChuanhuAgent.cpython-311.pyc and b/modules/models/__pycache__/ChuanhuAgent.cpython-311.pyc differ
|
|
modules/models/__pycache__/ChuanhuAgent.cpython-39.pyc
CHANGED
Binary files a/modules/models/__pycache__/ChuanhuAgent.cpython-39.pyc and b/modules/models/__pycache__/ChuanhuAgent.cpython-39.pyc differ
|
|
modules/models/__pycache__/base_model.cpython-311.pyc
CHANGED
Binary files a/modules/models/__pycache__/base_model.cpython-311.pyc and b/modules/models/__pycache__/base_model.cpython-311.pyc differ
|
|
modules/models/__pycache__/base_model.cpython-39.pyc
CHANGED
Binary files a/modules/models/__pycache__/base_model.cpython-39.pyc and b/modules/models/__pycache__/base_model.cpython-39.pyc differ
|
|
modules/models/__pycache__/minimax.cpython-39.pyc
ADDED
Binary file (4.35 kB). View file
|
|
modules/models/__pycache__/models.cpython-311.pyc
CHANGED
Binary files a/modules/models/__pycache__/models.cpython-311.pyc and b/modules/models/__pycache__/models.cpython-311.pyc differ
|
|
modules/models/__pycache__/models.cpython-39.pyc
CHANGED
Binary files a/modules/models/__pycache__/models.cpython-39.pyc and b/modules/models/__pycache__/models.cpython-39.pyc differ
|
|
modules/models/base_model.py
CHANGED
@@ -13,7 +13,7 @@ import pathlib
|
|
13 |
|
14 |
from tqdm import tqdm
|
15 |
import colorama
|
16 |
-
from
|
17 |
import asyncio
|
18 |
import aiohttp
|
19 |
from enum import Enum
|
@@ -62,6 +62,19 @@ class CallbackToIterator:
|
|
62 |
self.finished = True
|
63 |
self.cond.notify() # Wake up the generator if it's waiting.
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
class ChuanhuCallbackHandler(BaseCallbackHandler):
|
66 |
|
67 |
def __init__(self, callback) -> None:
|
@@ -71,7 +84,7 @@ class ChuanhuCallbackHandler(BaseCallbackHandler):
|
|
71 |
def on_agent_action(
|
72 |
self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
|
73 |
) -> Any:
|
74 |
-
self.callback(action.log)
|
75 |
|
76 |
def on_tool_end(
|
77 |
self,
|
@@ -82,16 +95,22 @@ class ChuanhuCallbackHandler(BaseCallbackHandler):
|
|
82 |
**kwargs: Any,
|
83 |
) -> None:
|
84 |
"""If not the final action, print out observation."""
|
|
|
|
|
|
|
|
|
|
|
85 |
if observation_prefix is not None:
|
86 |
-
|
87 |
self.callback(output)
|
88 |
if llm_prefix is not None:
|
89 |
-
|
90 |
|
91 |
def on_agent_finish(
|
92 |
self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
|
93 |
) -> None:
|
94 |
-
self.callback(f"{finish.log}\n\n")
|
|
|
95 |
|
96 |
def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
|
97 |
"""Run on new LLM token. Only available when streaming is enabled."""
|
@@ -107,8 +126,8 @@ class ModelType(Enum):
|
|
107 |
StableLM = 4
|
108 |
MOSS = 5
|
109 |
YuanAI = 6
|
110 |
-
|
111 |
-
|
112 |
|
113 |
@classmethod
|
114 |
def get_type(cls, model_name: str):
|
@@ -128,10 +147,10 @@ class ModelType(Enum):
|
|
128 |
model_type = ModelType.MOSS
|
129 |
elif "yuanai" in model_name_lower:
|
130 |
model_type = ModelType.YuanAI
|
|
|
|
|
131 |
elif "川虎助理" in model_name_lower:
|
132 |
model_type = ModelType.ChuanhuAgent
|
133 |
-
elif "palm" in model_name_lower:
|
134 |
-
model_type = ModelType.PaLM
|
135 |
else:
|
136 |
model_type = ModelType.Unknown
|
137 |
return model_type
|
@@ -225,6 +244,8 @@ class BaseLLMModel:
|
|
225 |
|
226 |
stream_iter = self.get_answer_stream_iter()
|
227 |
|
|
|
|
|
228 |
for partial_text in stream_iter:
|
229 |
chatbot[-1] = (chatbot[-1][0], partial_text + display_append)
|
230 |
self.all_token_counts[-1] += 1
|
@@ -265,6 +286,26 @@ class BaseLLMModel:
|
|
265 |
status = i18n("索引构建完成")
|
266 |
return gr.Files.update(), chatbot, status
|
267 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
268 |
def prepare_inputs(self, real_inputs, use_websearch, files, reply_language, chatbot):
|
269 |
fake_inputs = None
|
270 |
display_append = []
|
@@ -295,15 +336,15 @@ class BaseLLMModel:
|
|
295 |
)
|
296 |
elif use_websearch:
|
297 |
limited_context = True
|
298 |
-
search_results =
|
299 |
reference_results = []
|
300 |
for idx, result in enumerate(search_results):
|
301 |
logging.debug(f"搜索结果{idx + 1}:{result}")
|
302 |
-
domain_name = urllib3.util.parse_url(result
|
303 |
-
reference_results.append([result
|
304 |
display_append.append(
|
305 |
# f"{idx+1}. [{domain_name}]({result['href']})\n"
|
306 |
-
f"<li><a href=\"{result
|
307 |
)
|
308 |
reference_results = add_source_numbers(reference_results)
|
309 |
display_append = "<ol>\n\n" + "".join(display_append) + "</ol>"
|
|
|
13 |
|
14 |
from tqdm import tqdm
|
15 |
import colorama
|
16 |
+
from googlesearch import search
|
17 |
import asyncio
|
18 |
import aiohttp
|
19 |
from enum import Enum
|
|
|
62 |
self.finished = True
|
63 |
self.cond.notify() # Wake up the generator if it's waiting.
|
64 |
|
65 |
+
def get_action_description(text):
|
66 |
+
match = re.search('```(.*?)```', text, re.S)
|
67 |
+
json_text = match.group(1)
|
68 |
+
# 把json转化为python字典
|
69 |
+
json_dict = json.loads(json_text)
|
70 |
+
# 提取'action'和'action_input'的值
|
71 |
+
action_name = json_dict['action']
|
72 |
+
action_input = json_dict['action_input']
|
73 |
+
if action_name != "Final Answer":
|
74 |
+
return f'<p style="font-size: smaller; color: gray;">{action_name}: {action_input}</p>'
|
75 |
+
else:
|
76 |
+
return ""
|
77 |
+
|
78 |
class ChuanhuCallbackHandler(BaseCallbackHandler):
|
79 |
|
80 |
def __init__(self, callback) -> None:
|
|
|
84 |
def on_agent_action(
|
85 |
self, action: AgentAction, color: Optional[str] = None, **kwargs: Any
|
86 |
) -> Any:
|
87 |
+
self.callback(get_action_description(action.log))
|
88 |
|
89 |
def on_tool_end(
|
90 |
self,
|
|
|
95 |
**kwargs: Any,
|
96 |
) -> None:
|
97 |
"""If not the final action, print out observation."""
|
98 |
+
# if observation_prefix is not None:
|
99 |
+
# self.callback(f"\n\n{observation_prefix}")
|
100 |
+
# self.callback(output)
|
101 |
+
# if llm_prefix is not None:
|
102 |
+
# self.callback(f"\n\n{llm_prefix}")
|
103 |
if observation_prefix is not None:
|
104 |
+
logging.info(observation_prefix)
|
105 |
self.callback(output)
|
106 |
if llm_prefix is not None:
|
107 |
+
logging.info(llm_prefix)
|
108 |
|
109 |
def on_agent_finish(
|
110 |
self, finish: AgentFinish, color: Optional[str] = None, **kwargs: Any
|
111 |
) -> None:
|
112 |
+
# self.callback(f"{finish.log}\n\n")
|
113 |
+
logging.info(finish.log)
|
114 |
|
115 |
def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
|
116 |
"""Run on new LLM token. Only available when streaming is enabled."""
|
|
|
126 |
StableLM = 4
|
127 |
MOSS = 5
|
128 |
YuanAI = 6
|
129 |
+
Minimax = 7
|
130 |
+
ChuanhuAgent = 8
|
131 |
|
132 |
@classmethod
|
133 |
def get_type(cls, model_name: str):
|
|
|
147 |
model_type = ModelType.MOSS
|
148 |
elif "yuanai" in model_name_lower:
|
149 |
model_type = ModelType.YuanAI
|
150 |
+
elif "minimax" in model_name_lower:
|
151 |
+
model_type = ModelType.Minimax
|
152 |
elif "川虎助理" in model_name_lower:
|
153 |
model_type = ModelType.ChuanhuAgent
|
|
|
|
|
154 |
else:
|
155 |
model_type = ModelType.Unknown
|
156 |
return model_type
|
|
|
244 |
|
245 |
stream_iter = self.get_answer_stream_iter()
|
246 |
|
247 |
+
if display_append:
|
248 |
+
display_append = "<hr>" +display_append
|
249 |
for partial_text in stream_iter:
|
250 |
chatbot[-1] = (chatbot[-1][0], partial_text + display_append)
|
251 |
self.all_token_counts[-1] += 1
|
|
|
286 |
status = i18n("索引构建完成")
|
287 |
return gr.Files.update(), chatbot, status
|
288 |
|
289 |
+
def summarize_index(self, files, chatbot, language):
|
290 |
+
status = gr.Markdown.update()
|
291 |
+
if files:
|
292 |
+
index = construct_index(self.api_key, file_src=files)
|
293 |
+
status = i18n("总结完成")
|
294 |
+
logging.info(i18n("生成内容总结中……"))
|
295 |
+
os.environ["OPENAI_API_KEY"] = self.api_key
|
296 |
+
from langchain.chains.summarize import load_summarize_chain
|
297 |
+
from langchain.prompts import PromptTemplate
|
298 |
+
from langchain.chat_models import ChatOpenAI
|
299 |
+
from langchain.callbacks import StdOutCallbackHandler
|
300 |
+
prompt_template = "Write a concise summary of the following:\n\n{text}\n\nCONCISE SUMMARY IN " + language + ":"
|
301 |
+
PROMPT = PromptTemplate(template=prompt_template, input_variables=["text"])
|
302 |
+
llm = ChatOpenAI()
|
303 |
+
chain = load_summarize_chain(llm, chain_type="map_reduce", return_intermediate_steps=True, map_prompt=PROMPT, combine_prompt=PROMPT)
|
304 |
+
summary = chain({"input_documents": list(index.docstore.__dict__["_dict"].values())}, return_only_outputs=True)["output_text"]
|
305 |
+
print(i18n("总结") + f": {summary}")
|
306 |
+
chatbot.append([i18n("上传了")+str(len(files))+"个文件", summary])
|
307 |
+
return chatbot, status
|
308 |
+
|
309 |
def prepare_inputs(self, real_inputs, use_websearch, files, reply_language, chatbot):
|
310 |
fake_inputs = None
|
311 |
display_append = []
|
|
|
336 |
)
|
337 |
elif use_websearch:
|
338 |
limited_context = True
|
339 |
+
search_results = [i for i in search(real_inputs, advanced=True)]
|
340 |
reference_results = []
|
341 |
for idx, result in enumerate(search_results):
|
342 |
logging.debug(f"搜索结果{idx + 1}:{result}")
|
343 |
+
domain_name = urllib3.util.parse_url(result.url).host
|
344 |
+
reference_results.append([result.description, result.url])
|
345 |
display_append.append(
|
346 |
# f"{idx+1}. [{domain_name}]({result['href']})\n"
|
347 |
+
f"<li><a href=\"{result.url}\" target=\"_blank\">{domain_name}</a></li>\n"
|
348 |
)
|
349 |
reference_results = add_source_numbers(reference_results)
|
350 |
display_append = "<ol>\n\n" + "".join(display_append) + "</ol>"
|
modules/models/minimax.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import os
|
3 |
+
|
4 |
+
import colorama
|
5 |
+
import requests
|
6 |
+
import logging
|
7 |
+
|
8 |
+
from modules.models.base_model import BaseLLMModel
|
9 |
+
from modules.presets import STANDARD_ERROR_MSG, GENERAL_ERROR_MSG, TIMEOUT_STREAMING, TIMEOUT_ALL, i18n
|
10 |
+
|
11 |
+
group_id = os.environ.get("MINIMAX_GROUP_ID", "")
|
12 |
+
|
13 |
+
|
14 |
+
class MiniMax_Client(BaseLLMModel):
|
15 |
+
"""
|
16 |
+
MiniMax Client
|
17 |
+
接口文档见 https://api.minimax.chat/document/guides/chat
|
18 |
+
"""
|
19 |
+
|
20 |
+
def __init__(self, model_name, api_key, user_name="", system_prompt=None):
|
21 |
+
super().__init__(model_name=model_name, user=user_name)
|
22 |
+
self.url = f'https://api.minimax.chat/v1/text/chatcompletion?GroupId={group_id}'
|
23 |
+
self.history = []
|
24 |
+
self.api_key = api_key
|
25 |
+
self.system_prompt = system_prompt
|
26 |
+
self.headers = {
|
27 |
+
"Authorization": f"Bearer {api_key}",
|
28 |
+
"Content-Type": "application/json"
|
29 |
+
}
|
30 |
+
|
31 |
+
def get_answer_at_once(self):
|
32 |
+
# minimax temperature is (0,1] and base model temperature is [0,2], and yuan 0.9 == base 1 so need to convert
|
33 |
+
temperature = self.temperature * 0.9 if self.temperature <= 1 else 0.9 + (self.temperature - 1) / 10
|
34 |
+
|
35 |
+
request_body = {
|
36 |
+
"model": self.model_name.replace('minimax-', ''),
|
37 |
+
"temperature": temperature,
|
38 |
+
"skip_info_mask": True,
|
39 |
+
'messages': [{"sender_type": "USER", "text": self.history[-1]['content']}]
|
40 |
+
}
|
41 |
+
if self.n_choices:
|
42 |
+
request_body['beam_width'] = self.n_choices
|
43 |
+
if self.system_prompt:
|
44 |
+
request_body['prompt'] = self.system_prompt
|
45 |
+
if self.max_generation_token:
|
46 |
+
request_body['tokens_to_generate'] = self.max_generation_token
|
47 |
+
if self.top_p:
|
48 |
+
request_body['top_p'] = self.top_p
|
49 |
+
|
50 |
+
response = requests.post(self.url, headers=self.headers, json=request_body)
|
51 |
+
|
52 |
+
res = response.json()
|
53 |
+
answer = res['reply']
|
54 |
+
total_token_count = res["usage"]["total_tokens"]
|
55 |
+
return answer, total_token_count
|
56 |
+
|
57 |
+
def get_answer_stream_iter(self):
|
58 |
+
response = self._get_response(stream=True)
|
59 |
+
if response is not None:
|
60 |
+
iter = self._decode_chat_response(response)
|
61 |
+
partial_text = ""
|
62 |
+
for i in iter:
|
63 |
+
partial_text += i
|
64 |
+
yield partial_text
|
65 |
+
else:
|
66 |
+
yield STANDARD_ERROR_MSG + GENERAL_ERROR_MSG
|
67 |
+
|
68 |
+
def _get_response(self, stream=False):
|
69 |
+
minimax_api_key = self.api_key
|
70 |
+
history = self.history
|
71 |
+
logging.debug(colorama.Fore.YELLOW +
|
72 |
+
f"{history}" + colorama.Fore.RESET)
|
73 |
+
headers = {
|
74 |
+
"Content-Type": "application/json",
|
75 |
+
"Authorization": f"Bearer {minimax_api_key}",
|
76 |
+
}
|
77 |
+
|
78 |
+
temperature = self.temperature * 0.9 if self.temperature <= 1 else 0.9 + (self.temperature - 1) / 10
|
79 |
+
|
80 |
+
messages = []
|
81 |
+
for msg in self.history:
|
82 |
+
if msg['role'] == 'user':
|
83 |
+
messages.append({"sender_type": "USER", "text": msg['content']})
|
84 |
+
else:
|
85 |
+
messages.append({"sender_type": "BOT", "text": msg['content']})
|
86 |
+
|
87 |
+
request_body = {
|
88 |
+
"model": self.model_name.replace('minimax-', ''),
|
89 |
+
"temperature": temperature,
|
90 |
+
"skip_info_mask": True,
|
91 |
+
'messages': messages
|
92 |
+
}
|
93 |
+
if self.n_choices:
|
94 |
+
request_body['beam_width'] = self.n_choices
|
95 |
+
if self.system_prompt:
|
96 |
+
lines = self.system_prompt.splitlines()
|
97 |
+
if lines[0].find(":") != -1 and len(lines[0]) < 20:
|
98 |
+
request_body["role_meta"] = {
|
99 |
+
"user_name": lines[0].split(":")[0],
|
100 |
+
"bot_name": lines[0].split(":")[1]
|
101 |
+
}
|
102 |
+
lines.pop()
|
103 |
+
request_body["prompt"] = "\n".join(lines)
|
104 |
+
if self.max_generation_token:
|
105 |
+
request_body['tokens_to_generate'] = self.max_generation_token
|
106 |
+
else:
|
107 |
+
request_body['tokens_to_generate'] = 512
|
108 |
+
if self.top_p:
|
109 |
+
request_body['top_p'] = self.top_p
|
110 |
+
|
111 |
+
if stream:
|
112 |
+
timeout = TIMEOUT_STREAMING
|
113 |
+
request_body['stream'] = True
|
114 |
+
request_body['use_standard_sse'] = True
|
115 |
+
else:
|
116 |
+
timeout = TIMEOUT_ALL
|
117 |
+
try:
|
118 |
+
response = requests.post(
|
119 |
+
self.url,
|
120 |
+
headers=headers,
|
121 |
+
json=request_body,
|
122 |
+
stream=stream,
|
123 |
+
timeout=timeout,
|
124 |
+
)
|
125 |
+
except:
|
126 |
+
return None
|
127 |
+
|
128 |
+
return response
|
129 |
+
|
130 |
+
def _decode_chat_response(self, response):
|
131 |
+
error_msg = ""
|
132 |
+
for chunk in response.iter_lines():
|
133 |
+
if chunk:
|
134 |
+
chunk = chunk.decode()
|
135 |
+
chunk_length = len(chunk)
|
136 |
+
print(chunk)
|
137 |
+
try:
|
138 |
+
chunk = json.loads(chunk[6:])
|
139 |
+
except json.JSONDecodeError:
|
140 |
+
print(i18n("JSON解析错误,��到的内容: ") + f"{chunk}")
|
141 |
+
error_msg += chunk
|
142 |
+
continue
|
143 |
+
if chunk_length > 6 and "delta" in chunk["choices"][0]:
|
144 |
+
if "finish_reason" in chunk["choices"][0] and chunk["choices"][0]["finish_reason"] == "stop":
|
145 |
+
self.all_token_counts.append(chunk["usage"]["total_tokens"] - sum(self.all_token_counts))
|
146 |
+
break
|
147 |
+
try:
|
148 |
+
yield chunk["choices"][0]["delta"]
|
149 |
+
except Exception as e:
|
150 |
+
logging.error(f"Error: {e}")
|
151 |
+
continue
|
152 |
+
if error_msg:
|
153 |
+
try:
|
154 |
+
error_msg = json.loads(error_msg)
|
155 |
+
if 'base_resp' in error_msg:
|
156 |
+
status_code = error_msg['base_resp']['status_code']
|
157 |
+
status_msg = error_msg['base_resp']['status_msg']
|
158 |
+
raise Exception(f"{status_code} - {status_msg}")
|
159 |
+
except json.JSONDecodeError:
|
160 |
+
pass
|
161 |
+
raise Exception(error_msg)
|
modules/models/models.py
CHANGED
@@ -15,7 +15,6 @@ from PIL import Image
|
|
15 |
|
16 |
from tqdm import tqdm
|
17 |
import colorama
|
18 |
-
from duckduckgo_search import ddg
|
19 |
import asyncio
|
20 |
import aiohttp
|
21 |
from enum import Enum
|
@@ -603,12 +602,14 @@ def get_model(
|
|
603 |
elif model_type == ModelType.YuanAI:
|
604 |
from .inspurai import Yuan_Client
|
605 |
model = Yuan_Client(model_name, api_key=access_key, user_name=user_name, system_prompt=system_prompt)
|
|
|
|
|
|
|
|
|
|
|
606 |
elif model_type == ModelType.ChuanhuAgent:
|
607 |
from .ChuanhuAgent import ChuanhuAgent_Client
|
608 |
model = ChuanhuAgent_Client(model_name, access_key, user_name=user_name)
|
609 |
-
elif model_type == ModelType.PaLM:
|
610 |
-
from .PaLM import PaLM_Client
|
611 |
-
model = PaLM_Client(model_name, user_name=user_name)
|
612 |
elif model_type == ModelType.Unknown:
|
613 |
raise ValueError(f"未知模型: {model_name}")
|
614 |
logging.info(msg)
|
|
|
15 |
|
16 |
from tqdm import tqdm
|
17 |
import colorama
|
|
|
18 |
import asyncio
|
19 |
import aiohttp
|
20 |
from enum import Enum
|
|
|
602 |
elif model_type == ModelType.YuanAI:
|
603 |
from .inspurai import Yuan_Client
|
604 |
model = Yuan_Client(model_name, api_key=access_key, user_name=user_name, system_prompt=system_prompt)
|
605 |
+
elif model_type == ModelType.Minimax:
|
606 |
+
from .minimax import MiniMax_Client
|
607 |
+
if os.environ.get("MINIMAX_API_KEY") != "":
|
608 |
+
access_key = os.environ.get("MINIMAX_API_KEY")
|
609 |
+
model = MiniMax_Client(model_name, api_key=access_key, user_name=user_name, system_prompt=system_prompt)
|
610 |
elif model_type == ModelType.ChuanhuAgent:
|
611 |
from .ChuanhuAgent import ChuanhuAgent_Client
|
612 |
model = ChuanhuAgent_Client(model_name, access_key, user_name=user_name)
|
|
|
|
|
|
|
613 |
elif model_type == ModelType.Unknown:
|
614 |
raise ValueError(f"未知模型: {model_name}")
|
615 |
logging.info(msg)
|
modules/presets.py
CHANGED
@@ -59,20 +59,21 @@ APPEARANCE_SWITCHER = """
|
|
59 |
"""
|
60 |
|
61 |
ONLINE_MODELS = [
|
62 |
-
"川虎助理",
|
63 |
-
"川虎助理 Pro",
|
64 |
"gpt-3.5-turbo",
|
65 |
"gpt-3.5-turbo-0301",
|
66 |
"gpt-4",
|
67 |
"gpt-4-0314",
|
68 |
"gpt-4-32k",
|
69 |
"gpt-4-32k-0314",
|
|
|
|
|
70 |
"xmchat",
|
71 |
-
"Google PaLM",
|
72 |
"yuanai-1.0-base_10B",
|
73 |
"yuanai-1.0-translate",
|
74 |
"yuanai-1.0-dialog",
|
75 |
"yuanai-1.0-rhythm_poems",
|
|
|
|
|
76 |
]
|
77 |
|
78 |
LOCAL_MODELS = [
|
|
|
59 |
"""
|
60 |
|
61 |
ONLINE_MODELS = [
|
|
|
|
|
62 |
"gpt-3.5-turbo",
|
63 |
"gpt-3.5-turbo-0301",
|
64 |
"gpt-4",
|
65 |
"gpt-4-0314",
|
66 |
"gpt-4-32k",
|
67 |
"gpt-4-32k-0314",
|
68 |
+
"川虎助理",
|
69 |
+
"川虎助理 Pro",
|
70 |
"xmchat",
|
|
|
71 |
"yuanai-1.0-base_10B",
|
72 |
"yuanai-1.0-translate",
|
73 |
"yuanai-1.0-dialog",
|
74 |
"yuanai-1.0-rhythm_poems",
|
75 |
+
"minimax-abab4-chat",
|
76 |
+
"minimax-abab5-chat",
|
77 |
]
|
78 |
|
79 |
LOCAL_MODELS = [
|
modules/shared.py
CHANGED
@@ -1,6 +1,7 @@
|
|
1 |
from modules.presets import COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST
|
2 |
import os
|
3 |
import queue
|
|
|
4 |
|
5 |
class State:
|
6 |
interrupted = False
|
@@ -15,23 +16,28 @@ class State:
|
|
15 |
def recover(self):
|
16 |
self.interrupted = False
|
17 |
|
18 |
-
def set_api_host(self, api_host):
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
|
|
|
|
|
|
23 |
|
24 |
def reset_api_host(self):
|
25 |
self.completion_url = COMPLETION_URL
|
26 |
self.balance_api_url = BALANCE_API_URL
|
27 |
self.usage_api_url = USAGE_API_URL
|
28 |
-
os.environ["OPENAI_API_BASE"] = f"https://{API_HOST}
|
29 |
return API_HOST
|
30 |
|
31 |
def reset_all(self):
|
32 |
self.interrupted = False
|
33 |
self.completion_url = COMPLETION_URL
|
34 |
-
|
35 |
def set_api_key_queue(self, api_key_list):
|
36 |
self.multi_api_key = True
|
37 |
self.api_key_queue = queue.Queue()
|
@@ -50,6 +56,6 @@ class State:
|
|
50 |
return ret
|
51 |
|
52 |
return wrapped
|
53 |
-
|
54 |
|
55 |
state = State()
|
|
|
1 |
from modules.presets import COMPLETION_URL, BALANCE_API_URL, USAGE_API_URL, API_HOST
|
2 |
import os
|
3 |
import queue
|
4 |
+
import openai
|
5 |
|
6 |
class State:
|
7 |
interrupted = False
|
|
|
16 |
def recover(self):
|
17 |
self.interrupted = False
|
18 |
|
19 |
+
def set_api_host(self, api_host: str):
|
20 |
+
api_host = api_host.rstrip("/")
|
21 |
+
if not api_host.startswith("http"):
|
22 |
+
api_host = f"https://{api_host}"
|
23 |
+
if api_host.endswith("/v1"):
|
24 |
+
api_host = api_host[:-3]
|
25 |
+
self.completion_url = f"{api_host}/v1/chat/completions"
|
26 |
+
self.balance_api_url = f"{api_host}/dashboard/billing/credit_grants"
|
27 |
+
self.usage_api_url = f"{api_host}/dashboard/billing/usage"
|
28 |
+
os.environ["OPENAI_API_BASE"] = api_host
|
29 |
|
30 |
def reset_api_host(self):
|
31 |
self.completion_url = COMPLETION_URL
|
32 |
self.balance_api_url = BALANCE_API_URL
|
33 |
self.usage_api_url = USAGE_API_URL
|
34 |
+
os.environ["OPENAI_API_BASE"] = f"https://{API_HOST}"
|
35 |
return API_HOST
|
36 |
|
37 |
def reset_all(self):
|
38 |
self.interrupted = False
|
39 |
self.completion_url = COMPLETION_URL
|
40 |
+
|
41 |
def set_api_key_queue(self, api_key_list):
|
42 |
self.multi_api_key = True
|
43 |
self.api_key_queue = queue.Queue()
|
|
|
56 |
return ret
|
57 |
|
58 |
return wrapped
|
59 |
+
|
60 |
|
61 |
state = State()
|
modules/utils.py
CHANGED
@@ -116,6 +116,9 @@ def set_single_turn(current_model, *args):
|
|
116 |
def handle_file_upload(current_model, *args):
|
117 |
return current_model.handle_file_upload(*args)
|
118 |
|
|
|
|
|
|
|
119 |
def like(current_model, *args):
|
120 |
return current_model.like(*args)
|
121 |
|
|
|
116 |
def handle_file_upload(current_model, *args):
|
117 |
return current_model.handle_file_upload(*args)
|
118 |
|
119 |
+
def handle_summarize_index(current_model, *args):
|
120 |
+
return current_model.summarize_index(*args)
|
121 |
+
|
122 |
def like(current_model, *args):
|
123 |
return current_model.like(*args)
|
124 |
|
requirements.txt
CHANGED
@@ -1,14 +1,14 @@
|
|
1 |
-
gradio==3.
|
2 |
-
gradio_client==0.
|
3 |
mdtex2html
|
4 |
pypinyin
|
5 |
tiktoken
|
6 |
socksio
|
7 |
tqdm
|
8 |
colorama
|
9 |
-
|
10 |
Pygments
|
11 |
-
langchain==0.0.
|
12 |
markdown
|
13 |
PyPDF2
|
14 |
pdfplumber
|
@@ -24,4 +24,3 @@ wikipedia
|
|
24 |
google.generativeai
|
25 |
openai
|
26 |
unstructured
|
27 |
-
google-api-python-client
|
|
|
1 |
+
gradio==3.30.0
|
2 |
+
gradio_client==0.2.4
|
3 |
mdtex2html
|
4 |
pypinyin
|
5 |
tiktoken
|
6 |
socksio
|
7 |
tqdm
|
8 |
colorama
|
9 |
+
googlesearch-python
|
10 |
Pygments
|
11 |
+
langchain==0.0.173
|
12 |
markdown
|
13 |
PyPDF2
|
14 |
pdfplumber
|
|
|
24 |
google.generativeai
|
25 |
openai
|
26 |
unstructured
|
|