File size: 9,582 Bytes
233222c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
import json
from typing import List, Tuple, Optional, Dict
from langchain_core.prompts import PromptTemplate, ChatPromptTemplate
from langchain_core.messages import SystemMessage, HumanMessage

from .core import get_llm, llm

def infer_purpose(state: dict, user_response: str, llm=None) -> str:
    """Use LLM to infer the purpose of the event."""
    if llm is None:
        llm = get_llm()
    subcategory = state["hackathon_details"].get("drillSubCategory", "").upper()
    prompt = f"""
    Based on the drill subcategory '{subcategory}' and the user input: '{user_response}',
    determine the most likely purpose of the event.
    The possible purposes are 'Innovation' or 'Hiring'.
    If the input strongly suggests one of these purposes, return it.
    Otherwise, default to 'Innovation'.
    """
    prompt_template = ChatPromptTemplate.from_messages([
        ("system", prompt),
        ("human", "Provide the inferred purpose.")
    ])
    response = (prompt_template | llm).invoke({})
    inferred_purpose = response.content.strip().capitalize()
    return inferred_purpose if inferred_purpose in ["Innovation", "Hiring"] else "Innovation"

def infer_drill_type(user_response: str, llm=None) -> str:
    """Use LLM to infer the drill type as 'Theme Based' or 'Problem Based'."""
    if llm is None:
        llm = get_llm()

    prompt = f"""
    Based on the user input: '{user_response}', determine whether the drill type should be 'Theme Based' or 'Problem Based'.
    
    - If the input contains keywords like 'theme', 'topic', or 'thematic', infer 'Theme Based'.
    - If the input contains words like 'problem', 'challenge', or 'issue', infer 'Problem Based'.
    - If it's unclear, default to 'Problem Based'.
    
    Respond with only 'Theme Based' or 'Problem Based'.
    """

    response = llm.invoke([SystemMessage(content=prompt), HumanMessage(content="Infer the drill type.")])
    inferred_drill_type = response.content.strip()

    return inferred_drill_type if inferred_drill_type in ["Theme Based", "Problem Based"] else "Problem Based"

def infer_subcategory(user_response: str, category_subcategory_map: dict, llm=None) -> str:
    """Use LLM to infer the most relevant subcategory."""
    if llm is None:
        llm = get_llm()
    valid_subcategories = list(category_subcategory_map.keys())
    prompt = f"""
    Given the user input: '{user_response}', determine the most relevant subcategory from the following list:
    {valid_subcategories}.
    If no clear match is found, return an empty string.
    """
    prompt_template = ChatPromptTemplate.from_messages([
        ("system", prompt),
        ("human", "Provide the inferred subcategory.")
    ])
    response = (prompt_template | llm).invoke({})
    inferred_subcategory = response.content.strip().upper()
    return inferred_subcategory if inferred_subcategory in category_subcategory_map else ""

def infer_yes_no(user_response: str, llm=None) -> str:
    """Use LLM to infer whether the user's response is 'Yes' or 'No'."""
    if llm is None:
        llm = get_llm()
    prompt = f"""
    Given the user input: '{user_response}', determine whether the response indicates 'Yes' or 'No'.
    Return 'Yes' if the input strongly suggests affirmation, otherwise return 'No'.
    """
    prompt_template = ChatPromptTemplate.from_messages([
        ("system", prompt),
        ("human", "Provide the inferred response.")
    ])
    response = (prompt_template | llm).invoke({})
    inferred_response = response.content.strip().capitalize()
    return inferred_response if inferred_response in ["Yes", "No"] else "No"

def infer_user_uncertainty(user_input: str, llm=None) -> bool:
    """Detect if user is uncertain about naming their event."""
    if llm is None:
        llm = get_llm()
    prompt = f"""
    Analyze this user input for signs of uncertainty about naming: "{user_input}"
    
    Look for:
    1. Direct expressions ("I'm not sure", "I don't know")
    2. Questions ("what should I name it?", "can you help?")
    3. Hesitation ("maybe", "possibly")
    4. Requests for suggestions
    5. General uncertainty
    
    Return ONLY "True" if uncertain, "False" if confident.
    """
    
    response = llm.invoke([
        SystemMessage(content=prompt),
        HumanMessage(content="Is the user uncertain about naming?")
    ])
    return response.content.strip().lower() == "true"

