Spaces:
Runtime error
Runtime error
Commit ·
feea96b
1
Parent(s): 7624bc7
Delete chatbot.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154import jsonimport gradio as grimport osimport requests
hf_token = os.getenv('HF_TOKEN')api_url = "http://region-31.seetacloud.com:46766/v1/chat/completions"headers = { 'Content-Type': 'application/json',}
TIME_OUT_SECONDS = 30
system_message = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe.Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content.Please ensure that your responses are socially unbiased and positive in nature.If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct.If you don't know the answer to a question, please don't share false information."""
title = "Next llama Chatbot"description = """...""" # 保留你原始的描述css = """.toast-wrap { display: none !important } """examples = [ ['Hello there! How are you doing?'], # ... 其他示例]
def post_process_response(response_content): lines = response_content.split("\n") processed_lines = [] for line in lines: if not (line.startswith("User:") or line.startswith("Human:") or line.startswith("Assistant:")): processed_lines.append(line) return "\n".join(processed_lines)
def process_api_response(response): assistant_response = "" for line in response.iter_lines(): decoded_line = line.decode('utf-8').strip() if decoded_line.startswith("data: "): decoded_line = decoded_line[6:] if decoded_line: try: json_line = json.loads(decoded_line) if "choices" in json_line and "delta" in json_line["choices"][0]: delta = json_line["choices"][0]["delta"] if "content" in delta: assistant_response += delta["content"] processed_response = post_process_response(assistant_response) yield processed_response except json.JSONDecodeError: print(f"Failed to decode line: {decoded_line}")
def predict(message, chatbot, system_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.6, repetition_penalty=1.0): messages = [ { "role": "assistant", "content": system_prompt }, { "role": "user", "content": message } ]
data = { "model": "LLaMa-2-13B-chat", "messages": messages, "stream": True, "temperature": temperature, "max_tokens": max_new_tokens, "presence_penalty": repetition_penalty }
# 打印发送到后端的API数据 print("Sending the following data to the backend API:") print(json.dumps(data, indent=4))
try: response = requests.post(api_url, headers=headers, data=json.dumps(data), auth=('hf', hf_token), stream=True, timeout=TIME_OUT_SECONDS) if response.status_code == 200: yield from process_api_response(response) elif response.status_code == 401: yield "Error: Unauthorized" else: yield f"Error with status code: {response.status_code}" except requests.Timeout: yield "Error: Request timed out" except requests.RequestException as e: yield f"Error: {e}"
# def vote(data: gr.LikeData):# if data.liked:# print("You upvoted this response: " + data.value)# else:# print("You downvoted this response: " + data.value)
additional_inputs = [ gr.Textbox("", label="Optional system prompt"), gr.Slider( label="Temperature", value=0.9, minimum=0.0, maximum=1.0, step=0.05, interactive=True, info="Higher values produce more diverse outputs", ), gr.Slider( label="Max new tokens", value=256, minimum=0, maximum=4096, step=64, interactive=True, info="The maximum numbers of new tokens", ), gr.Slider( label="Top-p (nucleus sampling)", value=0.6, minimum=0.0, maximum=1, step=0.05, interactive=True, info="Higher values sample more low-probability tokens", ), gr.Slider( label="Repetition penalty", value=1.2, minimum=1.0, maximum=2.0, step=0.05, interactive=True, info="Penalize repeated tokens", )]
# Remove the unrecognized arguments from gr.Chatbotchatbot_stream = gr.Chatbot()
# Since gr.ChatInterface doesn't support additional_inputs, we'll need to adjust our design.# For now, I'm removing the additional_inputs argument. You might need to consider a different interface type if you want to use these inputs.chat_interface_stream = gr.ChatInterface(predict, title=title, description=description, chatbot=chatbot_stream, css=css, examples=examples, cache_examples=True)
chat_interface_stream.queue().launch(debug=True)chatbot.pyDeleted-154