Spaces:
Runtime error
Runtime error
Update app.py
Browse files35 unmodified lines363738394041424 unmodified lines4748495051525313 unmodified lines676869707172737475767778794 unmodified lines848586878889909 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612712812910 unmodified lines14014114214314414514614714814915015 unmodified lines16616716816917017117210 unmodified lines18318418518618718818935 unmodified lines)logger.info("Tokenizer loaded successfully")# Load model - Modificada la carga del modelologger.info("Loading model...")model = AutoModelForCausalLM.from_pretrained(model_name,4 unmodified linesmodel = model.to(device)logger.info("Model loaded successfully")# Create pipeline - Modificada la creación del pipelinelogger.info("Creating generation pipeline...")model_gen = pipeline("text-generation",13 unmodified linesraise# Configure system messagesystem_message = {"role": "system","content": """You are AQuaBot, an AI assistant aware of environmental impact.You help users with any topic while raising awareness about water consumptionin AI. Did you know that training GPT-3 consumed 5.4 million liters of water,equivalent to the daily consumption of a city of 10,000 people?"""}# Constants for water consumption calculationWATER_PER_TOKEN = {4 unmodified lines}# Initialize variablesmessages = [system_message]total_water_consumption = 0def calculate_tokens(text):9 unmodified linesreturn tokens * (WATER_PER_TOKEN["input_training"] + WATER_PER_TOKEN["input_inference"])return tokens * (WATER_PER_TOKEN["output_training"] + WATER_PER_TOKEN["output_inference"])@spaces.GPU(duration=60)@torch.inference_mode()def generate_response(user_input, chat_history):try:logger.info("Generating response for user input...")global total_water_consumption, messages# Calculate water consumption for inputinput_water_consumption = calculate_water_consumption(user_input, True)total_water_consumption += input_water_consumption# Add user input to messagesmessages.append({"role": "user", "content": user_input})# Create promptprompt = ""for m in messages:if m["role"] == "system":prompt += f"<START SYSTEM MESSAGE>\n{m['content']}\n<END SYSTEM MESSAGE>\n\n"elif m["role"] == "user":prompt += f"User: {m['content']}\n"else:prompt += f"Assistant: {m['content']}\n"prompt += "Assistant:"logger.info("Generating model response...")outputs = model_gen(10 unmodified linesoutput_water_consumption = calculate_water_consumption(assistant_response, False)total_water_consumption += output_water_consumption# Add assistant's response to messagesmessages.append({"role": "assistant", "content": assistant_response})# Update chat historychat_history.append((user_input, assistant_response))# Prepare water consumption messagewater_message = f"""15 unmodified linesexcept Exception as e:logger.error(f"Error in generate_response: {str(e)}")error_message = f"An error occurred: {str(e)}"chat_history.append((user_input, error_message))return chat_history, show_water# Create Gradio interface10 unmodified lines</div>""")chatbot = gr.Chatbot(type="messages")message = gr.Textbox(placeholder="Type your message here...",show_label=False35 unmodified lines363738394041424 unmodified lines4748495051525313 unmodified lines676869707172737475764 unmodified lines8182838485869 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012112210 unmodified lines13313413513613713813914015 unmodified lines15615715815916016116210 unmodified lines17317417517617717817935 unmodified lines)logger.info("Tokenizer loaded successfully")# Load modellogger.info("Loading model...")model = AutoModelForCausalLM.from_pretrained(model_name,4 unmodified linesmodel = model.to(device)logger.info("Model loaded successfully")# Create pipelinelogger.info("Creating generation pipeline...")model_gen = pipeline("text-generation",13 unmodified linesraise# Configure system messagesystem_message = """You are AQuaBot, an AI assistant aware of environmental impact.You help users with any topic while raising awareness about water consumptionin AI. Did you know that training GPT-3 consumed 5.4 million liters of water,equivalent to the daily consumption of a city of 10,000 people?"""# Constants for water consumption calculationWATER_PER_TOKEN = {4 unmodified lines}# Initialize variablestotal_water_consumption = 0def calculate_tokens(text):9 unmodified linesreturn tokens * (WATER_PER_TOKEN["input_training"] + WATER_PER_TOKEN["input_inference"])return tokens * (WATER_PER_TOKEN["output_training"] + WATER_PER_TOKEN["output_inference"])def format_message(role, content):return {"role": role, "content": content}@spaces.GPU(duration=60)@torch.inference_mode()def generate_response(user_input, chat_history):try:logger.info("Generating response for user input...")global total_water_consumption# Calculate water consumption for inputinput_water_consumption = calculate_water_consumption(user_input, True)total_water_consumption += input_water_consumption# Create promptconversation_history = ""if chat_history:for message in chat_history:conversation_history += f"User: {message[0]}\nAssistant: {message[1]}\n"prompt = f"{system_message}\n\n{conversation_history}User: {user_input}\nAssistant:"logger.info("Generating model response...")outputs = model_gen(10 unmodified linesoutput_water_consumption = calculate_water_consumption(assistant_response, False)total_water_consumption += output_water_consumption# Update chat history with the new formatted messageschat_history.append([user_input, assistant_response])# Prepare water consumption messagewater_message = f"""15 unmodified linesexcept Exception as e:logger.error(f"Error in generate_response: {str(e)}")error_message = f"An error occurred: {str(e)}"chat_history.append([user_input, error_message])return chat_history, show_water# Create Gradio interface10 unmodified lines</div>""")chatbot = gr.Chatbot()message = gr.Textbox(placeholder="Type your message here...",show_label=False
app.py+20-30