Girish Jeswani commited on
Commit
290802c
·
1 Parent(s): d8a51fd

add in-chat orchestrator

Browse files
multi_llm_chatbot_backend/app/core/seamless_orchestrator.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/core/seamless_orchestrator.py
2
+
3
+ import re
4
+ from typing import Dict, List, Optional
5
+ from app.llm.mistral_client import MistralClient
6
+
7
+ class SeamlessOrchestrator:
8
+ def __init__(self):
9
+ self.llm = MistralClient()
10
+ self.required_fields = ["research_area", "specific_question", "academic_stage"]
11
+ self.collected_info = {}
12
+ self.conversation_history = []
13
+ self.orchestrator_active = False
14
+
15
+ def is_input_complete(self) -> bool:
16
+ """Check if we have enough information to proceed to advisors"""
17
+ return all(field in self.collected_info for field in self.required_fields)
18
+
19
+ def is_input_vague(self, user_input: str) -> bool:
20
+ """Determine if the input is too vague and needs clarification"""
21
+ vague_patterns = [
22
+ r"i'm (not sure|unsure|confused|lost)",
23
+ r"i (don't know|dunno) (what|how|where)",
24
+ r"help me with (my|the|a) (thesis|research|phd)",
25
+ r"(what should i|how do i|where do i start)",
26
+ r"i need (help|advice|guidance)",
27
+ r"(stuck|struggling) with",
28
+ r"(any|some) (advice|suggestions|ideas)",
29
+ r"^(help|advice|guidance)$",
30
+ ]
31
+
32
+ user_lower = user_input.lower().strip()
33
+
34
+ # Check for vague patterns
35
+ for pattern in vague_patterns:
36
+ if re.search(pattern, user_lower):
37
+ return True
38
+
39
+ # Check if input is too short (likely vague)
40
+ if len(user_input.split()) < 8:
41
+ return True
42
+
43
+ return False
44
+
45
+ def extract_info(self, user_input: str) -> Dict[str, str]:
46
+ """Extract information from user input"""
47
+ info = {}
48
+ user_lower = user_input.lower()
49
+
50
+ # Detect research area
51
+ research_areas = {
52
+ "computer science": ["computer science", "cs", "software", "programming", "algorithms"],
53
+ "machine learning": ["machine learning", "ml", "ai", "artificial intelligence", "deep learning"],
54
+ "biology": ["biology", "molecular", "genetics", "bioinformatics"],
55
+ "chemistry": ["chemistry", "chemical", "organic chemistry"],
56
+ "physics": ["physics", "quantum", "theoretical physics"],
57
+ "mathematics": ["mathematics", "math", "statistics", "mathematical"],
58
+ "psychology": ["psychology", "cognitive", "behavioral"],
59
+ "sociology": ["sociology", "social science", "anthropology"],
60
+ "literature": ["literature", "english", "linguistics"],
61
+ "history": ["history", "historical"],
62
+ "philosophy": ["philosophy", "philosophical"],
63
+ "economics": ["economics", "economic", "finance"],
64
+ "political science": ["political science", "politics", "government"],
65
+ "engineering": ["engineering", "mechanical", "electrical", "civil"],
66
+ "medicine": ["medicine", "medical", "healthcare", "clinical"],
67
+ "education": ["education", "teaching", "pedagogy"],
68
+ "business": ["business", "management", "mba"],
69
+ "data science": ["data science", "data analysis", "big data"]
70
+ }
71
+
72
+ for area, keywords in research_areas.items():
73
+ if any(keyword in user_lower for keyword in keywords):
74
+ info["research_area"] = area
75
+ break
76
+
77
+ # Detect academic stage
78
+ stage_keywords = {
79
+ "early PhD": ["first year", "1st year", "beginning", "just started", "new student"],
80
+ "coursework phase": ["coursework", "classes", "courses", "taking classes"],
81
+ "mid PhD": ["proposal", "qualifying", "comprehensive", "candidacy"],
82
+ "late PhD": ["dissertation", "thesis writing", "final year", "defending", "defense"]
83
+ }
84
+
85
+ for stage, keywords in stage_keywords.items():
86
+ if any(keyword in user_lower for keyword in keywords):
87
+ info["academic_stage"] = stage
88
+ break
89
+
90
+ # Detect specific question types
91
+ question_keywords = {
92
+ "topic selection": ["topic", "research question", "focus", "direction", "what to study"],
93
+ "methodology": ["method", "approach", "design", "analysis", "how to research"],
94
+ "literature review": ["literature", "sources", "papers", "reading", "references"],
95
+ "time management": ["time", "schedule", "deadline", "planning", "organizing"],
96
+ "advisor relationship": ["advisor", "supervisor", "mentor", "committee", "meeting"],
97
+ "career planning": ["career", "job", "postdoc", "industry", "academic job"],
98
+ "writing": ["writing", "paper", "manuscript", "publication"],
99
+ "funding": ["funding", "grant", "scholarship", "money", "financial"]
100
+ }
101
+
102
+ for q_type, keywords in question_keywords.items():
103
+ if any(keyword in user_lower for keyword in keywords):
104
+ info["specific_question"] = q_type
105
+ break
106
+
107
+ return info
108
+
109
+ def analyze_input(self, user_input: str):
110
+ """Analyze and store information from user input"""
111
+ self.conversation_history.append({"role": "user", "content": user_input})
112
+ extracted = self.extract_info(user_input)
113
+ self.collected_info.update(extracted)
114
+
115
+ async def generate_orchestrator_question(self) -> str:
116
+ """Generate a contextual follow-up question using the LLM"""
117
+ missing = [f for f in self.required_fields if f not in self.collected_info]
118
+
119
+ # Create context for the LLM
120
+ context = f"Conversation so far: {' '.join([msg['content'] for msg in self.conversation_history])}\n"
121
+ context += f"Information collected: {self.collected_info}\n"
122
+ context += f"Still need to know: {missing}\n"
123
+
124
+ system_prompt = """You are a PhD advisor's assistant helping to gather essential information before providing advice.
125
+ Based on the conversation and what information is still missing, ask ONE natural, conversational follow-up question.
126
+
127
+ Missing information types:
128
+ - research_area: What field/discipline they're studying
129
+ - specific_question: What specific aspect they need help with
130
+ - academic_stage: What stage of PhD they're in
131
+
132
+ Ask in a friendly, conversational way as if you're part of the chat. Keep it brief and natural."""
133
+
134
+ try:
135
+ question = await self.llm.generate(system_prompt, [{"role": "user", "content": context}])
136
+ return question.strip()
137
+ except Exception as e:
138
+ # Fallback to template questions
139
+ fallback_questions = {
140
+ "research_area": "What field are you studying in?",
141
+ "specific_question": "What specific aspect would you like guidance on?",
142
+ "academic_stage": "What stage of your PhD are you currently in?"
143
+ }
144
+ return fallback_questions.get(missing[0], "Could you tell me more about your situation?")
145
+
146
+ async def process_message(self, user_input: str) -> Dict:
147
+ """Process user message and determine next action"""
148
+
149
+ # If this is the first message and it's vague, activate orchestrator
150
+ if not self.conversation_history and self.is_input_vague(user_input):
151
+ self.orchestrator_active = True
152
+
153
+ # Analyze the input
154
+ self.analyze_input(user_input)
155
+
156
+ # If orchestrator is active and we don't have complete info
157
+ if self.orchestrator_active and not self.is_input_complete():
158
+ question = await self.generate_orchestrator_question()
159
+ return {
160
+ "status": "orchestrator_asking",
161
+ "orchestrator_question": question,
162
+ "collected_info": self.collected_info.copy()
163
+ }
164
+
165
+ # If we have complete information or orchestrator was never activated
166
+ if self.is_input_complete() or not self.orchestrator_active:
167
+ self.orchestrator_active = False
168
+ return {
169
+ "status": "ready_for_advisors",
170
+ "collected_info": self.collected_info.copy(),
171
+ "enhanced_context": self._create_enhanced_context(user_input)
172
+ }
173
+
174
+ # Default case - proceed without orchestrator
175
+ return {
176
+ "status": "ready_for_advisors",
177
+ "collected_info": {},
178
+ "enhanced_context": user_input
179
+ }
180
+
181
+ def _create_enhanced_context(self, original_query: str) -> str:
182
+ """Create enhanced context for advisors"""
183
+ if not self.collected_info:
184
+ return original_query
185
+
186
+ context_parts = []
187
+ if "research_area" in self.collected_info:
188
+ context_parts.append(f"Research area: {self.collected_info['research_area']}")
189
+ if "academic_stage" in self.collected_info:
190
+ context_parts.append(f"Academic stage: {self.collected_info['academic_stage']}")
191
+ if "specific_question" in self.collected_info:
192
+ context_parts.append(f"Focus area: {self.collected_info['specific_question']}")
193
+
194
+ if context_parts:
195
+ return f"[Context: {', '.join(context_parts)}] {original_query}"
196
+ return original_query
197
+
198
+ def reset(self):
199
+ """Reset for new conversation"""
200
+ self.collected_info = {}
201
+ self.conversation_history = []
202
+ self.orchestrator_active = False