Files changed (2)
- app.py+66-59
- requirements.txt+1-1
1234567891011121314151617181926 unmodified lines4647484950515253545556575859606162636465666768697071727374757677787926 unmodified lines1061071081091101111121131144 unmodified lines1191201211221231241251261271281291301311325 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691708 unmodified lines1791801811821831841854 unmodified lines190191192193194195196# Requires gradio==3.16.2# Requires huggingface_hub==0.11.0import gradio as grfrom huggingface_hub import InferenceClientimport loggingfrom functools import lru_cacheimport htmlimport signal# Setup logginglogging.basicConfig(level=logging.INFO)# Initialize the Hugging Face Inference Clientclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta")# ConstantsMAX_HISTORY_LENGTH = 5 # Adjust as needed26 unmodified lineselse:return "You are a helpful assistant."@lru_cache(maxsize=32)def get_response_from_model(messages_tuple, max_tokens, temperature, top_p):"""Calls the Hugging Face Inference API to get a response.Parameters:messages_tuple (tuple): A tuple of messages to be sent to the model.max_tokens (int): Maximum number of tokens for the response.temperature (float): Sampling temperature.top_p (float): Top-p (nucleus) sampling parameter.Returns:str: The generated response from the model."""# Convert tuple back to list of dictsmessages = [dict(m) for m in messages_tuple]response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):token = message.choices[0].delta.contentresponse += tokenreturn responsedef sanitize_input(text):"""Sanitizes user input to prevent code injection or XSS attacks.26 unmodified linesreturn False, "Error: 'Top-p' must be between 0.1 and 1.0."return True, ""def respond(message, history, persona_choice, custom_persona, max_tokens, temperature, top_p):"""Generates a response using the Hugging Face Inference API.Parameters:message (str): User's current input.4 unmodified linestemperature (float): Sampling temperature.top_p (float): Top-p (nucleus sampling) parameter.Yields:str: The generated chatbot response."""# Validate parametersis_valid, error_message = validate_parameters(max_tokens, temperature, top_p)if not is_valid:yield error_messagereturn# Sanitize user inputsafe_message = sanitize_input(message)5 unmodified lines# Select system messagesystem_message = system_message_selector(persona_choice, custom_persona)# Build messages with truncated historymessages = [{"role": "system", "content": system_message}]for user_msg, bot_msg in truncated_history:if user_msg:messages.append({"role": "user", "content": user_msg})if bot_msg:messages.append({"role": "assistant", "content": bot_msg})messages.append({"role": "user", "content": safe_message})# Log the requestlogging.info(f"Received message: {safe_message}")try:# Convert messages to a tuple of tuples for cachingmessages_tuple = tuple(tuple(m.items()) for m in messages)# Use caching to optimize performanceresponse = get_response_from_model(messages_tuple,max_tokens,temperature,top_p,)yield responseexcept Exception as e:logging.error(f"An error occurred: {e}")yield "I'm sorry, but something went wrong. Please try again."# Create the UI componentssystem_message_radio = gr.Radio(8 unmodified lines)max_tokens_slider = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")temperature_slider = gr.Slider(4 unmodified linesminimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")# Create the ChatInterface directly with additional inputsdemo = gr.ChatInterface(fn=respond,additional_inputs=[123456789101112131426 unmodified lines41424344454626 unmodified lines7374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261274 unmodified lines1321331341351361371381391401411421431445 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711721731741751761778 unmodified lines1861871881891901911924 unmodified lines197198199200201202203import gradio as grimport transformersimport torchimport loggingimport htmlimport signalfrom functools import lru_cache# Setup logginglogging.basicConfig(level=logging.INFO)# ConstantsMAX_HISTORY_LENGTH = 5 # Adjust as needed26 unmodified lineselse:return "You are a helpful assistant."def sanitize_input(text):"""Sanitizes user input to prevent code injection or XSS attacks.26 unmodified linesreturn False, "Error: 'Top-p' must be between 0.1 and 1.0."return True, ""# Load the model and tokenizermodel_name = "HuggingFaceH4/zephyr-7b-beta" # Replace with your actual model nametry:tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)model = transformers.AutoModelForCausalLM.from_pretrained(model_name,torch_dtype=torch.float16,device_map="auto" # Automatically places model layers on available GPUs)model.eval()except Exception as e:logging.error(f"Failed to load model {model_name}: {e}")exit(1)@lru_cache(maxsize=32)def generate_response(prompt, max_tokens, temperature, top_p):"""Generates a response using the loaded language model.Parameters:prompt (str): The input prompt for the model.max_tokens (int): Maximum number of tokens for the response.temperature (float): Sampling temperature.top_p (float): Top-p (nucleus) sampling parameter.Returns:str: The generated response from the model."""input_ids = tokenizer.encode(prompt, return_tensors="pt")input_ids = input_ids.to(model.device)with torch.no_grad():output_ids = model.generate(input_ids,max_length=input_ids.shape[1] + max_tokens,temperature=temperature,top_p=top_p,do_sample=True,pad_token_id=tokenizer.eos_token_id,eos_token_id=tokenizer.eos_token_id,)generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True)return generated_text[len(prompt):].strip()def respond(message, history, persona_choice, custom_persona, max_tokens, temperature, top_p):"""Generates a response using the loaded language model.Parameters:message (str): User's current input.4 unmodified linestemperature (float): Sampling temperature.top_p (float): Top-p (nucleus sampling) parameter.Returns:str: The generated chatbot response."""# Validate parametersis_valid, error_message = validate_parameters(max_tokens, temperature, top_p)if not is_valid:return error_message# Sanitize user inputsafe_message = sanitize_input(message)5 unmodified lines# Select system messagesystem_message = system_message_selector(persona_choice, custom_persona)# Build the conversation promptconversation = system_message + "\n\n"for user_msg, bot_msg in truncated_history:conversation += f"User: {user_msg}\n"conversation += f"Assistant: {bot_msg}\n"conversation += f"User: {safe_message}\nAssistant:"# Log the requestlogging.info(f"Received message: {safe_message}")try:# Use caching to optimize performanceresponse = generate_response(prompt=conversation,max_tokens=max_tokens,temperature=temperature,top_p=top_p,)return responseexcept Exception as e:logging.error(f"An error occurred: {e}")return "I'm sorry, but something went wrong. Please try again."# Create the UI componentssystem_message_radio = gr.Radio(8 unmodified lines)max_tokens_slider = gr.Slider(minimum=1, maximum=1024, value=512, step=1, label="Max new tokens")temperature_slider = gr.Slider(4 unmodified linesminimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")# Create the ChatInterfacedemo = gr.ChatInterface(fn=respond,additional_inputs=[
123transformers==4.31.0gradio==3.40.1torch==2.0.1123transformers==4.31.0gradio==3.40.1torch==2.0.1
app.py+66-59
requirements.txt+1-1