Spaces:
Paused
Paused
Husnain commited on
🔨 [WIP] Enabling get_message_id
Browse files123456784 unmodified lines131415161718195 unmodified lines252627282930312 unmodified lines343536373839404142434445464748495 unmodified lines5556575859604 unmodified lines656667686970714 unmodified lines7677787980import jsonimport reimport requestsfrom tclogger import loggerfrom transformers import AutoTokenizer4 unmodified linesTOKEN_RESERVED,)from constants.envs import PROXIESfrom constants.networks import REQUESTS_HEADERSfrom messagers.message_outputer import OpenaiStreamOutputer5 unmodified linesself.model = "mixtral-8x7b"self.model_fullname = MODEL_MAP[self.model]self.message_outputer = OpenaiStreamOutputer(model=self.model)# export HF_ENDPOINT=https://hf-mirror.comself.tokenizer = AutoTokenizer.from_pretrained(self.model_fullname)def count_tokens(self, text):2 unmodified lineslogger.note(f"Prompt Token Count: {token_count}")return token_countdef get_conversation_id(self, preprompt: str = ""):request_url = "https://huggingface.co/chat/conversation"request_body = {"model": self.model_fullname,"preprompt": preprompt,}logger.note(f"> Conversation ID:", end=" ")res = requests.post(request_url,headers=REQUESTS_HEADERS,json=request_body,proxies=PROXIES,timeout=10,5 unmodified lineslogger.warn(f"[{res.status_code}]")raise ValueError("Failed to get conversation ID!")self.conversation_id = conversation_iddef chat_response(self,4 unmodified linesapi_key: str = None,use_cache: bool = False,):passdef chat_return_dict(self, stream_response):pass4 unmodified linesif __name__ == "__main__":streamer = HuggingchatStreamer(model="mixtral-8x7b")conversation_id = streamer.get_conversation_id()# python -m networks.huggingchat_streamer123456789104 unmodified lines15161718192021222324255 unmodified lines3132333435362 unmodified lines394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283845 unmodified lines909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741754 unmodified lines1801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152164 unmodified lines221222223224225226import copyimport jsonimport reimport requestsimport uuid# from curl_cffi import requestsfrom tclogger import loggerfrom transformers import AutoTokenizer4 unmodified linesTOKEN_RESERVED,)from constants.envs import PROXIESfrom constants.headers import (REQUESTS_HEADERS,HUGGINGCHAT_POST_HEADERS,HUGGINGCHAT_SETTINGS_POST_DATA,)from messagers.message_outputer import OpenaiStreamOutputer5 unmodified linesself.model = "mixtral-8x7b"self.model_fullname = MODEL_MAP[self.model]self.message_outputer = OpenaiStreamOutputer(model=self.model)self.tokenizer = AutoTokenizer.from_pretrained(self.model_fullname)def count_tokens(self, text):2 unmodified lineslogger.note(f"Prompt Token Count: {token_count}")return token_countdef get_hf_chat_id(self):request_url = "https://huggingface.co/chat/settings"request_body = copy.deepcopy(HUGGINGCHAT_SETTINGS_POST_DATA)extra_body = {"activeModel": self.model_fullname,}request_body.update(extra_body)logger.note(f"> hf-chat ID:", end=" ")res = requests.post(request_url,headers=HUGGINGCHAT_POST_HEADERS,json=request_body,proxies=PROXIES,timeout=10,)self.hf_chat_id = res.cookies.get("hf-chat")if self.hf_chat_id:logger.success(f"[{self.hf_chat_id}]")else:logger.warn(f"[{res.status_code}]")logger.warn(res.text)raise ValueError("Failed to get hf-chat ID!")def get_conversation_id(self, preprompt: str = ""):request_url = "https://huggingface.co/chat/conversation"request_headers = HUGGINGCHAT_POST_HEADERSextra_headers = {"Cookie": f"hf-chat={self.hf_chat_id}",}request_headers.update(extra_headers)request_body = {"model": self.model_fullname,"preprompt": preprompt,}logger.note(f"> Conversation ID:", end=" ")res = requests.post(request_url,headers=request_headers,json=request_body,proxies=PROXIES,timeout=10,5 unmodified lineslogger.warn(f"[{res.status_code}]")raise ValueError("Failed to get conversation ID!")self.conversation_id = conversation_idreturn conversation_iddef get_message_id(self):request_url = f"https://huggingface.co/chat/conversation/{self.conversation_id}/__data.json?x-sveltekit-invalidated=11"request_headers = HUGGINGCHAT_POST_HEADERSextra_headers = {"Cookie": f"hf-chat={self.hf_chat_id}",}request_headers.update(extra_headers)logger.note(f"> Message ID:", end=" ")message_id = Noneres = requests.post(request_url,headers=request_headers,proxies=PROXIES,timeout=10,)if res.status_code == 200:data = res.json()# TODO - extract message_idlogger.success(f"[{message_id}]")else:logger.warn(f"[{res.status_code}]")raise ValueError("Failed to get conversation ID!")return message_iddef log_request(self, url, method="GET"):logger.note(f"> {method}:", end=" ")logger.mesg(f"{url}", end=" ")def log_response(self, res: requests.Response, stream=False, iter_lines=False, verbose=False):status_code = res.status_codestatus_code_str = f"[{status_code}]"if status_code == 200:logger_func = logger.successelse:logger_func = logger.warnlogger_func(status_code_str)logger.enter_quiet(not verbose)if status_code != 200:logger_func(res.text)if stream:if not iter_lines:returnfor line in res.iter_lines():line = line.decode("utf-8")line = re.sub(r"^data:\s*", "", line)line = line.strip()if line:try:data = json.loads(line, strict=False)msg_type = data.get("type")if msg_type == "status":msg_status = data.get("status")elif msg_type == "stream":content = data.get("token", "")logger_func(content, end="")elif msg_type == "finalAnswer":full_content = data.get("text")logger.success("\n[Finished]")breakelse:passexcept Exception as e:logger.warn(e)else:logger_func(res.json())logger.exit_quiet(not verbose)def chat_response(self,4 unmodified linesapi_key: str = None,use_cache: bool = False,):self.get_hf_chat_id()self.get_conversation_id()message_id = self.get_message_id()request_url = f"https://huggingface.co/chat/conversation/{self.conversation_id}"request_headers = copy.deepcopy(HUGGINGCHAT_POST_HEADERS)extra_headers = {"Content-Type": "text/event-stream","Referer": request_url,"Cookie": f"hf-chat={self.hf_chat_id}",}request_headers.update(extra_headers)request_body = {"files": [],"id": message_id,"inputs": prompt,"is_continue": False,"is_retry": False,"web_search": False,}self.log_request(request_url, method="POST")res = requests.post(request_url,headers=request_headers,json=request_body,proxies=PROXIES,stream=True,)self.log_response(res, stream=True, iter_lines=True, verbose=True)return resdef chat_return_dict(self, stream_response):pass4 unmodified linesif __name__ == "__main__":streamer = HuggingchatStreamer(model="mixtral-8x7b")prompt = "who are you?"streamer.chat_response(prompt=prompt)# HF_ENDPOINT=https://hf-mirror.com python -m networks.huggingchat_streamer
networks/huggingchat_streamer.py+153-7