CoolFace
Apppublic

SoDa12321/ChatGPT_for_Academic_Releases1

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
predict.py247 linesDownload Raw Back to root
1# 借鉴了 https://github.com/GaiZhenbiao/ChuanhuChatGPT 项目2 3"""4    该文件中主要包含三个函数5 6    不具备多线程能力的函数:7    1. predict: 正常对话时使用,具备完备的交互功能,不可多线程8 9    具备多线程调用能力的函数10    2. predict_no_ui:高级实验性功能模块调用,不会实时显示在界面上,参数简单,可以多线程并行,方便实现复杂的功能逻辑11    3. predict_no_ui_long_connection:在实验过程中发现调用predict_no_ui处理长文档时,和openai的连接容易断掉,这个函数用stream的方式解决这个问题,同样支持多线程12"""13 14import json15import gradio as gr16import logging17import traceback18import requests19import importlib20 21# config_private.py放自己的秘密如API和代理网址22# 读取时首先看是否存在私密的config_private配置文件(不受git管控),如果有,则覆盖原config文件23from toolbox import get_conf24proxies, API_URL, API_KEY, TIMEOUT_SECONDS, MAX_RETRY, LLM_MODEL = \25    get_conf('proxies', 'API_URL', 'API_KEY', 'TIMEOUT_SECONDS', 'MAX_RETRY', 'LLM_MODEL')26 27timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \28                  '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。'29 30def get_full_error(chunk, stream_response):31    """32        获取完整的从Openai返回的报错33    """34    while True:35        try:36            chunk += next(stream_response)37        except:38            break39    return chunk40 41def predict_no_ui(inputs, top_p, temperature, history=[], sys_prompt=""):42    """43        发送至chatGPT,等待回复,一次性完成,不显示中间过程。44        predict函数的简化版。45        用于payload比较大的情况,或者用于实现多线、带嵌套的复杂功能。46 47        inputs 是本次问询的输入48        top_p, temperature是chatGPT的内部调优参数49        history 是之前的对话列表50        (注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误,然后raise ConnectionAbortedError)51    """52    headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=False)53 54    retry = 055    while True:56        try:57            # make a POST request to the API endpoint, stream=False58            response = requests.post(API_URL, headers=headers, proxies=proxies,59                                    json=payload, stream=False, timeout=TIMEOUT_SECONDS*2); break60        except requests.exceptions.ReadTimeout as e:61            retry += 162            traceback.print_exc()63            if retry > MAX_RETRY: raise TimeoutError64            if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')65 66    try:67        result = json.loads(response.text)["choices"][0]["message"]["content"]68        return result69    except Exception as e:70        if "choices" not in response.text: print(response.text)71        raise ConnectionAbortedError("Json解析不合常规,可能是文本过长" + response.text)72 73 74def predict_no_ui_long_connection(inputs, top_p, temperature, history=[], sys_prompt=""):75    """76        发送至chatGPT,等待回复,一次性完成,不显示中间过程。但内部用stream的方法避免有人中途掐网线。77    """78    headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt=sys_prompt, stream=True)79 80    retry = 081    while True:82        try:83            # make a POST request to the API endpoint, stream=False84            response = requests.post(API_URL, headers=headers, proxies=proxies,85                                    json=payload, stream=True, timeout=TIMEOUT_SECONDS); break86        except requests.exceptions.ReadTimeout as e:87            retry += 188            traceback.print_exc()89            if retry > MAX_RETRY: raise TimeoutError90            if MAX_RETRY!=0: print(f'请求超时,正在重试 ({retry}/{MAX_RETRY}) ……')91 92    stream_response =  response.iter_lines()93    result = ''94    while True:95        try: chunk = next(stream_response).decode()96        except StopIteration: break97        if len(chunk)==0: continue98        if not chunk.startswith('data:'): 99            error_msg = get_full_error(chunk.encode('utf8'), stream_response).decode()100            if "reduce the length" in error_msg:101                raise ConnectionAbortedError("OpenAI拒绝了请求:" + error_msg)102            else:103                raise RuntimeError("OpenAI拒绝了请求:" + error_msg)104        json_data = json.loads(chunk.lstrip('data:'))['choices'][0]105        delta = json_data["delta"]106        if len(delta) == 0: break107        if "role" in delta: continue108        if "content" in delta: result += delta["content"]; print(delta["content"], end='')109        else: raise RuntimeError("意外Json结构:"+delta)110    if json_data['finish_reason'] == 'length':111        raise ConnectionAbortedError("正常结束,但显示Token不足。")112    return result113 114 115def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='', 116            stream = True, additional_fn=None):117    """118        发送至chatGPT,流式获取输出。119        用于基础的对话功能。120        inputs 是本次问询的输入121        top_p, temperature是chatGPT的内部调优参数122        history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)123        chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容124        additional_fn代表点击的哪个按钮,按钮见functional.py125    """126    if additional_fn is not None:127        import functional128        importlib.reload(functional)    # 热更新prompt129        functional = functional.get_functionals()130        if "PreProcess" in functional[additional_fn]: inputs = functional[additional_fn]["PreProcess"](inputs)  # 获取预处理函数(如果有的话)131        inputs = functional[additional_fn]["Prefix"] + inputs + functional[additional_fn]["Suffix"]132 133    if stream:134        raw_input = inputs135        logging.info(f'[raw_input] {raw_input}')136        chatbot.append((inputs, ""))137        yield chatbot, history, "等待响应"138 139    headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt, stream)140    history.append(inputs); history.append(" ")141 142    retry = 0143    while True:144        try:145            # make a POST request to the API endpoint, stream=True146            response = requests.post(API_URL, headers=headers, proxies=proxies,147                                    json=payload, stream=True, timeout=TIMEOUT_SECONDS);break148        except:149            retry += 1150            chatbot[-1] = ((chatbot[-1][0], timeout_bot_msg))151            retry_msg = f",正在重试 ({retry}/{MAX_RETRY}) ……" if MAX_RETRY > 0 else ""152            yield chatbot, history, "请求超时"+retry_msg153            if retry > MAX_RETRY: raise TimeoutError154 155    gpt_replying_buffer = ""156    157    is_head_of_the_stream = True158    if stream:159        stream_response =  response.iter_lines()160        while True:161            chunk = next(stream_response)162            # print(chunk.decode()[6:])163            if is_head_of_the_stream:164                # 数据流的第一帧不携带content165                is_head_of_the_stream = False; continue166            167            if chunk:168                try:169                    if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:170                        # 判定为数据流的结束,gpt_replying_buffer也写完了171                        logging.info(f'[response] {gpt_replying_buffer}')172                        break173                    # 处理数据流的主体174                    chunkjson = json.loads(chunk.decode()[6:])175                    status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"176                    # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出177                    gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]178                    history[-1] = gpt_replying_buffer179                    chatbot[-1] = (history[-2], history[-1])180                    yield chatbot, history, status_text181 182                except Exception as e:183                    traceback.print_exc()184                    yield chatbot, history, "Json解析不合常规"185                    chunk = get_full_error(chunk, stream_response)186                    error_msg = chunk.decode()187                    if "reduce the length" in error_msg:188                        chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")189                        history = []190                    elif "Incorrect API key" in error_msg:191                        chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")192                    else:193                        from toolbox import regular_txt_to_markdown194                        tb_str = regular_txt_to_markdown(traceback.format_exc())195                        chatbot[-1] = (chatbot[-1][0], f"[Local Message] Json Error \n\n {tb_str} \n\n {regular_txt_to_markdown(chunk.decode()[4:])}")196                    yield chatbot, history, "Json解析不合常规" + error_msg197                    return198 199def generate_payload(inputs, top_p, temperature, history, system_prompt, stream):200    """201        整合所有信息,选择LLM模型,生成http请求,为发送请求做准备202    """203    headers = {204        "Content-Type": "application/json",205        "Authorization": f"Bearer {API_KEY}"206    }207 208    conversation_cnt = len(history) // 2209 210    messages = [{"role": "system", "content": system_prompt}]211    if conversation_cnt:212        for index in range(0, 2*conversation_cnt, 2):213            what_i_have_asked = {}214            what_i_have_asked["role"] = "user"215            what_i_have_asked["content"] = history[index]216            what_gpt_answer = {}217            what_gpt_answer["role"] = "assistant"218            what_gpt_answer["content"] = history[index+1]219            if what_i_have_asked["content"] != "":220                if what_gpt_answer["content"] == "": continue221                if what_gpt_answer["content"] == timeout_bot_msg: continue222                messages.append(what_i_have_asked)223                messages.append(what_gpt_answer)224            else:225                messages[-1]['content'] = what_gpt_answer['content']226 227    what_i_ask_now = {}228    what_i_ask_now["role"] = "user"229    what_i_ask_now["content"] = inputs230    messages.append(what_i_ask_now)231 232    payload = {233        "model": LLM_MODEL,234        "messages": messages, 235        "temperature": temperature,  # 1.0,236        "top_p": top_p,  # 1.0,237        "n": 1,238        "stream": stream,239        "presence_penalty": 0,240        "frequency_penalty": 0,241    }242    243    print(f" {LLM_MODEL} : {conversation_cnt} : {inputs}")244    return headers,payload245 246 247