LuckyHappyFish commited on
Commit
29cff03
·
1 Parent(s): 5bd35a5
Files changed (1) hide show
  1. app.py +95 -107
app.py CHANGED
@@ -5,7 +5,6 @@ import traceback
5
  import os
6
 
7
  # Initialize the Inference Client with your model
8
- # Ensure you have set the HUGGINGFACE_API_TOKEN environment variable
9
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=os.getenv("HUGGINGFACE_API_TOKEN"))
10
 
11
  def respond(
@@ -17,15 +16,13 @@ def respond(
17
  current_salary
18
  ):
19
  """
20
- Handles the negotiation conversation and assesses salary changes.
21
  """
22
- # Define the system message internally (hidden from the user)
23
  system_message = (
24
- "You are a hiring manager negotiating a job offer. "
25
- "Your initial offer is $60,000. "
26
- "Only increase the salary if the candidate provides compelling reasons. "
27
- "Communicate any salary offers explicitly in your responses, "
28
- "and only mention the salary when you are making an offer."
29
  )
30
 
31
  # Initialize the messages with the system prompt
@@ -41,9 +38,9 @@ def respond(
41
  # Append the latest user message
42
  messages.append({"role": "user", "content": message})
43
 
44
- # Generate the AI response (Negotiation Interaction)
45
  try:
46
- ai_response = client.chat_completion(
47
  messages,
48
  max_tokens=max_tokens,
49
  temperature=temperature,
@@ -51,69 +48,65 @@ def respond(
51
  stop=None
52
  ).get("choices")[0].get("message").get("content")
53
  except Exception as e:
54
- ai_response = f"An error occurred while communicating with the AI: {e}"
55
  traceback.print_exc()
56
 
57
- # Append AI response to history
58
- history.append((message, ai_response))
59
 
60
- # Assess the negotiation outcome (Salary Assessment Interaction)
61
- # Prepare the assessment prompt
62
- assessment_prompt = (
63
- "Based on the following conversation, determine if the candidate's salary should be increased, "
64
- "decreased, or remain the same compared to $60,000. Respond with one of the following words only: 'increase', 'decrease', or 'same'.\n\n"
65
- "Conversation:\n"
66
  )
67
 
 
 
 
 
68
  for user_msg, ai_msg in history:
69
  if user_msg:
70
- assessment_prompt += f"User: {user_msg}\n"
71
  if ai_msg:
72
- assessment_prompt += f"AI: {ai_msg}\n"
73
 
74
- # Send the assessment prompt to the AI
75
  try:
76
- assessment_response = client.chat_completion(
77
- [{"role": "user", "content": assessment_prompt}],
78
  max_tokens=10,
79
- temperature=0,
80
- top_p=1.0,
81
  stop=None
82
- ).get("choices")[0].get("message").get("content").strip().lower()
83
  except Exception as e:
84
- assessment_response = f"An error occurred during salary assessment: {e}"
85
  traceback.print_exc()
 
86
 
87
- # Determine salary adjustment based on assessment
88
- if assessment_response == "increase":
89
- increment = 5000 # Fixed increment; modify as desired
90
- current_salary += increment
91
- negotiation_result = f"🎉 Negotiation successful! Your salary has been increased to ${current_salary:,}."
92
- # Append the negotiation result to history as an AI message
93
- history.append(("", negotiation_result))
94
- elif assessment_response == "decrease":
95
- decrement = 5000 # Fixed decrement; modify as desired
96
- current_salary -= decrement
97
- # Ensure salary doesn't go below $60,000
98
- if current_salary < 60000:
99
- current_salary = 60000
100
- negotiation_result = f"⚠️ Negotiation resulted in no change. Your salary remains at $60,000."
101
  else:
102
- negotiation_result = f"⚠️ Negotiation resulted in a salary decrease to ${current_salary:,}."
103
- history.append(("", negotiation_result))
104
- elif assessment_response == "same":
105
- negotiation_result = f"✅ No change to your salary. It remains at ${current_salary:,}."
106
- history.append(("", negotiation_result))
107
- else:
108
- # If the response is unclear, do not change the salary
109
- negotiation_result = "🤔 I couldn't determine the salary adjustment based on the conversation."
110
- history.append(("", negotiation_result))
111
 
112
- return history, current_salary
113
 
114
  def reset_game():
115
  """
116
- Resets the game to its initial state.
117
  """
118
  return [], 60000 # Reset history and salary to $60,000
119
 
@@ -122,65 +115,60 @@ with gr.Blocks() as demo:
122
  gr.Markdown("# 💼 Salary Negotiation Game")
123
  gr.Markdown(
124
  """
125
- **Objective:** Negotiate your salary starting from \$60,000.
126
-
127
  **Instructions:**
128
- - Use the chat interface to negotiate your salary with the hiring manager.
129
  - Provide compelling reasons for a higher salary.
130
  - The hiring manager will consider your arguments and may adjust the offer.
131
  """
132
  )
133
-
134
- with gr.Row():
135
- with gr.Column(scale=1):
136
- # Reset button to restart the game
137
- reset_btn = gr.Button("Reset Game")
138
- reset_btn.click(fn=reset_game, inputs=None, outputs=[gr.State(), gr.State()])
139
- with gr.Column(scale=3):
140
- # Chat history to keep track of the conversation
141
- chat_history = gr.State([])
142
-
143
- # Chat Interface
144
- chatbot = gr.Chatbot()
145
-
146
- # User input
147
- user_input = gr.Textbox(
148
- label="Your Message",
149
- placeholder="Enter your negotiation message here...",
150
- lines=2
151
- )
152
- send_button = gr.Button("Send")
153
-
154
- def handle_message(message, history, max_tokens, temperature, top_p, current_salary):
155
- """
156
- Handles user messages, updates the conversation history, and manages salary adjustments.
157
- """
158
- history, current_salary = respond(message, history, max_tokens, temperature, top_p, current_salary)
159
- return history, current_salary, "" # Clear the input textbox
160
-
161
- send_button.click(
162
- handle_message,
163
- inputs=[
164
- user_input,
165
- chat_history,
166
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max New Tokens"),
167
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
168
- gr.Slider(
169
- minimum=0.1,
170
- maximum=1.0,
171
- value=0.95,
172
- step=0.05,
173
- label="Top-p (nucleus sampling)",
174
- ),
175
- gr.State(60000) # Initial salary
176
- ],
177
- outputs=[
178
- chatbot,
179
- gr.State(), # Update the salary state
180
- user_input # Clear the input textbox
181
- ]
182
- )
183
-
184
  gr.Markdown(
185
  """
186
  ---
 
5
  import os
6
 
7
  # Initialize the Inference Client with your model
 
8
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=os.getenv("HUGGINGFACE_API_TOKEN"))
9
 
10
  def respond(
 
16
  current_salary
17
  ):
18
  """
19
+ Respond function to handle the conversation and update salary based on AI's assessment.
20
  """
21
+ # Define the system message for the conversation (hidden from the user)
22
  system_message = (
23
+ "You are a hiring manager negotiating a job offer with a candidate. "
24
+ "Your initial salary offer is $60,000. "
25
+ "Engage in a negotiation with the candidate, adjusting your offer based on their arguments."
 
 
26
  )
27
 
28
  # Initialize the messages with the system prompt
 
38
  # Append the latest user message
39
  messages.append({"role": "user", "content": message})
40
 
41
+ # Generate the AI's response to the user's message
42
  try:
43
+ response = client.chat_completion(
44
  messages,
45
  max_tokens=max_tokens,
46
  temperature=temperature,
 
48
  stop=None
49
  ).get("choices")[0].get("message").get("content")
50
  except Exception as e:
51
+ response = f"An error occurred while communicating with the AI: {e}"
52
  traceback.print_exc()
53
 
54
+ # Append the AI's response to the history
55
+ history.append((message, response))
56
 
57
+ # Now, send the conversation to the AI to get the updated salary
58
+ # Prepare the salary assessment prompt
59
+ salary_assessment_prompt = (
60
+ "As the hiring manager, based on the conversation so far, "
61
+ "what salary do you now offer to the candidate? "
62
+ "Please provide only the salary amount as a number, without any additional text."
63
  )
64
 
65
+ # Prepare the messages for salary assessment
66
+ assessment_messages = [{"role": "system", "content": salary_assessment_prompt}]
67
+
68
+ # Include the conversation history
69
  for user_msg, ai_msg in history:
70
  if user_msg:
71
+ assessment_messages.append({"role": "user", "content": user_msg})
72
  if ai_msg:
73
+ assessment_messages.append({"role": "assistant", "content": ai_msg})
74
 
75
+ # Generate the AI's salary assessment
76
  try:
77
+ salary_response = client.chat_completion(
78
+ assessment_messages,
79
  max_tokens=10,
80
+ temperature=temperature,
81
+ top_p=top_p,
82
  stop=None
83
+ ).get("choices")[0].get("message").get("content")
84
  except Exception as e:
85
+ salary_response = f"An error occurred while assessing salary: {e}"
86
  traceback.print_exc()
87
+ salary_response = str(current_salary)
88
 
89
+ # Parse the salary from the AI's response
90
+ try:
91
+ # Remove any non-digit characters
92
+ salary_str = re.sub(r'[^\d]', '', salary_response)
93
+ if salary_str:
94
+ new_salary = int(salary_str)
95
+ if new_salary != current_salary:
96
+ # Update current_salary
97
+ current_salary = new_salary
 
 
 
 
 
98
  else:
99
+ # If parsing fails, keep the current salary
100
+ pass
101
+ except Exception as e:
102
+ # If parsing fails, keep the current salary
103
+ pass
 
 
 
 
104
 
105
+ return history, "", current_salary # Return history, clear input, and update salary internally
106
 
107
  def reset_game():
108
  """
109
+ Function to reset the game to initial state.
110
  """
111
  return [], 60000 # Reset history and salary to $60,000
112
 
 
115
  gr.Markdown("# 💼 Salary Negotiation Game")
116
  gr.Markdown(
117
  """
118
+ **Objective:** Negotiate your salary starting from $60,000.
119
+
120
  **Instructions:**
121
+ - Use the chat to negotiate your salary with the hiring manager.
122
  - Provide compelling reasons for a higher salary.
123
  - The hiring manager will consider your arguments and may adjust the offer.
124
  """
125
  )
126
+
127
+ # Chat history to keep track of the conversation
128
+ chat_history = gr.State([])
129
+
130
+ # Current salary (hidden from the user)
131
+ current_salary_state = gr.State(60000)
132
+
133
+ # Chat Interface
134
+ chatbot = gr.Chatbot()
135
+
136
+ # User input
137
+ user_input = gr.Textbox(
138
+ label="Your Message",
139
+ placeholder="Enter your negotiation message here...",
140
+ lines=2
141
+ )
142
+ send_button = gr.Button("Send")
143
+
144
+ def handle_message(message, history, max_tokens, temperature, top_p, current_salary):
145
+ """
146
+ Handles user messages and updates the conversation history and salary.
147
+ """
148
+ history, _, current_salary = respond(message, history, max_tokens, temperature, top_p, current_salary)
149
+ return history, "", current_salary
150
+
151
+ send_button.click(
152
+ handle_message,
153
+ inputs=[
154
+ user_input,
155
+ chat_history,
156
+ gr.Number(value=512, label="Max New Tokens"),
157
+ gr.Number(value=0.7, label="Temperature"),
158
+ gr.Number(value=0.95, label="Top-p"),
159
+ current_salary_state # Pass the current salary
160
+ ],
161
+ outputs=[
162
+ chatbot,
163
+ user_input, # Clear the input textbox
164
+ current_salary_state # Update the salary internally
165
+ ]
166
+ )
167
+
168
+ # Reset button to restart the game
169
+ reset_btn = gr.Button("Reset Game")
170
+ reset_btn.click(fn=reset_game, inputs=None, outputs=[chat_history, current_salary_state])
171
+
 
 
 
 
 
172
  gr.Markdown(
173
  """
174
  ---