import json from utils import GroqClient class QuestionGeneratorAgent: def __init__(self, api_key): self.client = GroqClient(api_key) def generate(self, query, context=""): system_prompt = """You are designing a semi-structured interview protocol based on the Empathy Map framework (Dave Gray, XPLANE) and Jobs-to-be-Done theory (Clayton Christensen). OBJECTIVE: Generate 5-7 interview questions following evidence-based customer research methodologies. THEORETICAL FRAMEWORK: Your questions must cover the Empathy Map dimensions: 1. DO: Observable behaviors and actions (behavioral data) 2. SAY: Verbal expressions and statements (self-reported data) 3. THINK: Cognitive processes and beliefs 4. FEEL: Emotional responses and reactions 5. SEE: Environmental observations and marketplace stimuli 6. HEAR: External influences and social proof 7. PAINS: Obstacles, frustrations, risks (Jobs-to-be-Done: negative jobs) 8. GAINS: Desired outcomes, benefits, aspirations (Jobs-to-be-Done: positive jobs) QUESTION DESIGN PRINCIPLES (based on "The Mom Test" - Rob Fitzpatrick): ✓ Ask about past behavior, not future intentions Example: "Tell me about the last time you..." NOT "Would you ever...?" ✓ Ask about specific instances, not generalities Example: "Walk me through your most recent experience with..." NOT "What do you usually do...?" ✓ Focus on their life and context, not your assumptions Example: "How do you currently solve [problem]?" NOT "Would this solution work for you?" ✓ Listen for problems and contexts, don't pitch or lead Example: "What's challenging about [process]?" NOT "Don't you think [X] is hard?" QUESTION REQUIREMENTS: - Open-ended (cannot be answered yes/no) - Behaviorally anchored (ask about actual experiences) - Non-leading (don't suggest answers) - Contextual (probe the situation and environment) - Specific (ask for concrete examples, not opinions) DISTRIBUTION ACROSS EMPATHY MAP: - SEE: 1 question (external observations, market stimuli) - SAY: 1 question (how they describe the problem/need to others) - DO: 1-2 questions (actual behaviors, current solutions, workarounds) - HEAR: 1 question (influences, information sources, social proof) - THINK & FEEL: 2-3 questions (pains = obstacles/frustrations, gains = desired outcomes/benefits) Return ONLY valid JSON: { "questions": [ {"id": 1, "section": "do", "question": "Walk me through the last time you [relevant action]. What did you do step by step?"}, {"id": 2, "section": "see", "question": "When you [context], what information or options do you pay attention to?"}, {"id": 3, "section": "say", "question": "How do you describe [this need/problem] when talking to [relevant person]?"}, {"id": 4, "section": "hear", "question": "Where do you currently get information or advice about [topic]?"}, {"id": 5, "section": "think & feel", "question": "What's the most frustrating part of [current process/situation]?"}, {"id": 6, "section": "think & feel", "question": "If you could wave a magic wand and change one thing about [situation], what would it be and why?"}, {"id": 7, "section": "think & feel", "question": "Tell me about a time when [relevant success]. What made that experience good?"} ] } VALIDATION CHECKLIST: - Each question asks about PAST behavior or CURRENT situation (not hypotheticals) - Questions are specific to the context provided - No yes/no questions - No leading or biased questions - Questions probe for concrete examples and stories""" if context: user_message = f"Customer Segment: {query}\n\nAdditional Context: {context}\n\nGenerate interview questions following the framework above." else: user_message = f"Customer Segment: {query}\n\nGenerate interview questions following the framework above." response = self.client.chat_completion( messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_message} ], temperature=0.7, max_tokens=2048 ) response_text = response['choices'][0]['message']['content'].strip() # Clean response if response_text.startswith("```"): response_text = response_text.split("```")[1] if response_text.startswith("json"): response_text = response_text[4:] response_text = response_text.strip() return json.loads(response_text) class SynthesisAgent: def __init__(self, api_key): self.client = GroqClient(api_key) def aggregate_interviews(self, all_interviews): """ Aggregate multiple interviews using thematic analysis """ total_interviews = len(all_interviews) if total_interviews == 0: return {"error": "No interviews to analyze"} # Build interviews text interviews_text = "" for i, interview in enumerate(all_interviews, 1): interviews_text += f"\n=== INTERVIEW {i} ===\n" for item in interview: interviews_text += f"Q: {item['q']}\nA: {item['a']}\n" interviews_text += "\n" system_prompt = f"""You are a qualitative researcher conducting thematic analysis on customer interview data to populate an Empathy Map. METHODOLOGY: You will apply systematic qualitative coding following these steps: 1. Open Coding: Identify all themes mentioned in interviews 2. Axial Coding: Group similar themes into categories 3. Pattern Recognition: Calculate frequency and strength of themes 4. Triangulation: Cross-validate insights across multiple respondents 5. Synthesis: Create actionable empathy map with evidence DATA: {total_interviews} complete customer interviews {interviews_text} ANALYTICAL FRAMEWORK (Empathy Map - Dave Gray): WHO: Customer segment profile based on: - Demographics (if mentioned) - Behaviors (observed patterns) - Context (situation they're in) - Role (their position in the ecosystem) THINK & FEEL (Internal): - PAINS: Obstacles, fears, frustrations, risks, barriers - GAINS: Desires, aspirations, hoped-for outcomes, success criteria DO (Observable Actions): - Current behaviors - Workarounds and solutions they use today - Decision-making process - Actions taken SAY (Verbal): - How they articulate needs - Language they use - Statements they make to others SEE (External Observations): - Market stimuli - Competitive landscape awareness - Information sources they notice HEAR (External Influences): - Advice from others - Social proof - Information channels - Influencers CODING RULES: 1. Code inductively from data (bottom-up), don't impose preconceptions 2. A theme must appear in at least 1 interview to be valid 3. Quote verbatim - never paraphrase or interpret beyond data 4. Note frequency (count) but also strength (emphasis in interviews) 5. Identify majority patterns AND significant minority perspectives 6. Distinguish stated preferences vs revealed preferences (say vs do) INSIGHT QUALITY STANDARDS: - Specific and actionable (not vague generalities) - Supported by evidence (quotes) - Behaviorally grounded (what they actually do, not what they say they do) - Contextual (includes situational factors) OUTPUT FORMAT: Return ONLY valid JSON: {{ "total_interviews": {total_interviews}, "who": {{ "description": "Evidence-based description: who they are, their context, their role (2-3 sentences, data-driven)", "insights": [ {{ "text": "Specific characteristic or behavioral pattern observed", "count": 3, "percentage": 60, "quotes": ["Exact quote 1", "Exact quote 2"] }} ] }}, "goal": {{ "main_goal": "The primary job-to-be-done or outcome they seek to achieve", "insights": [ {{ "text": "Specific sub-goal, success criterion, or decision driver", "count": 4, "percentage": 80, "quotes": ["Quote"] }} ] }}, "see": {{ "summary": "Overview: What they observe in their environment", "insights": [ {{ "text": "Specific market stimulus, information source, or observation", "count": 5, "percentage": 100, "quotes": ["Quote"] }} ] }}, "say": {{ "summary": "Overview: How they verbally express their needs", "insights": [ {{ "text": "Specific language, phrase, or way they describe the situation", "count": 2, "percentage": 40, "quotes": ["Quote"] }} ] }}, "do": {{ "summary": "Overview: Their current behaviors and actions", "insights": [ {{ "text": "Specific behavior, workaround, or action they currently take", "count": 4, "percentage": 80, "quotes": ["Quote"] }} ] }}, "hear": {{ "summary": "Overview: External influences on their decisions", "insights": [ {{ "text": "Specific source of advice, social proof, or external influence", "count": 3, "percentage": 60, "quotes": ["Quote"] }} ] }}, "think_feel": {{ "pains": [ {{ "text": "Specific pain point: obstacle, frustration, fear, or risk", "count": 5, "percentage": 100, "quotes": ["Quote"] }} ], "gains": [ {{ "text": "Specific desired gain: aspiration, benefit, or success criterion", "count": 4, "percentage": 80, "quotes": ["Quote"] }} ] }} }} CRITICAL REQUIREMENTS: - Base all insights on actual interview data only - Quotes must be verbatim (exact words from respondents) - Calculate percentage accurately: (count / {total_interviews}) * 100 - No speculation or inference beyond the data - If respondents contradict each other, report both perspectives""" response = self.client.chat_completion( messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": "Analyze the interviews using systematic thematic coding. Return ONLY the JSON."} ], temperature=0.6, max_tokens=4096 ) response_text = response['choices'][0]['message']['content'].strip() print(f"DEBUG - Raw response length: {len(response_text)}") # Clean up response if response_text.startswith("```"): lines = response_text.split("\n") lines = lines[1:] if lines and lines[-1].strip() == "```": lines = lines[:-1] response_text = "\n".join(lines).strip() if "{" in response_text: start_idx = response_text.index("{") response_text = response_text[start_idx:] if "}" in response_text: end_idx = response_text.rindex("}") response_text = response_text[:end_idx+1] try: parsed = json.loads(response_text) print("DEBUG - JSON parsed successfully!") return parsed except json.JSONDecodeError as e: print(f"DEBUG - JSON parse error: {e}") return { "error": "Failed to parse JSON from AI response", "json_error": str(e), "raw_response_preview": response_text[:500] }