Spaces:
Build error
Build error
Commit ·
29cff03
1
Parent(s): 5bd35a5
done
Browse files4 unmodified lines5678910115 unmodified lines1718192021222324252627282930319 unmodified lines4142434445464748491 unmodified line515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181192 unmodified lines1221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851864 unmodified linesimport os# Initialize the Inference Client with your model# Ensure you have set the HUGGINGFACE_API_TOKEN environment variableclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=os.getenv("HUGGINGFACE_API_TOKEN"))def respond(5 unmodified linescurrent_salary):"""Handles the negotiation conversation and assesses salary changes."""# Define the system message internally (hidden from the user)system_message = ("You are a hiring manager negotiating a job offer. ""Your initial offer is $60,000. ""Only increase the salary if the candidate provides compelling reasons. ""Communicate any salary offers explicitly in your responses, ""and only mention the salary when you are making an offer.")# Initialize the messages with the system prompt9 unmodified lines# Append the latest user messagemessages.append({"role": "user", "content": message})# Generate the AI response (Negotiation Interaction)try:ai_response = client.chat_completion(messages,max_tokens=max_tokens,temperature=temperature,1 unmodified linestop=None).get("choices")[0].get("message").get("content")except Exception as e:ai_response = f"An error occurred while communicating with the AI: {e}"traceback.print_exc()# Append AI response to historyhistory.append((message, ai_response))# Assess the negotiation outcome (Salary Assessment Interaction)# Prepare the assessment promptassessment_prompt = ("Based on the following conversation, determine if the candidate's salary should be increased, ""decreased, or remain the same compared to $60,000. Respond with one of the following words only: 'increase', 'decrease', or 'same'.\n\n""Conversation:\n")for user_msg, ai_msg in history:if user_msg:assessment_prompt += f"User: {user_msg}\n"if ai_msg:assessment_prompt += f"AI: {ai_msg}\n"# Send the assessment prompt to the AItry:assessment_response = client.chat_completion([{"role": "user", "content": assessment_prompt}],max_tokens=10,temperature=0,top_p=1.0,stop=None).get("choices")[0].get("message").get("content").strip().lower()except Exception as e:assessment_response = f"An error occurred during salary assessment: {e}"traceback.print_exc()# Determine salary adjustment based on assessmentif assessment_response == "increase":increment = 5000 # Fixed increment; modify as desiredcurrent_salary += incrementnegotiation_result = f"🎉 Negotiation successful! Your salary has been increased to ${current_salary:,}."# Append the negotiation result to history as an AI messagehistory.append(("", negotiation_result))elif assessment_response == "decrease":decrement = 5000 # Fixed decrement; modify as desiredcurrent_salary -= decrement# Ensure salary doesn't go below $60,000if current_salary < 60000:current_salary = 60000negotiation_result = f"⚠️ Negotiation resulted in no change. Your salary remains at $60,000."else:negotiation_result = f"⚠️ Negotiation resulted in a salary decrease to ${current_salary:,}."history.append(("", negotiation_result))elif assessment_response == "same":negotiation_result = f"✅ No change to your salary. It remains at ${current_salary:,}."history.append(("", negotiation_result))else:# If the response is unclear, do not change the salarynegotiation_result = "🤔 I couldn't determine the salary adjustment based on the conversation."history.append(("", negotiation_result))return history, current_salarydef reset_game():"""Resets the game to its initial state."""return [], 60000 # Reset history and salary to $60,0002 unmodified linesgr.Markdown("# 💼 Salary Negotiation Game")gr.Markdown("""**Objective:** Negotiate your salary starting from \$60,000.**Instructions:**- Use the chat interface to negotiate your salary with the hiring manager.- Provide compelling reasons for a higher salary.- The hiring manager will consider your arguments and may adjust the offer.""")with gr.Row():with gr.Column(scale=1):# Reset button to restart the gamereset_btn = gr.Button("Reset Game")reset_btn.click(fn=reset_game, inputs=None, outputs=[gr.State(), gr.State()])with gr.Column(scale=3):# Chat history to keep track of the conversationchat_history = gr.State([])# Chat Interfacechatbot = gr.Chatbot()# User inputuser_input = gr.Textbox(label="Your Message",placeholder="Enter your negotiation message here...",lines=2)send_button = gr.Button("Send")def handle_message(message, history, max_tokens, temperature, top_p, current_salary):"""Handles user messages, updates the conversation history, and manages salary adjustments."""history, current_salary = respond(message, history, max_tokens, temperature, top_p, current_salary)return history, current_salary, "" # Clear the input textboxsend_button.click(handle_message,inputs=[user_input,chat_history,gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max New Tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),gr.State(60000) # Initial salary],outputs=[chatbot,gr.State(), # Update the salary stateuser_input # Clear the input textbox])gr.Markdown("""---4 unmodified lines56789105 unmodified lines161718192021222324252627289 unmodified lines3839404142434445461 unmodified line484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111122 unmodified lines1151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731744 unmodified linesimport os# Initialize the Inference Client with your modelclient = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=os.getenv("HUGGINGFACE_API_TOKEN"))def respond(5 unmodified linescurrent_salary):"""Respond function to handle the conversation and update salary based on AI's assessment."""# Define the system message for the conversation (hidden from the user)system_message = ("You are a hiring manager negotiating a job offer with a candidate. ""Your initial salary offer is $60,000. ""Engage in a negotiation with the candidate, adjusting your offer based on their arguments.")# Initialize the messages with the system prompt9 unmodified lines# Append the latest user messagemessages.append({"role": "user", "content": message})# Generate the AI's response to the user's messagetry:response = client.chat_completion(messages,max_tokens=max_tokens,temperature=temperature,1 unmodified linestop=None).get("choices")[0].get("message").get("content")except Exception as e:response = f"An error occurred while communicating with the AI: {e}"traceback.print_exc()# Append the AI's response to the historyhistory.append((message, response))# Now, send the conversation to the AI to get the updated salary# Prepare the salary assessment promptsalary_assessment_prompt = ("As the hiring manager, based on the conversation so far, ""what salary do you now offer to the candidate? ""Please provide only the salary amount as a number, without any additional text.")# Prepare the messages for salary assessmentassessment_messages = [{"role": "system", "content": salary_assessment_prompt}]# Include the conversation historyfor user_msg, ai_msg in history:if user_msg:assessment_messages.append({"role": "user", "content": user_msg})if ai_msg:assessment_messages.append({"role": "assistant", "content": ai_msg})# Generate the AI's salary assessmenttry:salary_response = client.chat_completion(assessment_messages,max_tokens=10,temperature=temperature,top_p=top_p,stop=None).get("choices")[0].get("message").get("content")except Exception as e:salary_response = f"An error occurred while assessing salary: {e}"traceback.print_exc()salary_response = str(current_salary)# Parse the salary from the AI's responsetry:# Remove any non-digit characterssalary_str = re.sub(r'[^\d]', '', salary_response)if salary_str:new_salary = int(salary_str)if new_salary != current_salary:# Update current_salarycurrent_salary = new_salaryelse:# If parsing fails, keep the current salarypassexcept Exception as e:# If parsing fails, keep the current salarypassreturn history, "", current_salary # Return history, clear input, and update salary internallydef reset_game():"""Function to reset the game to initial state."""return [], 60000 # Reset history and salary to $60,0002 unmodified linesgr.Markdown("# 💼 Salary Negotiation Game")gr.Markdown("""**Objective:** Negotiate your salary starting from $60,000.**Instructions:**- Use the chat to negotiate your salary with the hiring manager.- Provide compelling reasons for a higher salary.- The hiring manager will consider your arguments and may adjust the offer.""")# Chat history to keep track of the conversationchat_history = gr.State([])# Current salary (hidden from the user)current_salary_state = gr.State(60000)# Chat Interfacechatbot = gr.Chatbot()# User inputuser_input = gr.Textbox(label="Your Message",placeholder="Enter your negotiation message here...",lines=2)send_button = gr.Button("Send")def handle_message(message, history, max_tokens, temperature, top_p, current_salary):"""Handles user messages and updates the conversation history and salary."""history, _, current_salary = respond(message, history, max_tokens, temperature, top_p, current_salary)return history, "", current_salarysend_button.click(handle_message,inputs=[user_input,chat_history,gr.Number(value=512, label="Max New Tokens"),gr.Number(value=0.7, label="Temperature"),gr.Number(value=0.95, label="Top-p"),current_salary_state # Pass the current salary],outputs=[chatbot,user_input, # Clear the input textboxcurrent_salary_state # Update the salary internally])# Reset button to restart the gamereset_btn = gr.Button("Reset Game")reset_btn.click(fn=reset_game, inputs=None, outputs=[chat_history, current_salary_state])gr.Markdown("""---
app.py+95-107