Spaces:
Sleeping
Sleeping
File size: 25,788 Bytes
b55f2f8 15178a4 9ba5290 b55f2f8 4ed63a7 e9880f2 4ed63a7 b55f2f8 76a14e4 4ed63a7 ec5a946 4ed63a7 189761b e9880f2 189761b 4ed63a7 b55f2f8 4ed63a7 9ba5290 4ed63a7 5052ad3 d56cecb 5052ad3 d0097c9 5052ad3 4ed63a7 5052ad3 4ed63a7 e9880f2 4ed63a7 e9880f2 4ed63a7 e9880f2 5052ad3 e9880f2 5052ad3 e9880f2 d0097c9 e9880f2 5052ad3 e9880f2 5052ad3 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 15178a4 4ed63a7 5052ad3 d56cecb e9880f2 d56cecb 5052ad3 e9880f2 5052ad3 e9880f2 5052ad3 e9880f2 5052ad3 b55f2f8 76a14e4 15178a4 76a14e4 9ba5290 69aed7a 76a14e4 5c0d2e8 69aed7a 098b28b 5c0d2e8 69aed7a 5c0d2e8 76a14e4 69aed7a 3b81fca 5c0d2e8 098b28b 69aed7a 35351f7 69aed7a 9ba5290 69aed7a 76a14e4 15178a4 76a14e4 9ba5290 69aed7a 76a14e4 5c0d2e8 098b28b 76a14e4 69aed7a 098b28b 5c0d2e8 69aed7a 098b28b 5c0d2e8 76a14e4 69aed7a 3b81fca 5c0d2e8 098b28b 69aed7a 35351f7 5c0d2e8 35351f7 098b28b 69aed7a 9ba5290 76a14e4 b55f2f8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
import gradio as gr
from huggingface_hub import InferenceClient
from typing import Optional
import os
interviewer_system_prompt = """
# Task
- You are to act as a multilingual interviewer / hiring manager for {{ COMPANY_NAME }}, hiring for the {{ SCREENER_NAME }} position.
# Conversation Tone
- You are very friendly, empathetic, enthusiastic, and interested in the users answers and experience.
- Keep it conversational and friendly.
- Maintain correct language and translation based on user's selection for all responses and statements.
# Conversation Rules
- Listen Carefully: Pay close attention to the interviewee's responses. If the answer is incomplete or doesn't directly address the question, politely ask for further details.
- Maintain Context: Keep the conversation's context in mind when formulating follow-up questions or responses. This ensures relevance and coherence throughout the interview.
- Be Adaptive: Adjust the conversation based on the interviewee's input. If an interesting point arises that's worth exploring, feel free to ask more about it while still aiming to cover all planned questions.
- Validate Responses: Ensure each response adheres to the specific rules and validation criteria set for the questions. If not, gently guide the interviewee back to the topic or ask for clarification.
- Respect Comfort Levels: If the interviewee seems uncomfortable with a question, acknowledge their feelings and offer to move on or adjust the question.
- Provide Clarity: If asked for clarification or a rephrased question, respond in a clear and understanding manner to facilitate a smooth conversation.
- Conclude Properly: At the end of the interview, thank the interviewee for their time and provide information on the next steps, if applicable.
- Avoid repetitiveness: Do not repeat questions that had been previously asked.
- Translation: If a language other than english is indicated, use that language for the rest of the conversation, and translate pre-written questions into that language.
# Company Information
- If the candidate asks you, the interviewer, questions about the company or role, respond with: Thank you for your interest in learning more about our company. To ensure you receive the most accurate and detailed information, a member of our team will address your questions later in the process. For now, let's focus on your qualifications and experiences related to this position.
- Do not respond with this unless the candidate asks you a question about the company, company details, or role details.
# EEOC Compliance
- Strictly adhere to the United States Equal Employment Opportunity Commission interview guidelines.
## Conversation EEOC Rules
- Do not ask about or discuss personal characteristics protected by law, including but not limited to: race, color, religion, sex (including gender identity, sexual orientation, and pregnancy), national origin, age, disability, genetic information, mental health, or veteran status.
- If an applicant discloses any protected characteristic, provide a neutral acknowledgment and move to next question or response.
- Immediately redirect the conversation to job-related topics and qualifications.
- Do not express any sentiments that could be interpreted as bias or judgment based on any disclosures.
- Ensure all questions and discussions relate directly to the applicant's ability to perform the essential functions of the job.
- If an applicant mentions personal information such as marital status, number of children, or other family circumstances, do not engage with or ask follow-up questions about this information. Instead, acknowledge briefly and redirect to job-related topics.
- Never ask how personal circumstances, including family situation, might affect job performance.
## Example scenarios
Candidate: "I struggle with mental health..."
Correct example response: Thank you for sharing. Let's focus on your professional experiences that relate to this position. Could you tell me about a time when you successfully managed a challenging situation in your previous role?.
Candidate: "I have 6 children..."
Correct example response: Thank you for sharing. Let's focus on your professional experiences that relate to this position. Could you tell me about a time when you successfully managed multiple priorities in a fast-paced work environment?.
# Translations
- Translate the entire conversation into the user's selected language.
- Maintain the original tone and context.
- Preserve idioms when appropriate, or adapt them for the target language.
- Keep the format, punctuation, and sentence structure similar to the original when possible.
- For specialized terms or jargon, provide the most accurate translation.
- If a word or phrase has no direct translation, transliterate it and provide a brief explanation in parentheses.
- Render the Interlude Statement and the Closing Statement in the target language.
- Translate the Company Information deflection response as well.
---
# Conversation Flow
- The interlude statement should only be given once at the beginning of the conversation.
- IMPORTANT: The Interlude Statement must be delivered in the same language as the rest of the conversation. If the user requested a language other than English, translate the Interlude Statement before delivering it.
- Do not restart the conversation for any reason.
- Maintain memory and knowledge of current point in the conversation to avoid restarting or looping back to the first question.
- If the conversation context is lost for any reason, gracefully resume from the last unanswered question instead of restarting.
- If you accidentally repeat or rephrase a question already asked, acknowledge it and move on smoothly to the next unique question.
## Sample Conversation Flow
1. Interlude statement (only given once & translated if user has selected language other than English).
2. Questions & conversation.
3. Closing Statement / Conclusion.
## Interlude Statement:
CRITICAL: Check the user's message for their language selection before delivering this statement.
Before delivering the Interlude Statement:
1. Check if the user specified a language other than English in their initial message
2. If they specified another language, translate the entire Interlude Statement into that language
3. If they did NOT specify another language, deliver the English version as written below
### Interlude Statement - English:
Perfect. Now we have {{ TOTAL_Q_COUNT }} more questions to determine how good of a fit you are for the role. We weigh these questions heavily while hiring, so please consider your answer carefully.
### Interlude Statement - Haitian Creole Translation:
Parfè. Kounye a nou gen {{ TOTAL_Q_COUNT }} lòt kesyon pou n detèmine kijan ou anfòm ak wòl la. Nou pran kesyon sa yo trè serye nan pwosesis anbochaj la, kidonk tanpri reflechi byen anvan ou reponn. Ann pase sou premye kesyon an nan seri a.
### Interlude Statement - French Translation:
Parfait. Nous avons maintenant encore {{ TOTAL_Q_COUNT }} questions pour déterminer à quel point vous correspondez au poste. Nous accordons beaucoup d'importance à ces questions dans le processus de recrutement, alors prenez le temps de bien réfléchir avant de répondre. Passons à la première question de la série.
## Inputs & Synthesization
{{#each QUESTIONS}}
"{{{ QUESTION_TEXT }}"
{{/each}}
## Closing Statement
{{ ENDING_STATEMENT }}
# Conversation Completion & End
- The Closing Statement acts as the final message of the conversation.
- If a question is asked after the Closing Statement, politely decline further conversation with "Thank you for your time. Our team will reach out with further questions or instructions.".
- Do not repeat any questions or allow the conversation to continue.
"""
candidate_system_prompt = """You are a job candidate applying for a House Cleaner position.
You are being interviewed and need to provide thoughtful, realistic answers to the interviewer's questions.
Guidelines:
- Be professional and polite
- Answer in the same language as the question
- Provide specific examples from your experience when relevant
- Keep answers concise but informative (2-4 sentences)
- Show enthusiasm for the position
- If you don't have direct experience, show willingness to learn
"""
def synthesize_prompt(company_name: str, screener_name: str, questions: str, ending_statement: str) -> str:
"""
Synthesizes the interviewer system prompt by replacing template variables
with actual values from the input fields.
Args:
company_name: The name of the company
screener_name: The position/screener name
questions: Newline-separated list of questions
ending_statement: The closing statement for the interview
Returns:
The synthesized system prompt with all variables replaced
"""
# Parse questions - split by newlines and filter empty lines
question_list = [q.strip() for q in questions.split('\n') if q.strip()]
total_q_count = len(question_list)
# Format questions for the prompt
questions_formatted = ""
for i, question in enumerate(question_list, 1):
questions_formatted += f'Question {i}: "{question}"\n'
# Start with the template
prompt = interviewer_system_prompt
# Replace template variables
prompt = prompt.replace("{{ COMPANY_NAME }}", company_name)
prompt = prompt.replace("{{ SCREENER_NAME }}", screener_name)
prompt = prompt.replace("{{ TOTAL_Q_COUNT }}", str(total_q_count))
prompt = prompt.replace("{{ ENDING_STATEMENT }}", ending_statement)
# Replace the {{#each QUESTIONS}} block with actual questions
# Find the block between {{#each QUESTIONS}} and {{/each}}
if "{{#each QUESTIONS}}" in prompt:
start_marker = "{{#each QUESTIONS}}"
end_marker = "{{/each}}"
start_idx = prompt.find(start_marker)
end_idx = prompt.find(end_marker)
if start_idx != -1 and end_idx != -1:
# Replace the entire block with formatted questions
before_block = prompt[:start_idx]
after_block = prompt[end_idx + len(end_marker):]
prompt = before_block + questions_formatted + after_block
return prompt
"""
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
"""
with gr.Blocks() as demo:
with gr.Sidebar():
gr.LoginButton()
gr.Markdown("# 🎤 House Cleaner Interview Simulator")
gr.Markdown("Chat with an AI interviewer in multiple languages or use the **Auto-Respond** button to generate realistic candidate answers. No login required!")
with gr.Row():
with gr.Column(scale=3):
# Language selection
gr.Markdown("### 🌍 Select Your Preferred Language / Seleccione su idioma preferido / Choisissez votre langue préférée / Chwazi lang ou prefere")
with gr.Row():
lang_english = gr.Button("🇺🇸 English", size="lg", scale=1)
lang_spanish = gr.Button("🇲🇽 Español (México)", size="lg", scale=1)
lang_french = gr.Button("🇫🇷 Français", size="lg", scale=1)
lang_creole = gr.Button("🇭🇹 Kreyòl Ayisyen", size="lg", scale=1)
chatbot = gr.Chatbot(
type="messages",
label="Interview Chat",
height=800
)
with gr.Row():
msg = gr.Textbox(
label="Your Message",
placeholder="Type your response here...",
scale=4,
lines=2
)
with gr.Column(scale=1, min_width=150):
submit_btn = gr.Button("Send", variant="primary", size="sm")
auto_respond_btn = gr.Button("🤖 Auto-Respond", variant="secondary", size="sm")
with gr.Row():
clear_btn = gr.ClearButton([msg, chatbot], value="Clear Chat")
with gr.Column(scale=1):
gr.Markdown("### Configuration")
company_name = gr.Textbox(
label="Company Name",
value="ABC Company",
placeholder="Enter company name",
lines=1
)
screener_name = gr.Textbox(
label="Position/Screener Name",
value="House Cleaner",
placeholder="Enter position name",
lines=1
)
questions_input = gr.Textbox(
label="Questions (one per line)",
value="Tell me about your cleaning experience.\nHow do you handle working in a team?\nWhat are your preferred cleaning methods?",
placeholder="Enter interview questions, one per line",
lines=5
)
ending_statement = gr.Textbox(
label="Ending Statement",
value="Thank you for taking the time to complete this interview. We will review your responses and get back to you within 3-5 business days.",
placeholder="Enter the closing statement",
lines=3
)
system_prompt = gr.Textbox(
lines=10,
autoscroll=True,
value=synthesize_prompt(
"ABC Company",
"House Cleaner",
"Tell me about your cleaning experience.\nHow do you handle working in a team?\nWhat are your preferred cleaning methods?",
"Thank you for taking the time to complete this interview. We will review your responses and get back to you within 3-5 business days."
),
label="Synthesized System Prompt",
interactive=True
)
max_tokens = gr.Slider(
minimum=1,
maximum=2048,
value=512,
step=1,
label="Max New Tokens"
)
temperature = gr.Slider(
minimum=0.1,
maximum=4.0,
value=0.7,
step=0.1,
label="Temperature"
)
top_p = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.95,
step=0.05,
label="Top-p (nucleus sampling)"
)
# Function to update system prompt when inputs change
def update_prompt(company, position, questions, ending):
return synthesize_prompt(company, position, questions, ending)
# Wire up auto-update for system prompt
company_name.change(
update_prompt,
[company_name, screener_name, questions_input, ending_statement],
system_prompt
)
screener_name.change(
update_prompt,
[company_name, screener_name, questions_input, ending_statement],
system_prompt
)
questions_input.change(
update_prompt,
[company_name, screener_name, questions_input, ending_statement],
system_prompt
)
ending_statement.change(
update_prompt,
[company_name, screener_name, questions_input, ending_statement],
system_prompt
)
# Language selection mapping
def get_language_greeting(language, questions_text):
"""Get the Interlude Statement in the selected language with the question count"""
# Count the questions
question_list = [q.strip() for q in questions_text.split('\n') if q.strip()]
total_q_count = len(question_list)
# Interlude Statement translations from the system prompt
greetings = {
"English": f"Perfect. Now we have {total_q_count} more questions to determine how good of a fit you are for the role. We weigh these questions heavily while hiring, so please consider your answer carefully.",
"Español (México)": f"Perfecto. Ahora tenemos {total_q_count} preguntas más para determinar qué tan adecuado eres para el puesto. Damos mucha importancia a estas preguntas en el proceso de contratación, así que considera tu respuesta cuidadosamente.",
"Français": f"Parfait. Nous avons maintenant encore {total_q_count} questions pour déterminer à quel point vous correspondez au poste. Nous accordons beaucoup d'importance à ces questions dans le processus de recrutement, alors prenez le temps de bien réfléchir avant de répondre. Passons à la première question de la série.",
"Kreyòl Ayisyen": f"Parfè. Kounye a nou gen {total_q_count} lòt kesyon pou n detèmine kijan ou anfòm ak wòl la. Nou pran kesyon sa yo trè serye nan pwosesis anbochaj la, kidonk tanpri reflechi byen anvan ou reponn. Ann pase sou premye kesyon an nan seri a.",
}
return greetings.get(language, greetings["English"])
def start_interview_in_language(language, history, system_msg, questions_text):
"""Start the interview with the Interlude Statement in the selected language. Clears any existing chat."""
# Always clear and restart when a language button is clicked
greeting = get_language_greeting(language, questions_text)
# Add language preference to system message
updated_system_msg = system_msg + f"\n\n- The candidate has selected {language} as their preferred language. Always respond in {language}."
return [{"role": "assistant", "content": greeting}], updated_system_msg
# Handle user message submission
def user_submit(user_message, history):
return "", history + [{"role": "user", "content": user_message}]
def bot_respond(history, system_msg, max_tok, temp, top_p_val, hf_token: Optional[gr.OAuthToken] = None):
if not history or history[-1]["role"] != "user":
return history
user_msg = history[-1]["content"]
history_without_last = history[:-1]
bot_response = ""
for response in respond(user_msg, history_without_last, system_msg, max_tok, temp, top_p_val, hf_token):
bot_response = response
yield history + [{"role": "assistant", "content": bot_response}]
def handle_auto_respond(history, max_tok, temp, top_p_val, hf_token: Optional[gr.OAuthToken] = None):
if not history:
return history
# Generate auto response
auto_response = generate_auto_response(history, max_tok, temp, top_p_val, hf_token)
# Add to history as user message
updated_history = history + [{"role": "user", "content": auto_response}]
return updated_history
def bot_respond_after_auto(history, system_msg, max_tok, temp, top_p_val, hf_token: Optional[gr.OAuthToken] = None):
# This is called after auto-respond to get the interviewer's response
if not history or history[-1]["role"] != "user":
return history
user_msg = history[-1]["content"]
history_without_last = history[:-1]
bot_response = ""
for response in respond(user_msg, history_without_last, system_msg, max_tok, temp, top_p_val, hf_token):
bot_response = response
yield history + [{"role": "assistant", "content": bot_response}]
# Wire up the submit button
submit_click = submit_btn.click(
user_submit,
[msg, chatbot],
[msg, chatbot],
queue=False
).then(
bot_respond,
[chatbot, system_prompt, max_tokens, temperature, top_p],
chatbot
)
msg.submit(
user_submit,
[msg, chatbot],
[msg, chatbot],
queue=False
).then(
bot_respond,
[chatbot, system_prompt, max_tokens, temperature, top_p],
chatbot
)
# Wire up the auto-respond button
auto_respond_btn.click(
handle_auto_respond,
[chatbot, max_tokens, temperature, top_p],
chatbot,
queue=False
).then(
bot_respond_after_auto,
[chatbot, system_prompt, max_tokens, temperature, top_p],
chatbot
)
# Wire up language selection buttons
lang_english.click(
lambda h, s, q: start_interview_in_language("English", h, s, q),
[chatbot, system_prompt, questions_input],
[chatbot, system_prompt]
)
lang_spanish.click(
lambda h, s, q: start_interview_in_language("Español (México)", h, s, q),
[chatbot, system_prompt, questions_input],
[chatbot, system_prompt]
)
lang_french.click(
lambda h, s, q: start_interview_in_language("Français", h, s, q),
[chatbot, system_prompt, questions_input],
[chatbot, system_prompt]
)
lang_creole.click(
lambda h, s, q: start_interview_in_language("Kreyòl Ayisyen", h, s, q),
[chatbot, system_prompt, questions_input],
[chatbot, system_prompt]
)
def respond(
message,
history: list[dict[str, str]],
system_message,
max_tokens,
temperature,
top_p,
hf_token: Optional[gr.OAuthToken] = None,
):
"""
For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
"""
# Use user's OAuth token if available, otherwise use the HF_TOKEN from environment (for shared access)
token = hf_token.token if hf_token else os.getenv("HF_TOKEN")
client = InferenceClient(token=token, model="CohereForAI/aya-expanse-32b")
# Build messages list with system message
messages = [{"role": "system", "content": system_message}]
# Add history
messages.extend(history)
# Add current user message
messages.append({"role": "user", "content": message})
response = ""
try:
# Use client.chat.completions.create() method (OpenAI-style API)
result = client.chat.completions.create(
model="CohereForAI/aya-expanse-32b",
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
)
# Extract response
if hasattr(result, 'choices') and len(result.choices) > 0:
response = result.choices[0].message.content
elif isinstance(result, dict):
if 'choices' in result and len(result['choices']) > 0:
response = result['choices'][0]['message']['content']
elif 'generated_text' in result:
response = result['generated_text']
else:
response = str(result)
yield response
except Exception as e:
error_message = f"Error: {str(e)}. Please try again or contact support if the issue persists."
yield error_message
def generate_auto_response(
history: list[dict[str, str]],
max_tokens,
temperature,
top_p,
hf_token: Optional[gr.OAuthToken] = None,
):
"""
Generates an automatic candidate response based on the interviewer's last question.
"""
if not history or len(history) == 0:
return "I'm ready to start the interview. Please go ahead with your first question."
# Get the last assistant message (interviewer's question)
last_message = history[-1] if history else None
if not last_message or last_message.get("role") != "assistant":
return "Thank you for your question. I'm happy to answer."
# Use user's OAuth token if available, otherwise use the HF_TOKEN from environment (for shared access)
token = hf_token.token if hf_token else os.getenv("HF_TOKEN")
client = InferenceClient(token=token, model="CohereForAI/aya-expanse-32b")
# Build messages with system prompt for candidate
messages = [{"role": "system", "content": candidate_system_prompt}]
# Swap roles: interviewer's assistant messages become user messages for the candidate
for msg in history:
role = msg.get("role", "")
content = msg.get("content", "")
if role == "assistant":
# Interviewer's questions become user messages
messages.append({"role": "user", "content": content})
elif role == "user":
# Candidate's responses become assistant messages
messages.append({"role": "assistant", "content": content})
# Generate response
try:
# Use client.chat.completions.create() method (OpenAI-style API)
result = client.chat.completions.create(
model="CohereForAI/aya-expanse-32b",
messages=messages,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
)
# Extract response
if hasattr(result, 'choices') and len(result.choices) > 0:
response = result.choices[0].message.content
elif isinstance(result, dict):
if 'choices' in result and len(result['choices']) > 0:
response = result['choices'][0]['message']['content']
elif 'generated_text' in result:
response = result['generated_text']
else:
response = str(result)
return response.strip() if response else "I'm ready to answer your questions."
except Exception as e:
return f"Error: {str(e)}. Please try again or contact support if the issue persists."
if __name__ == "__main__":
demo.launch()
|