def infer_eligibility(user_response: str, llm=None) -> List[str]:
    """Infer which categories of participants are eligible for an event."""
    if llm is None:
        llm = get_llm()
    
    valid_categories = ["Graduate", "Working Professionals", "College Students"]
    
    user_response_lower = user_response.lower().strip()
    
    if any(term in user_response_lower for term in ["all", "everyone", "anybody", "anyone"]):
        return valid_categories
    
    matched_categories = []
    
    if "graduate" in user_response_lower or "graduates" in user_response_lower:
        matched_categories.append("Graduate")
        
    if "college" in user_response_lower or "students" in user_response_lower:
        matched_categories.append("College Students")
        
    if "working" in user_response_lower or "professional" in user_response_lower or "professionals" in user_response_lower:
        matched_categories.append("Working Professionals")
    
    if matched_categories:
        return matched_categories
    
    prompt = ChatPromptTemplate.from_messages([
        ("system", """Analyze the user's response and determine which categories of participants are eligible for an event.
        
        Valid categories:
        - Graduate
        - College Students
        - Working Professionals
        
        Instructions:
        1. Return ONLY the valid categories that match the user's response
        2. Be specific - only include categories that are clearly mentioned or implied
        3. If the user mentions "students" without further specification, interpret as "College Students"
        4. If the user mentions "professionals" or "working people", interpret as "Working Professionals"
        5. If the user mentions "graduates", interpret as "Graduate"
        6. If the intent is unclear, return the most likely category based on the response
        7. Return the result as a JSON array with exact category names as shown above
        
        Examples:
        - "Students and professionals" → ["College Students", "Working Professionals"]
        - "Only graduates" → ["Graduate"]
        - "Anyone with a degree" → ["Graduate", "Working Professionals"]
        - "Students in college" → ["College Students"]
        """), 
        ("human", user_response)
    ])
    
    try:
        response = (prompt | llm).invoke({})
        
        if response is None or not hasattr(response, 'content') or not response.content:
            print("LLM returned null or empty response")
            return ["College Students"]
            
        content = response.content.strip()
        
        if not content:
            print("LLM returned empty content")
            return ["College Students"]
        
        categories = []
        try:
            if "[" in content and "]" in content:
                start = content.find("[")
                end = content.rfind("]") + 1
                json_str = content[start:end]
                parsed_content = json.loads(json_str)
                if parsed_content is None:
                    return ["College Students"]
                categories = parsed_content
            else:
                parsed_content = json.loads(content)
                if parsed_content is None:
                    return ["College Students"]
                categories = parsed_content
        except json.JSONDecodeError:
            cleaned = content.replace("The eligible categories are:", "")
            cleaned = cleaned.replace("Based on the response, the eligible categories are:", "")
            if "," in cleaned:
                categories = [cat.strip() for cat in cleaned.split(",")]
            elif "\n" in cleaned:
                categories = [cat.strip() for cat in cleaned.split("\n") if cat.strip()]
            else:
                categories = [cleaned.strip()]
        
        if not categories:
            print("Failed to extract categories from LLM response")
            return ["College Students"]
        
        validated_categories = []
        for cat in categories:
            if cat is None or not isinstance(cat, str) or not cat.strip():
                continue
                
            matches = [valid for valid in valid_categories if valid.lower() == cat.lower()]
            if matches:
                validated_categories.append(matches[0])
            elif "college" in cat.lower() or "student" in cat.lower():
                if "College Students" not in validated_categories:
                    validated_categories.append("College Students")
            elif "work" in cat.lower() or "professional" in cat.lower():
                if "Working Professionals" not in validated_categories:
                    validated_categories.append("Working Professionals")
            elif "grad" in cat.lower():
                if "Graduate" not in validated_categories:
                    validated_categories.append("Graduate")
        
        return validated_categories if validated_categories else ["College Students"]

    except Exception as e:
        print(f"Error in infer_eligibility: {str(e)}")
        return ["College Students"]