Spaces:
Build error
Build error
Update researchsimulation/InteractiveInterviewChatbot.py
Browse files
researchsimulation/InteractiveInterviewChatbot.py
CHANGED
|
@@ -1,411 +1,162 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import logging
|
| 3 |
-
import re
|
| 4 |
-
|
| 5 |
-
from RespondentAgent import *
|
| 6 |
from langchain_groq import ChatGroq
|
| 7 |
-
from
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 11 |
|
| 12 |
-
def parse_question_with_llm(question, respondent_names, processor_llm):
|
| 13 |
-
"""
|
| 14 |
-
Uses OpenAI's LLM to extract the specific agents being addressed and their respective questions.
|
| 15 |
-
Supports compound requests.
|
| 16 |
-
"""
|
| 17 |
-
logging.info(f"Parsing question with LLM: {question}")
|
| 18 |
-
|
| 19 |
-
prompt = f"""
|
| 20 |
-
You are an expert in market research interview analysis.
|
| 21 |
-
Your task is to **identify respondents** mentioned in the question and **extract the exact question** posed to them.
|
| 22 |
-
|
| 23 |
-
### User Input:
|
| 24 |
-
{question}
|
| 25 |
-
### Instructions:
|
| 26 |
-
1. Identify **each respondent being addressed**.
|
| 27 |
-
The respondents available are {respondent_names}. If these names are mistyped, then ensure that you match the names to the ones available.
|
| 28 |
-
2. Extract the **exact question** directed to each respondent with the following conditions:
|
| 29 |
-
- Remove the respondent's name(s), whether at the beginning, middle, or end of the question.
|
| 30 |
-
- Also remove any directly surrounding commas or punctuation attached to the name.
|
| 31 |
-
- Keep all other wording, punctuation, and sentence structure exactly as in the original. Do NOT rephrase or rewrite under any circumstance.
|
| 32 |
-
3. If no respondent is explicitly addressed, return "General" as the respondent name.
|
| 33 |
-
4. If the question is posed to all respondents, return "All" as the respondent name.
|
| 34 |
-
5. Rewrite the question in **British English** if necessary.
|
| 35 |
-
- Do not rephrase beyond British spelling or grammar.
|
| 36 |
-
- Do not add, remove, or change the meaning of the question.
|
| 37 |
-
- Where there are regional variations (e.g. 'licence' vs 'license', 'programme' vs 'program', 'aeroplane' vs 'airplane'), always default to the standard British form.
|
| 38 |
-
- Examples:
|
| 39 |
-
- **Correct (British):** organised, prioritise, minimise, realise, behaviour, centre, defence, travelling, practise (verb), licence (noun), programme, aeroplane.
|
| 40 |
-
- **Incorrect (American):** organized, prioritize, minimize, realize, behavior, center, defense, traveling, practice (verb and noun), license (noun), program, airplane.
|
| 41 |
-
6. Ensure that you follow the **Formatting Rules** exactly. THIS IS EXTREMELY IMPORTANT.
|
| 42 |
-
|
| 43 |
-
### Examples:
|
| 44 |
-
- "Sourav, do you agree with this topic?" β "Do you agree with this topic?"
|
| 45 |
-
- "What do you think about this topic, Divya?" β "What do you think about this topic?"
|
| 46 |
-
- "Do you believe, Rahul, that this is correct?" β "Do you believe that this is correct?"
|
| 47 |
-
- "What do you think, Divya, about this topic?" β "What do you think about this topic?"
|
| 48 |
-
- "Do you, Rahul, agree with this statement?" β "Do you agree with this statement?"
|
| 49 |
-
- "Are you, Sourav, going to do this?" β "Are you going to do this?"
|
| 50 |
-
- "What is your favorite color, Meena?" β "What is your favourite colour?"
|
| 51 |
-
- "Divya, what did you learn from this program?" β "What did you learn from this programme?"
|
| 52 |
-
- "How do you stay organized, Rahul?" β "How do you stay organised?"
|
| 53 |
-
- "Meena, how do you balance work and traveling?" β "How do you balance work and travelling?"
|
| 54 |
-
|
| 55 |
-
### **Formatting Rules**:
|
| 56 |
-
For each question identified, respond using **only** the following format:
|
| 57 |
-
- Respondent: <Respondent Name>
|
| 58 |
-
Question: <Extracted Question>
|
| 59 |
-
|
| 60 |
-
Only return the formatted output without explanations.
|
| 61 |
-
"""
|
| 62 |
-
|
| 63 |
-
# Invoke LangChain LLM
|
| 64 |
-
logging.info("Invoking LLM for parsing...")
|
| 65 |
-
response = processor_llm.invoke(prompt)
|
| 66 |
-
chatgpt_output = response.content.strip()
|
| 67 |
-
logging.info(f"LLM Parsed Output: {chatgpt_output}")
|
| 68 |
-
|
| 69 |
-
parsed_questions = {}
|
| 70 |
-
respondent_name = "General"
|
| 71 |
-
question_text = None
|
| 72 |
-
|
| 73 |
-
for line in chatgpt_output.split("\n"):
|
| 74 |
-
if "- Respondent:" in line:
|
| 75 |
-
respondent_name = re.sub(r"^.*Respondent:\s*", "", line).strip().capitalize()
|
| 76 |
-
elif "Question:" in line:
|
| 77 |
-
question_text = re.sub(r"^.*Question:\s*", "", line).strip()
|
| 78 |
-
if respondent_name and question_text:
|
| 79 |
-
parsed_questions[respondent_name] = question_text
|
| 80 |
-
logging.info(f"Parsed -> Respondent: {respondent_name}, Question: {question_text}")
|
| 81 |
-
respondent_name = "General"
|
| 82 |
-
question_text = None
|
| 83 |
-
|
| 84 |
-
logging.info("Parsing complete.")
|
| 85 |
-
return parsed_questions
|
| 86 |
-
|
| 87 |
-
def validate_question_topics(parsed_questions, processor_llm):
|
| 88 |
-
"""
|
| 89 |
-
Validates each question to ensure it's within the permitted topic scope.
|
| 90 |
-
Converts question to British English spelling if valid.
|
| 91 |
-
Returns 'INVALID' for any out-of-scope question.
|
| 92 |
-
"""
|
| 93 |
-
logging.info("Validating question topics and converting to British English...")
|
| 94 |
-
validated_questions = {}
|
| 95 |
|
| 96 |
-
for respondent, question in parsed_questions.items():
|
| 97 |
-
logging.info(f"Validating question for {respondent}: {question}")
|
| 98 |
-
prompt = f"""
|
| 99 |
-
You are a senior research analyst. Your job is to **validate** whether a market research question is within the allowed topic scope and convert it to **British English** spelling, grammar, and phrasing.
|
| 100 |
-
### Question:
|
| 101 |
-
{question}
|
| 102 |
-
### Permitted Topics Scope:
|
| 103 |
-
The respondents may only answer questions related to the following general topics:
|
| 104 |
-
|
| 105 |
-
- Demographics: Age, location, education, family background, life events.
|
| 106 |
-
- Values & Beliefs: Family responsibility, independence, hard work, gender equality, spirituality, simplicity, mental health, traditional vs modern values.
|
| 107 |
-
- Career & Aspirations: Education, career goals, entrepreneurship, financial independence, stability, ambition, and personal development.
|
| 108 |
-
- Influences & Role Models: Family members, mentors, public figures, influencers.
|
| 109 |
-
- Interests & Hobbies: Sports, music, fitness, cooking, creative arts, gaming, travel, entertainment content, podcasts, leisure.
|
| 110 |
-
- Health & Lifestyle: Physical health, fitness, diet, skincare, self-care, mental wellbeing, lifestyle balance.
|
| 111 |
-
- Social Media & Technology: Social media usage, digital content, influencer interests, technology habits.
|
| 112 |
-
- Personal Relationships: Family, friends, romantic relationships, support systems, social circles.
|
| 113 |
-
- Future Outlook: Career plans, financial security, personal growth, family goals, confidence building.
|
| 114 |
-
- Social & Societal Issues: Gender equality, societal expectations, economic issues, tradition vs freedom, social development.
|
| 115 |
-
- Lifestyle Preferences: Food preferences, fashion, routines, spending habits, religious or cultural practices.
|
| 116 |
-
- Personal Growth & Development: Maturity, emotional regulation, responsibility, adaptability, self-improvement, learning mindset.
|
| 117 |
-
|
| 118 |
-
### Validation Instructions:
|
| 119 |
-
You must determine if the question is appropriate for a lifestyle, values, and personal development interview.
|
| 120 |
-
|
| 121 |
-
1. **Topical Relevance**
|
| 122 |
-
- Accept the question only if it is **clearly relevant** to the Permitted Topics Scope and can be answered from a **personal, lifestyle, or values-based perspective**.
|
| 123 |
-
|
| 124 |
-
2. **Content Restrictions**
|
| 125 |
-
Return exactly "INVALID" if the question contains any of the following:
|
| 126 |
-
- Hate speech, discrimination, harassment
|
| 127 |
-
- Sexually explicit, violent, or graphic content
|
| 128 |
-
- Religious extremism or proselytising
|
| 129 |
-
- Politically sensitive content:
|
| 130 |
-
- Opinions or knowledge about politicians or political parties
|
| 131 |
-
- Policy debates, election-related topics, or partisan comparisons
|
| 132 |
-
- References to extremist ideologies or hate groups
|
| 133 |
-
- Overly technical, academic, or scientific content not grounded in personal lifestyle (e.g. biology, physics, finance, geopolitics)
|
| 134 |
-
- News-related or controversial current events
|
| 135 |
-
|
| 136 |
-
3. **Everyday Relevance**
|
| 137 |
-
- Even if the topic superficially fits the scope, it must be **personally relatable, non-controversial**, and answerable by someone with the respondent's **general life experience**, not specialised knowledge.
|
| 138 |
-
|
| 139 |
-
4. **Output Instructions**
|
| 140 |
-
- If invalid, return exactly: "INVALID"
|
| 141 |
-
- If valid, return the **same question**
|
| 142 |
-
|
| 143 |
-
### Output:
|
| 144 |
-
<Validated question OR "INVALID">
|
| 145 |
-
"""
|
| 146 |
-
|
| 147 |
-
# ### Validation Instructions:
|
| 148 |
-
# - Judge based on **intent** and **relevance**.
|
| 149 |
-
# - Accept the question if it is **clearly relevant to the permitted topics** and something the respondent could **reasonably be expected to answer or reflect on**.
|
| 150 |
-
# - Be cautious with speculative or technical questions (e.g. cryptocurrency, political policies) β only allow if they're framed in a **personal or lifestyle** context that the respondent could discuss.
|
| 151 |
-
# - If a question is **clearly unrelated**, overly technical, or beyond the respondent's likely knowledge or experience, respond with exactly: "INVALID".
|
| 152 |
-
# - If valid, return the **same question**, rewritten in **British English** if necessary.
|
| 153 |
-
# - Do not add any new content or change the meaning β only apply British spelling, grammar, and phrasing.
|
| 154 |
-
# ### Output:
|
| 155 |
-
# <Validated question, or "INVALID">
|
| 156 |
-
|
| 157 |
-
# ### Stricter Validation Instructions:
|
| 158 |
-
# - If the question is not strictly relevant to the **Permitted Topics Scope**, it is invalid. Replace the queston with exactly: "INVALID"
|
| 159 |
-
# - If valid, return the **same question**, rewritten in **British English** if necessary.
|
| 160 |
-
# - Strictly do not add to the question other than rewriting to **British English**.
|
| 161 |
-
# ### Output:
|
| 162 |
-
# <Validated question in British English, or "INVALID">
|
| 163 |
-
|
| 164 |
-
response = processor_llm.invoke(prompt)
|
| 165 |
-
validated_output = response.content.strip()
|
| 166 |
-
logging.info(f"Validated output for {respondent}: {validated_output}")
|
| 167 |
-
validated_questions[respondent] = validated_output
|
| 168 |
-
|
| 169 |
-
logging.info("Validation complete.")
|
| 170 |
-
return validated_questions
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
def ask_interview_question(respondent_agents_dict, last_active_agent, question, processor_llm):
|
| 175 |
-
"""
|
| 176 |
-
Handles both individual and group interview questions while tracking conversation flow.
|
| 177 |
-
Uses OpenAI's LLM to extract the intended respondent(s) and their specific question(s).
|
| 178 |
-
Uses Groq's LLM for response generation.
|
| 179 |
-
"""
|
| 180 |
-
|
| 181 |
logging.info(f"Received question: {question}")
|
| 182 |
-
|
| 183 |
agent_names = list(respondent_agents_dict.keys())
|
| 184 |
-
logging.info(f"Available respondents: {agent_names}")
|
| 185 |
-
print(f"Available respondents: {agent_names}")
|
| 186 |
|
| 187 |
-
#
|
| 188 |
-
|
| 189 |
-
# Step 1: Parse question
|
| 190 |
parsed_questions = parse_question_with_llm(question, str(agent_names), processor_llm)
|
| 191 |
if not parsed_questions:
|
| 192 |
-
logging.warning("No questions were parsed from input.")
|
| 193 |
return ["**PreData Moderator**: No valid respondents were detected for this question."]
|
| 194 |
|
| 195 |
-
# Step 2: Validate question content (scope + spelling)
|
| 196 |
validated_questions = validate_question_topics(parsed_questions, processor_llm)
|
| 197 |
-
for
|
| 198 |
-
if
|
| 199 |
-
logging.warning(f"Invalid question detected for {resp_name}: {extracted_question}")
|
| 200 |
return ["**PreData Moderator**: The question is invalid. Please ask another question."]
|
| 201 |
-
|
| 202 |
-
# Use validated questions from this point on
|
| 203 |
parsed_questions = validated_questions
|
| 204 |
-
logging.info(f"Validated questions: {parsed_questions}")
|
| 205 |
-
|
| 206 |
-
if len(parsed_questions) > 1:
|
| 207 |
-
logging.warning("More than one respondent specified. Exiting function.")
|
| 208 |
-
return "**PreData Moderator**: Please ask each respondent one question at a time."
|
| 209 |
-
else:
|
| 210 |
-
print(f"Parsed questions are: {parsed_questions}")
|
| 211 |
-
|
| 212 |
-
if "General" in parsed_questions:
|
| 213 |
-
if "General" in parsed_questions:
|
| 214 |
-
if isinstance(last_active_agent, list) and all(name in agent_names for name in last_active_agent):
|
| 215 |
-
logging.info(f"General case detected. Continuing with last active agent: {last_active_agent}")
|
| 216 |
-
parsed_questions = {name: parsed_questions["General"] for name in last_active_agent}
|
| 217 |
-
else:
|
| 218 |
-
logging.info("General case detected without a valid previous active agent. Assigning question to all respondents.")
|
| 219 |
-
parsed_questions = {name: parsed_questions["General"] for name in agent_names}
|
| 220 |
-
elif "All" in parsed_questions:
|
| 221 |
-
logging.info("All case detected. Assigning question to all respondents.")
|
| 222 |
-
validated_question = parsed_questions["All"]
|
| 223 |
-
parsed_questions = {name: validated_question for name in agent_names}
|
| 224 |
|
|
|
|
|
|
|
| 225 |
|
| 226 |
last_active_agent = list(parsed_questions.keys())
|
| 227 |
-
logging.info(f"Final parsed questions: {parsed_questions}")
|
| 228 |
-
|
| 229 |
-
# Construct one crew and task for each agent and question
|
| 230 |
responses = []
|
| 231 |
|
| 232 |
for agent_name, agent_question in parsed_questions.items():
|
| 233 |
-
|
| 234 |
-
|
| 235 |
responses.append(f"**PreData Moderator**: {agent_name} is not a valid respondent.")
|
| 236 |
continue
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
### *Communication Profile Reference:*
|
| 248 |
-
- **Style:** {user_profile.get_field('Communication', 'Style')}
|
| 249 |
-
- **Tone:** {user_profile.get_field('Communication', 'Tone')}
|
| 250 |
-
- **Length:** {user_profile.get_field('Communication', 'Length')}
|
| 251 |
-
- **Topics:** {user_profile.get_field('Communication', 'Topics')}
|
| 252 |
-
---
|
| 253 |
-
---
|
| 254 |
-
### π **Hard Rules β You Must Follow These Without Exception**
|
| 255 |
-
- You must answer **only the question(s)** that are **explicitly asked**.
|
| 256 |
-
- **Never provide extra information** beyond what was asked.
|
| 257 |
-
- Keep your response **as short as possible** while still sounding natural and complete.
|
| 258 |
-
- Do **not infer or assume** what the user *might* want β only respond to what they *actually* asked.
|
| 259 |
-
- If multiple questions are asked, respond to **each one briefly**, and **nothing else**.
|
| 260 |
-
- If the question is vague, respond minimally and only within that scope.
|
| 261 |
-
-Give concise answers, whether the question is asked to the group or individually.
|
| 262 |
-
-For factual or demographic questions (e.g., age, gender, location, housing), keep responses brief and to the point, without extra commentary.
|
| 263 |
-
-Do not add any explanations, opinions, or additional information.
|
| 264 |
-
-Use simple, clear sentences.
|
| 265 |
-
-Example:
|
| 266 |
-
Q: Where are you from?
|
| 267 |
-
A: Iβm from [city], [country](DO NOT ADD ANY EXTRA COMMENTS).
|
| 268 |
-
-For reflective or opinion-based questions (e.g., feelings, preferences, motivations), provide thoughtful but still clear and focused answers.
|
| 269 |
-
-Never repeat the question or add unrelated background information.
|
| 270 |
-
---
|
| 271 |
-
### **How to Answer:**
|
| 272 |
-
- Your response should be **natural, authentic, and fully aligned** with the specified style and tone.
|
| 273 |
-
- Ensure the answer is **clear, engaging, and directly relevant** to the question.
|
| 274 |
-
- Adapt your **sentence structure, phrasing, and word choices** to match the intended communication style.
|
| 275 |
-
- If applicable, incorporate **culturally relevant expressions, regional nuances, or industry-specific terminology** that fit the given tone.
|
| 276 |
-
- **Adjust response length** based on the toneβ**concise and direct** for casual styles, **structured and detailed** for professional styles.
|
| 277 |
-
- **Always answer in first person ("I", "my", "me", "mine", etc.) as if you are personally responding to the question. You are an individual representing yourself, not speaking in third person.**
|
| 278 |
-
-Always answer as if you are the individual being directly spoken to. Use first-person language such as βI,β βme,β βmy,β and βmineβ in every response. Imagine you are having a real conversation β your tone should feel natural, personal, and authentic. Do not refer to yourself in the third person (e.g., βShe is from Trichyβ or βMeena likesβ¦β). Avoid describing yourself as if someone else is talking about you.
|
| 279 |
-
-Everything you say should come from your own perspective, just like you would in everyday speech. The goal is to sound human, relatable, and direct β like you're truly present in the conversation.
|
| 280 |
-
---
|
| 281 |
-
### **Guidelines for Ensuring Authenticity & Alignment:**
|
| 282 |
-
- **Consistency**: Maintain the same tone throughout the response.
|
| 283 |
-
- **Authenticity**: The response should feel natural and match the speakerβs persona.
|
| 284 |
-
- **Avoid Overgeneralisation**: Ensure responses are specific and not overly generic or robotic.
|
| 285 |
-
- **Cultural & Linguistic Relevance**: Adapt language and references to match the speakerβs background, industry, or region where appropriate.
|
| 286 |
-
- **Strict British Spelling & Grammar**:
|
| 287 |
-
- All responses must use correct British English spelling, grammar, and usage, **irrespective of how the question is phrased**.
|
| 288 |
-
- You must not mirror any American spelling, terminology, or phrasing found in the input question.
|
| 289 |
-
- Where there are regional variations (e.g. 'licence' vs 'license', 'programme' vs 'program', 'aeroplane' vs 'airplane'), always default to the standard British form.
|
| 290 |
-
- Examples:
|
| 291 |
-
- **Correct (British):** organised, prioritise, minimise, realise, behaviour, centre, defence, travelling, practise (verb), licence (noun), programme, aeroplane.
|
| 292 |
-
- **Incorrect (American):** organized, prioritize, minimize, realize, behavior, center, defense, traveling, practice (verb and noun), license (noun), program, airplane.
|
| 293 |
-
- **Formatting**:
|
| 294 |
-
- If the tone is informal, allow a conversational flow that mirrors natural speech.
|
| 295 |
-
- If the tone is formal, use a structured and professional format.
|
| 296 |
-
- **Do not include emojis or hashtags in the response.**
|
| 297 |
-
- Maintain **narrative and thematic consistency** across all answers to simulate a coherent personality.
|
| 298 |
-
-**Personality Profile Alignment:**
|
| 299 |
-
-Consider your assigned personality traits across these dimensions:
|
| 300 |
-
-Big Five Traits:
|
| 301 |
-
-Openness: Reflect your level of curiosity, creativity, and openness to new experiences
|
| 302 |
-
-Conscientiousness: Show your degree of organization, responsibility, and planning
|
| 303 |
-
-Extraversion: Express your sociability and energy level in interactions
|
| 304 |
-
-Agreeableness: Demonstrate your warmth, cooperation, and consideration for others
|
| 305 |
-
-Neuroticism: Consider your emotional stability and stress response
|
| 306 |
-
-Values and Priorities:
|
| 307 |
-
-Achievement Orientation: Show your drive for success and goal-setting approach
|
| 308 |
-
-Risk Tolerance: Express your comfort with uncertainty and change
|
| 309 |
-
-Traditional Values: Reflect your adherence to conventional norms and practices
|
| 310 |
-
-Communication Style:
|
| 311 |
-
-Detail Orientation: Demonstrate your preference for specific vs. general information
|
| 312 |
-
-Complexity: Show your comfort with nuanced vs. straightforward explanations
|
| 313 |
-
-Directness: Express your communication as either straightforward or diplomatic
|
| 314 |
-
-Emotional Expressiveness: Reflect your tendency to share or withhold emotions
|
| 315 |
-
-Your responses must consistently align with these personality traits from your profile.
|
| 316 |
-
---
|
| 317 |
-
### **Example Responses (for Different Styles & Tones)**
|
| 318 |
-
#### **Casual & Conversational Tone**
|
| 319 |
-
**Question:** "How do you stay updated on the latest fashion and tech trends?"
|
| 320 |
-
**Correct Response:**
|
| 321 |
-
"I keep up with trends by following influencers on Instagram and watching product reviews on YouTube. Brands like Noise and Boat always drop stylish, affordable options, so I make sure to stay ahead of the curve."
|
| 322 |
-
#### **Formal & Professional Tone**
|
| 323 |
-
**Question:** "How do you stay updated on the latest fashion and tech trends?"
|
| 324 |
-
**Correct Response:**
|
| 325 |
-
"I actively follow industry trends by reading reports, attending webinars, and engaging with thought leaders on LinkedIn. I also keep up with global fashion and technology updates through leading publications such as *The Business of Fashion* and *TechCrunch*."
|
| 326 |
-
---
|
| 327 |
-
Your final answer should be **a well-structured response that directly answers the question while maintaining the specified style and tone**:
|
| 328 |
-
**"{agent_question}"**
|
| 329 |
-
"""
|
| 330 |
-
|
| 331 |
-
question_task_expected_output = f"""
|
| 332 |
-
A culturally authentic and conversational response to the question: '{agent_question}'.
|
| 333 |
-
- The response must reflect the respondent's **local cultural background and geographic influences**, ensuring it aligns with their **speech patterns, preferences, and linguistic style**.
|
| 334 |
-
- The language must follow **strict British English spelling conventions**, ensuring it is **natural, personal, and free-flowing**, while strictly avoiding American spelling, phrasing, or grammar under any circumstances, regardless of the spelling, grammar, or vocabulary used in the input question.
|
| 335 |
-
- The response **must not introduce the respondent**, nor include placeholders like "[Your Name]" or "[Brand Name]".
|
| 336 |
-
- The response **must always be written in first person ("I", "my", "me", etc.) as if the respondent is personally answering the question directly. Third-person narration is never allowed.**
|
| 337 |
-
- The final output should be a **single, well-structured paragraph that directly answers the question** while staying fully aligned with the specified communication style.
|
| 338 |
-
"""
|
| 339 |
-
|
| 340 |
-
question_task = Task(
|
| 341 |
-
description=question_task_description,
|
| 342 |
-
expected_output=question_task_expected_output,
|
| 343 |
-
agent=respondent_agent
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
logging.debug(f"Created task for agent '{agent_name}' with description: {question_task_description}")
|
| 347 |
-
|
| 348 |
-
# Log before starting task execution
|
| 349 |
-
logging.info(f"Executing task for agent '{agent_name}'")
|
| 350 |
-
|
| 351 |
-
# Create a new crew for each agent-question pair
|
| 352 |
-
crew = Crew(
|
| 353 |
-
agents=[respondent_agent],
|
| 354 |
-
tasks=[question_task],
|
| 355 |
-
process=Process.sequential
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
|
|
|
|
|
|
|
|
|
| 2 |
from langchain_groq import ChatGroq
|
| 3 |
+
from RespondentAgent import *
|
| 4 |
+
from validation_utils import *
|
| 5 |
+
from crewai import Crew, Task, Process
|
| 6 |
|
| 7 |
+
# === Setup Logging ===
|
| 8 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def ask_interview_question(respondent_agents_dict, last_active_agent, question, processor_llm):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
logging.info(f"Received question: {question}")
|
|
|
|
| 13 |
agent_names = list(respondent_agents_dict.keys())
|
|
|
|
|
|
|
| 14 |
|
| 15 |
+
# Step 1: Parse and validate questions
|
|
|
|
|
|
|
| 16 |
parsed_questions = parse_question_with_llm(question, str(agent_names), processor_llm)
|
| 17 |
if not parsed_questions:
|
|
|
|
| 18 |
return ["**PreData Moderator**: No valid respondents were detected for this question."]
|
| 19 |
|
|
|
|
| 20 |
validated_questions = validate_question_topics(parsed_questions, processor_llm)
|
| 21 |
+
for resp, q in validated_questions.items():
|
| 22 |
+
if q == "INVALID":
|
|
|
|
| 23 |
return ["**PreData Moderator**: The question is invalid. Please ask another question."]
|
|
|
|
|
|
|
| 24 |
parsed_questions = validated_questions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
if len(parsed_questions) > 1:
|
| 27 |
+
return ["**PreData Moderator**: Please ask each respondent one question at a time."]
|
| 28 |
|
| 29 |
last_active_agent = list(parsed_questions.keys())
|
|
|
|
|
|
|
|
|
|
| 30 |
responses = []
|
| 31 |
|
| 32 |
for agent_name, agent_question in parsed_questions.items():
|
| 33 |
+
agent_entry = respondent_agents_dict.get(agent_name)
|
| 34 |
+
if not agent_entry:
|
| 35 |
responses.append(f"**PreData Moderator**: {agent_name} is not a valid respondent.")
|
| 36 |
continue
|
| 37 |
|
| 38 |
+
# === Step 1: Generate raw answer ===
|
| 39 |
+
raw_answer = generate_generic_answer(agent_name, agent_question, agent_entry.get_agent())
|
| 40 |
+
|
| 41 |
+
# === Step 2: Stylise answer ===
|
| 42 |
+
styled_answer = stylise_answer_to_profile(
|
| 43 |
+
raw_answer,
|
| 44 |
+
agent_name,
|
| 45 |
+
agent_entry.get_user_profile(),
|
| 46 |
+
processor_llm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
)
|
| 48 |
+
|
| 49 |
+
# === Step 3: Final validation ===
|
| 50 |
+
if not validate_final_answer(styled_answer):
|
| 51 |
+
responses.append(f"**PreData Moderator**: The answer could not be validated.")
|
| 52 |
+
continue
|
| 53 |
+
|
| 54 |
+
responses.append(f"**{agent_name}**: {styled_answer}")
|
| 55 |
+
|
| 56 |
+
return responses
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# === STEP 1: GENERATE RAW ANSWER ===
|
| 60 |
+
def generate_generic_answer(agent_name, question, agent):
|
| 61 |
+
prompt = f"""
|
| 62 |
+
You are {agent_name}. Answer the following question naturally and authentically in first person.
|
| 63 |
+
Use British English. Do not apply any tone or formatting rules.
|
| 64 |
+
|
| 65 |
+
### Question:
|
| 66 |
+
"{question}"
|
| 67 |
+
"""
|
| 68 |
+
task = Task(description=prompt, expected_output="", agent=agent)
|
| 69 |
+
Crew(agents=[agent], tasks=[task], process=Process.sequential).kickoff()
|
| 70 |
+
return task.output.raw.strip()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# === STEP 2: STYLISE ANSWER TO PROFILE ===
|
| 74 |
+
def stylise_answer_to_profile(raw_answer, agent_name, user_profile, processor_llm):
|
| 75 |
+
communication_style = user_profile.get_field("Communication", "Style") or "conversational"
|
| 76 |
+
prompt = f"""
|
| 77 |
+
Rephrase the following response into a {communication_style} tone using British English.
|
| 78 |
+
Keep it in first person. Do not change the meaning or add new content.
|
| 79 |
+
|
| 80 |
+
### Original:
|
| 81 |
+
"{raw_answer}"
|
| 82 |
+
"""
|
| 83 |
+
response = processor_llm.invoke(prompt)
|
| 84 |
+
return response.content.strip()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# === STEP 3: FINAL OUTPUT VALIDATION ===
|
| 88 |
+
def validate_final_answer(answer):
|
| 89 |
+
return bool(answer and len(answer.split()) > 2) # Example: check it's not empty or too short
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
# === PARSE QUESTIONS WITH LLM (Your existing code or external import) ===
|
| 93 |
+
def parse_question_with_llm(question, respondent_names, processor_llm):
|
| 94 |
+
prompt = f"""
|
| 95 |
+
You are an expert in market research interview analysis.
|
| 96 |
+
Your task is to identify respondents mentioned in the question and extract the exact question posed to them.
|
| 97 |
+
|
| 98 |
+
### User Input:
|
| 99 |
+
{question}
|
| 100 |
+
|
| 101 |
+
### Instructions:
|
| 102 |
+
1. Identify each respondent being addressed.
|
| 103 |
+
2. Extract the exact question posed to them.
|
| 104 |
+
3. Use "General" if no specific name is mentioned. Use "All" if it's for everyone.
|
| 105 |
+
4. If the question is out of scope, return "INVALID" as the question.
|
| 106 |
+
|
| 107 |
+
### Format:
|
| 108 |
+
- Respondent: <Respondent Name>
|
| 109 |
+
Question: <Extracted Question>
|
| 110 |
+
"""
|
| 111 |
+
response = processor_llm.invoke(prompt)
|
| 112 |
+
chatgpt_output = response.content.strip()
|
| 113 |
+
|
| 114 |
+
parsed_questions = {}
|
| 115 |
+
lines = chatgpt_output.split("\n")
|
| 116 |
+
respondent_name = "General"
|
| 117 |
+
question_text = None
|
| 118 |
+
|
| 119 |
+
for line in lines:
|
| 120 |
+
if "- Respondent:" in line:
|
| 121 |
+
respondent_name = line.split(":")[1].strip()
|
| 122 |
+
elif "Question:" in line:
|
| 123 |
+
question_text = line.split(":")[1].strip()
|
| 124 |
+
if question_text:
|
| 125 |
+
parsed_questions[respondent_name] = question_text
|
| 126 |
+
|
| 127 |
+
return parsed_questions
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
# === VALIDATE QUESTIONS FOR TOPIC SCOPE (Your existing logic) ===
|
| 131 |
+
def validate_question_topics(parsed_questions, processor_llm):
|
| 132 |
+
validated = {}
|
| 133 |
+
for respondent, question in parsed_questions.items():
|
| 134 |
+
prompt = f"""
|
| 135 |
+
You are a research analyst. Validate whether the question is in the allowed topic scope and convert it to British English.
|
| 136 |
+
|
| 137 |
+
### Question:
|
| 138 |
+
{question}
|
| 139 |
+
|
| 140 |
+
### If invalid:
|
| 141 |
+
Return exactly "INVALID"
|
| 142 |
+
|
| 143 |
+
### Permitted Topics:
|
| 144 |
+
- Demographics
|
| 145 |
+
- Values & Beliefs
|
| 146 |
+
- Career & Aspirations
|
| 147 |
+
- Influences
|
| 148 |
+
- Interests & Hobbies
|
| 149 |
+
- Health & Lifestyle
|
| 150 |
+
- Social Media & Tech
|
| 151 |
+
- Personal Relationships
|
| 152 |
+
- Future Outlook
|
| 153 |
+
- Social & Societal Issues
|
| 154 |
+
- Lifestyle Preferences
|
| 155 |
+
- Personal Growth
|
| 156 |
+
|
| 157 |
+
### Output:
|
| 158 |
+
"""
|
| 159 |
+
result = processor_llm.invoke(prompt)
|
| 160 |
+
validated[respondent] = result.content.strip()
|
| 161 |
+
return validated
|
| 162 |
+
|