CoolFace
Apppublic

fufa/chatgpt

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
predict.py241 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            chunk = get_full_error(chunk.encode('utf8'), stream_response)100            raise ConnectionAbortedError("OpenAI拒绝了请求:" + chunk.decode())101        delta = json.loads(chunk.lstrip('data:'))['choices'][0]["delta"]102        if len(delta) == 0: break103        if "role" in delta: continue104        if "content" in delta: result += delta["content"]; print(delta["content"], end='')105        else: raise RuntimeError("意外Json结构:"+delta)106    return result107 108 109def predict(inputs, top_p, temperature, chatbot=[], history=[], system_prompt='', 110            stream = True, additional_fn=None):111    """112        发送至chatGPT,流式获取输出。113        用于基础的对话功能。114        inputs 是本次问询的输入115        top_p, temperature是chatGPT的内部调优参数116        history 是之前的对话列表(注意无论是inputs还是history,内容太长了都会触发token数量溢出的错误)117        chatbot 为WebUI中显示的对话列表,修改它,然后yeild出去,可以直接修改对话界面内容118        additional_fn代表点击的哪个按钮,按钮见functional.py119    """120    if additional_fn is not None:121        import functional122        importlib.reload(functional)    # 热更新prompt123        functional = functional.get_functionals()124        if "PreProcess" in functional[additional_fn]: inputs = functional[additional_fn]["PreProcess"](inputs)  # 获取预处理函数(如果有的话)125        inputs = functional[additional_fn]["Prefix"] + inputs + functional[additional_fn]["Suffix"]126 127    if stream:128        raw_input = inputs129        logging.info(f'[raw_input] {raw_input}')130        chatbot.append((inputs, ""))131        yield chatbot, history, "等待响应"132 133    headers, payload = generate_payload(inputs, top_p, temperature, history, system_prompt, stream)134    history.append(inputs); history.append(" ")135 136    retry = 0137    while True:138        try:139            # make a POST request to the API endpoint, stream=True140            response = requests.post(API_URL, headers=headers, proxies=proxies,141                                    json=payload, stream=True, timeout=TIMEOUT_SECONDS);break142        except:143            retry += 1144            chatbot[-1] = ((chatbot[-1][0], timeout_bot_msg))145            retry_msg = f",正在重试 ({retry}/{MAX_RETRY}) ……" if MAX_RETRY > 0 else ""146            yield chatbot, history, "请求超时"+retry_msg147            if retry > MAX_RETRY: raise TimeoutError148 149    gpt_replying_buffer = ""150    151    is_head_of_the_stream = True152    if stream:153        stream_response =  response.iter_lines()154        while True:155            chunk = next(stream_response)156            # print(chunk.decode()[6:])157            if is_head_of_the_stream:158                # 数据流的第一帧不携带content159                is_head_of_the_stream = False; continue160            161            if chunk:162                try:163                    if len(json.loads(chunk.decode()[6:])['choices'][0]["delta"]) == 0:164                        # 判定为数据流的结束,gpt_replying_buffer也写完了165                        logging.info(f'[response] {gpt_replying_buffer}')166                        break167                    # 处理数据流的主体168                    chunkjson = json.loads(chunk.decode()[6:])169                    status_text = f"finish_reason: {chunkjson['choices'][0]['finish_reason']}"170                    # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出171                    gpt_replying_buffer = gpt_replying_buffer + json.loads(chunk.decode()[6:])['choices'][0]["delta"]["content"]172                    history[-1] = gpt_replying_buffer173                    chatbot[-1] = (history[-2], history[-1])174                    yield chatbot, history, status_text175 176                except Exception as e:177                    traceback.print_exc()178                    yield chatbot, history, "Json解析不合常规"179                    chunk = get_full_error(chunk, stream_response)180                    error_msg = chunk.decode()181                    if "reduce the length" in error_msg:182                        chatbot[-1] = (chatbot[-1][0], "[Local Message] Input (or history) is too long, please reduce input or clear history by refreshing this page.")183                        history = []184                    elif "Incorrect API key" in error_msg:185                        chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key provided.")186                    else:187                        from toolbox import regular_txt_to_markdown188                        tb_str = regular_txt_to_markdown(traceback.format_exc())189                        chatbot[-1] = (chatbot[-1][0], f"[Local Message] Json Error \n\n {tb_str} \n\n {regular_txt_to_markdown(chunk.decode()[4:])}")190                    yield chatbot, history, "Json解析不合常规" + error_msg191                    return192 193def generate_payload(inputs, top_p, temperature, history, system_prompt, stream):194    """195        整合所有信息,选择LLM模型,生成http请求,为发送请求做准备196    """197    headers = {198        "Content-Type": "application/json",199        "Authorization": f"Bearer {API_KEY}"200    }201 202    conversation_cnt = len(history) // 2203 204    messages = [{"role": "system", "content": system_prompt}]205    if conversation_cnt:206        for index in range(0, 2*conversation_cnt, 2):207            what_i_have_asked = {}208            what_i_have_asked["role"] = "user"209            what_i_have_asked["content"] = history[index]210            what_gpt_answer = {}211            what_gpt_answer["role"] = "assistant"212            what_gpt_answer["content"] = history[index+1]213            if what_i_have_asked["content"] != "":214                if what_gpt_answer["content"] == "": continue215                if what_gpt_answer["content"] == timeout_bot_msg: continue216                messages.append(what_i_have_asked)217                messages.append(what_gpt_answer)218            else:219                messages[-1]['content'] = what_gpt_answer['content']220 221    what_i_ask_now = {}222    what_i_ask_now["role"] = "user"223    what_i_ask_now["content"] = inputs224    messages.append(what_i_ask_now)225 226    payload = {227        "model": LLM_MODEL,228        "messages": messages, 229        "temperature": temperature,  # 1.0,230        "top_p": top_p,  # 1.0,231        "n": 1,232        "stream": stream,233        "presence_penalty": 0,234        "frequency_penalty": 0,235    }236    237    print(f" {LLM_MODEL} : {conversation_cnt} : {inputs}")238    return headers,payload239 240 241