Skip to content

Commit

Permalink
+异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
Your Name committed Apr 2, 2023
1 parent 16de181 commit 51b3f8a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
7 changes: 4 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
if not AUTHENTICATION: AUTHENTICATION = None

initial_prompt = "Serve me as a writing and programming assistant."
title_html = """<h1 align="center">ChatGPT 学术优化</h1>"""
title_html = "<h1 align=\"center\">ChatGPT 学术优化</h1>"
description = """代码开源和更新[地址🚀](https://github.com/binary-husky/chatgpt_academic),感谢热情的[开发者们❤️](https://github.com/binary-husky/chatgpt_academic/graphs/contributors)"""

# 问询记录, python 版本建议3.9+(越新越好)
import logging
Expand Down Expand Up @@ -78,12 +79,12 @@
with gr.Row():
with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
with gr.Accordion("展开SysPrompt & GPT参数 & 交互界面布局", open=False):
with gr.Accordion("展开SysPrompt & 交互界面布局 & Github地址", open=False):
system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区")

gr.Markdown(description)
# 功能区显示开关与功能区的互动
def fn_area_visibility(a):
ret = {}
Expand Down
10 changes: 6 additions & 4 deletions predict.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,16 @@ def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt=''
error_msg = chunk.decode()
if "reduce the length" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")
history = []
history = [] # 清除历史
elif "Incorrect API key" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")
elif "exceeded your current quota" in error_msg:
chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由,拒绝服务.")
else:
from toolbox import regular_txt_to_markdown
tb_str = regular_txt_to_markdown(traceback.format_exc())
chatbot[-1] = (chatbot[-1][0], f"[Local Message] Json Error \n\n {tb_str} \n\n {regular_txt_to_markdown(chunk.decode()[4:])}")
yield chatbot, history, "Json解析不合常规" + error_msg
tb_str = '```\n' + traceback.format_exc() + '```'
chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk.decode()[4:])}")
yield chatbot, history, "Json异常" + error_msg
return

def generate_payload(inputs, top_p, temperature, history, system_prompt, stream):
Expand Down
23 changes: 21 additions & 2 deletions toolbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,8 +115,9 @@ def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PO
from check_proxy import check_proxy
from toolbox import get_conf
proxies, = get_conf('proxies')
tb_str = regular_txt_to_markdown(traceback.format_exc())
chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}")
tb_str = '```\n' + traceback.format_exc() + '```'
if len(chatbot) == 0: chatbot.append(["插件调度异常","异常原因"])
chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n{tb_str} \n\n当前代理可用性: \n\n{check_proxy(proxies)}")
yield chatbot, history, f'异常 {e}'
return decorated

Expand Down Expand Up @@ -164,6 +165,23 @@ def markdown_convertion(txt):
else:
return pre + markdown.markdown(txt,extensions=['fenced_code','tables']) + suf

def close_up_code_segment_during_stream(gpt_reply):
"""
在gpt输出代码的中途(输出了前面的```,但还没输出完后面的```),补上后面的```
"""
if '```' not in gpt_reply: return gpt_reply
if gpt_reply.endswith('```'): return gpt_reply

# 排除了以上两个情况,我们
segments = gpt_reply.split('```')
n_mark = len(segments) - 1
if n_mark % 2 == 1:
print('输出代码片段中!')
return gpt_reply+'\n```'
else:
return gpt_reply



def format_io(self, y):
"""
Expand All @@ -172,6 +190,7 @@ def format_io(self, y):
if y is None or y == []: return []
i_ask, gpt_reply = y[-1]
i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波
gpt_reply = close_up_code_segment_during_stream(gpt_reply) # 当代码输出半截的时候,试着补上后个```
y[-1] = (
None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']),
None if gpt_reply is None else markdown_convertion(gpt_reply)
Expand Down

0 comments on commit 51b3f8a

Please sign in to comment.