Yaswanth123 commited on
Commit
17dace3
·
verified ·
1 Parent(s): afcbd3c

Create orchestrator.py

Browse files
Files changed (1) hide show
  1. orchestrator.py +507 -0
orchestrator.py ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FILE: orchestrator.py
2
+ # (Corrected Imports and Module Instantiation)
3
+
4
+ import logging
5
+ import json
6
+ from typing import List, Dict, Any, Tuple, Optional
7
+ import dspy
8
+
9
+ # --- 1. Corrected Imports from Project Modules ---
10
+
11
+ # Import the constants defined in config.py using a correct relative import.
12
+ # We no longer import the initialize_dspy function here.
13
+ from config import (
14
+ STATE_STAGE, STATE_HISTORY, STATE_FINAL_SYLLABUS, STATE_EXPLAINER_PROMPT,
15
+ STATE_EXPLANATION_START_INDEX, STATE_CURRENT_TITLE, STATE_GENERATED_TITLE,
16
+ STATE_RESOURCE_SUMMARY_OVERVIEW, STATE_RESOURCE_TYPE_FOR_SYLLABUS,
17
+ STATE_RESOURCE_CONTENT_JSON_FOR_SYLLABUS, STATE_DISPLAY_SYLLABUS_FLAG,
18
+ STATE_TRANSITION_EXPLAINER_FLAG, STAGE_START, STAGE_NEGOTIATING,
19
+ STAGE_EXPLAINING, STAGE_ERROR, DEFAULT_CHAT_TITLE,
20
+ TITLE_GENERATION_THRESHOLD, TITLE_MAX_HISTORY_SNIPPET_FOR_TITLE
21
+ )
22
+
23
+ # Import the synchronous DSPy modules and signatures.
24
+ from dspy_modules import (
25
+ ConversationManager,
26
+ SyllabusGeneratorRouter,
27
+ InitialResourceSummarizer,
28
+ DynamicResourceSummarizerModule,
29
+ LearningStyleQuestioner,
30
+ PersonaPromptGenerator,
31
+ ExplainerModule
32
+ )
33
+ from dspy_signatures import SyllabusFeedbackRequestSignature, FormatSyllabusXMLToMarkdown, TitleGenerationSignature
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ initial_summary_info = """
38
+ This Resource Summary is visible only to You (the agent/system) and not to the end-user.
39
+ It is provided for Your reference after the user has uploaded a resource.
40
+ This information is primarily for understanding the context of the user's resource.
41
+ For the syllabus, you should provide either the raw data or a dynamic summary.\n"""
42
+
43
+ if dspy.settings.lm:
44
+ CONVO_MANAGER = ConversationManager()
45
+ SYLLABUS_ROUTER = SyllabusGeneratorRouter()
46
+ INITIAL_RESOURCE_SUMMARIZER = InitialResourceSummarizer()
47
+ DYNAMIC_SUMMARIZER_MODULE = DynamicResourceSummarizerModule()
48
+ LEARNING_STYLE_QUESTIONER = LearningStyleQuestioner()
49
+ PERSONA_PROMPT_GENERATOR = PersonaPromptGenerator()
50
+ EXPLAINER_MODULE = ExplainerModule()
51
+ SYLLABUS_FEEDBACK_REQUESTER = dspy.Predict(SyllabusFeedbackRequestSignature, temperature=0.7)
52
+ SYLLABUS_XML_TO_MARKDOWN_FORMATTER = dspy.Predict(FormatSyllabusXMLToMarkdown, temperature=0.3)
53
+ TITLE_GENERATOR_PREDICTOR = dspy.Predict(TitleGenerationSignature, temperature=0.4)
54
+ logger.info("Orchestrator's DSPy modules initialized successfully.")
55
+ else:
56
+ logger.critical("Orchestrator loaded, but DSPy LM is NOT configured. This will cause errors when the orchestrator is called.")
57
+ # Set all modules to None so we can check for their existence and fail gracefully.
58
+ CONVO_MANAGER, SYLLABUS_ROUTER, INITIAL_RESOURCE_SUMMARIZER, DYNAMIC_SUMMARIZER_MODULE, \
59
+ LEARNING_STYLE_QUESTIONER, PERSONA_PROMPT_GENERATOR, EXPLAINER_MODULE, TITLE_GENERATOR_PREDICTOR, \
60
+ SYLLABUS_FEEDBACK_REQUESTER, SYLLABUS_XML_TO_MARKDOWN_FORMATTER = (None,) * 10
61
+
62
+ # --- Helper functions and the main process_chat_message function follow below ---
63
+ # (The rest of your file remains the same)
64
+
65
+ def format_history_for_dspy(history_list: List[Dict[str, Any]]) -> str:
66
+ formatted_history = []
67
+ for turn in history_list:
68
+ content = ""
69
+ if isinstance(turn.get('parts'), list) and turn['parts']:
70
+ content = turn['parts'][0]['text']
71
+ elif isinstance(turn.get('parts'), str):
72
+ content = turn['parts']
73
+
74
+ role = turn.get('role', 'unknown')
75
+ if role == 'model':
76
+ role = 'assistant' # Replace 'model' with 'assistant'
77
+
78
+ formatted_history.append(f"{role}: {content}")
79
+ return "\n---\n".join(formatted_history)
80
+
81
+ # The role part for model has been replaced with assistant for compatibility with litellm.
82
+
83
+ def get_last_syllabus_content_from_history(history: List[Dict[str, Any]]) -> Optional[str]:
84
+
85
+ logger.debug("Helper: Searching history backwards for last syllabus-typed message...")
86
+ if not history:
87
+ logger.warning("Helper: History is empty, cannot find syllabus.")
88
+ return None
89
+
90
+ for i in range(len(history) - 1, -1, -1):
91
+ message = history[i]
92
+ msg_role = message.get('role')
93
+ msg_type = message.get('message_type') # Get the message_type
94
+
95
+ logger.debug(f"Helper: Checking history index {i}, Role: '{msg_role}', Type: '{msg_type}'")
96
+
97
+ # We are looking for messages from 'model' or 'system' that are explicitly typed
98
+ # as either 'syllabus' (for old XML format) or 'syllabus_markdown' (for new Markdown format).
99
+ if msg_role in ['model', 'system'] and msg_type in ['syllabus', 'syllabus_markdown']:
100
+ content = ""
101
+ parts_list = message.get('parts', [])
102
+
103
+ if isinstance(parts_list, list) and len(parts_list) > 0:
104
+ first_part = parts_list[0]
105
+ if isinstance(first_part, dict):
106
+ content = first_part.get('text', '')
107
+ elif isinstance(first_part, str):
108
+ content = first_part
109
+ elif isinstance(parts_list, str): # Handle if 'parts' itself was saved as a string
110
+ content = parts_list
111
+ elif 'content' in message: # Fallback if structure is simpler like {'role': ..., 'content': ...}
112
+ logger.debug("Helper: 'parts' key not found or empty, trying 'content' key directly.")
113
+ if isinstance(message.get('content'), str):
114
+ content = message.get('content', '')
115
+
116
+
117
+ if content:
118
+ logger.info(f"Helper: FOUND syllabus content via message_type '{msg_type}' at index {i}. Content starts: '{content[:70]}...'")
119
+ return content.strip() # Return the full content of this message
120
+ else:
121
+ logger.warning(f"Helper: Found syllabus-typed message at index {i} but content was empty.")
122
+ # Continue searching
123
+
124
+ logger.warning("Helper: Finished searching history, did not find a valid syllabus-typed message with content.")
125
+ return None
126
+
127
+
128
+
129
+
130
+ # --- Main Orchestration Logic ---
131
+ def process_chat_message(
132
+ user_message_text: str,
133
+ current_session_state: Dict[str, Any],
134
+ modified_explainer_prompt: Optional[str] = None ,
135
+ uploaded_resource_data: Optional[Dict[str, str]] = None # Filename -> text content
136
+ ) -> Tuple[str, Dict[str, Any]]:
137
+ """
138
+ Processes user message using DSPy modules.
139
+ Handles initial resource processing if `uploaded_resource_data` is provided.
140
+ """
141
+ if not CONVO_MANAGER:
142
+ logger.error("Orchestrator's DSPy modules are not initialized. Cannot process message.")
143
+ # Return an error state immediately
144
+ error_state = current_session_state.copy()
145
+ error_state[STATE_STAGE] = STAGE_ERROR
146
+ error_state[STATE_HISTORY].append({'role': 'user', 'parts': [{'text': user_message_text}]})
147
+ error_state[STATE_HISTORY].append({'role': 'model', 'parts': [{'text': "[FATAL ERROR: AI modules not initialized. Please contact support.]"}]})
148
+ return "[FATAL ERROR: AI modules not initialized]", error_state
149
+
150
+
151
+ new_state = current_session_state.copy()
152
+ new_state.pop(STATE_DISPLAY_SYLLABUS_FLAG, None)
153
+ new_state.pop(STATE_TRANSITION_EXPLAINER_FLAG, None)
154
+ new_state.pop(STATE_GENERATED_TITLE, None)
155
+
156
+
157
+
158
+ stage = new_state.get(STATE_STAGE, STAGE_START)
159
+ history: List[Dict[str, Any]] = new_state.get(STATE_HISTORY, []) # History from view already includes latest user msg
160
+ current_title = new_state.get(STATE_CURRENT_TITLE, DEFAULT_CHAT_TITLE)
161
+
162
+ ai_reply_for_user = ""
163
+
164
+ logger.debug(f"Orchestrator (DSPy) received: Stage='{stage}', Title='{current_title}', History len={len(history)}")
165
+ if uploaded_resource_data:
166
+ logger.info(f"Processing {len(uploaded_resource_data)} uploaded resources.")
167
+
168
+ try:
169
+ # --- Initial Resource Processing (only if resources are provided AND it's the start of negotiation) ---
170
+ #Resources can Be only Uploaded at the start.
171
+ if stage == STAGE_START and uploaded_resource_data:
172
+ logger.info("First turn with resources. Processing them now...")
173
+
174
+ total_chars = sum(len(text) for text in uploaded_resource_data.values())
175
+
176
+ resource_summary_for_manager = "Resources were provided by the user." # Default
177
+ resource_type_for_syllabus = "NONE"
178
+ resource_content_json = "{}"
179
+ #Syllabus Segregation
180
+
181
+ if not uploaded_resource_data:
182
+ resource_summary_for_manager = "No resources were processed or user did not provide any."
183
+ resource_type_for_syllabus = "NONE"
184
+ elif total_chars > 70000: # Heuristic from your notebook for "heavy" resources
185
+ logger.info(f"Total resource chars ({total_chars}) > 70k. Using DYNAMIC SUMMARIES for syllabus gen.")
186
+ resource_type_for_syllabus = "SUMMARIES"
187
+ # For manager, provide an overview from InitialResourceSummarizer
188
+ # Truncate content for initial summary if very large before sending to InitialResourceSummarizer
189
+ initial_summary_input_dict = {
190
+ fname: content[:40000] for fname, content in uploaded_resource_data.items()
191
+ }
192
+ resource_summary_for_manager = INITIAL_RESOURCE_SUMMARIZER.forward(initial_summary_input_dict)
193
+
194
+ new_state['raw_resource_data_for_dynamic_summary'] = uploaded_resource_data # Store full data
195
+ else:
196
+ logger.info(f"Total resource chars ({total_chars}) <= 70k. Using RAW TEXT for syllabus gen.")
197
+ resource_type_for_syllabus = "RAW_TEXT"
198
+ initial_summary_input_dict = {
199
+ fname: content[:40000] for fname, content in uploaded_resource_data.items()
200
+ }
201
+ resource_summary_for_manager = INITIAL_RESOURCE_SUMMARIZER.forward(initial_summary_input_dict)
202
+ resource_content_json = json.dumps(uploaded_resource_data, indent=2)
203
+ new_state[STATE_RESOURCE_SUMMARY_OVERVIEW] = resource_summary_for_manager
204
+ new_state[STATE_RESOURCE_TYPE_FOR_SYLLABUS] = resource_type_for_syllabus
205
+ new_state[STATE_RESOURCE_CONTENT_JSON_FOR_SYLLABUS] = resource_content_json
206
+ new_state['raw_resource_data_for_dynamic_summary'] = uploaded_resource_data # Alreday done upside
207
+
208
+
209
+ # This should be done if Only History length is less than 2.
210
+ if resource_summary_for_manager and resource_summary_for_manager != "No resources were processed or user did not provide any." and len(history)<=2:
211
+
212
+ history.append({'role': 'model', 'parts': [{"text" : str(initial_summary_info) + str(resource_summary_for_manager)}],'message_type': 'internal_resource_summary'})
213
+
214
+
215
+
216
+ # --- Negotiation Phase (STAGE_START, STAGE_NEGOTIATING) ---
217
+ if stage in [STAGE_START, STAGE_NEGOTIATING]:
218
+ if stage == STAGE_START:
219
+ new_state[STATE_STAGE] = STAGE_NEGOTIATING
220
+ stage = STAGE_NEGOTIATING # Update local stage variable
221
+
222
+ logger.info(f"Orchestrator (DSPy): Stage={stage}. Calling ConversationManager.")
223
+
224
+ history_str = format_history_for_dspy(history)
225
+ current_syllabus_xml_str = new_state.get(STATE_FINAL_SYLLABUS) or \
226
+ get_last_syllabus_content_from_history(history) or \
227
+ "None" # Try to get latest syllabus for manager
228
+
229
+ # Get resource overview from state if set, otherwise "None"
230
+ resource_overview_for_manager = new_state.get(STATE_RESOURCE_SUMMARY_OVERVIEW, "No resources were processed or provided by the user for this session.")
231
+
232
+ action_code, display_text = CONVO_MANAGER.forward(
233
+ conversation_history_str=history_str,
234
+ current_syllabus_xml=current_syllabus_xml_str,
235
+ user_input=user_message_text, # Manager needs the latest user message explicitly
236
+
237
+ )
238
+ logger.info(f"ConversationManager action: '{action_code}', display_text: '{display_text[:100]}...'")
239
+
240
+ ai_reply_for_user = display_text # This will be empty if action is not CONVERSE
241
+ if display_text:
242
+ history.append({'role': 'model', 'parts': [{'text': display_text}]})
243
+
244
+
245
+
246
+ # --- Handle Actions from ConversationManager ---
247
+ if action_code in ["GENERATE", "MODIFY"]:
248
+ task_type_str = "generation" if action_code == "GENERATE" else "modification"
249
+ logger.info(f"Syllabus {task_type_str} requested. Resource type: {new_state.get(STATE_RESOURCE_TYPE_FOR_SYLLABUS)}")
250
+ retrieved_resource_type = new_state.get(STATE_RESOURCE_TYPE_FOR_SYLLABUS, "NONE")
251
+ retrieved_resource_content_json = new_state.get(STATE_RESOURCE_CONTENT_JSON_FOR_SYLLABUS, "{}")
252
+ _temp_resource_type = new_state.get(STATE_RESOURCE_TYPE_FOR_SYLLABUS) # Get value, could be Python None
253
+ if _temp_resource_type is None:
254
+ retrieved_resource_type = "NONE"
255
+ else:
256
+ retrieved_resource_type = _temp_resource_type
257
+ logger.info(f"Syllabus {task_type_str} requested. Resource type from state: {retrieved_resource_type}")
258
+ # If type is SUMMARIES, we need to generate them now using DynamicSummarizer
259
+ if retrieved_resource_type == "SUMMARIES":
260
+ raw_data_for_dynamic_summary = new_state.get('raw_resource_data_for_dynamic_summary')
261
+ if raw_data_for_dynamic_summary and isinstance(raw_data_for_dynamic_summary, dict):
262
+ logger.info("Generating dynamic summaries for syllabus router...")
263
+ summaries_for_syllabus = {}
264
+ history_str_for_summarizer = format_history_for_dspy(history) # Fresh history string
265
+ for res_id, res_content in raw_data_for_dynamic_summary.items():
266
+ summary_dict = DYNAMIC_SUMMARIZER_MODULE.forward(
267
+ resource_content=res_content,
268
+ resource_identifier=res_id,
269
+ conversation_history_str=history_str_for_summarizer
270
+ )
271
+ if summary_dict:
272
+ summaries_for_syllabus[res_id] = summary_dict
273
+ current_resource_content_json = json.dumps(summaries_for_syllabus, indent=2)
274
+ logger.info(f"Dynamic summaries generated. JSON length: {len(current_resource_content_json)}")
275
+
276
+ else:
277
+ logger.warning("SUMMARIES type selected but no 'raw_resource_data_for_dynamic_summary' found. Falling back to NONE.")
278
+ current_resource_type = "NONE"
279
+ current_resource_content_json = "{}"
280
+ if retrieved_resource_type == "RAW_TEXT":
281
+ current_resource_content_json = retrieved_resource_content_json
282
+
283
+
284
+
285
+ generated_xml = SYLLABUS_ROUTER.forward(
286
+ conversation_history_str=format_history_for_dspy(history),
287
+ resource_type=retrieved_resource_type,
288
+ resource_content=current_resource_content_json if retrieved_resource_type != "NONE" else None
289
+ )
290
+ print(retrieved_resource_type)
291
+
292
+ final_syllabus_content_for_frontend = generated_xml
293
+ message_content_type_for_syllabus_display = 'syllabus_markdown'
294
+ syllabus_generation_was_successful = False # Initialize flag
295
+
296
+ # --- BLOCK 1: XML to Markdown Formatting (and set success flag) ---
297
+ if generated_xml and not generated_xml.strip().upper().startswith(("<SYLLABUS>\n[ERROR", "<SYLLABUS>[ERROR")):
298
+ syllabus_generation_was_successful = True # Mark initial generation as successful
299
+ logger.info(f"Syllabus XML generated. Length: {len(generated_xml)}. Attempting Markdown formatting.")
300
+
301
+ if SYLLABUS_XML_TO_MARKDOWN_FORMATTER:
302
+ try:
303
+ format_prediction = SYLLABUS_XML_TO_MARKDOWN_FORMATTER(
304
+ syllabus_xml_input=generated_xml
305
+ )
306
+ formatted_markdown = format_prediction.cleaned_syllabus_markdown.strip()
307
+
308
+ if formatted_markdown and not formatted_markdown.lower().startswith(("[error", "[warn")):
309
+ final_syllabus_content_for_frontend = formatted_markdown
310
+ # message_content_type_for_syllabus_display = 'syllabus'
311
+ logger.info("Syllabus successfully formatted to Markdown.")
312
+ else:
313
+ logger.warning(f"Syllabus Markdown formatting returned empty/error: {formatted_markdown[:100]}. Using raw XML (from router).")
314
+
315
+ except Exception as fmt_e:
316
+ logger.error(f"Error during syllabus XML to Markdown formatting: {fmt_e}", exc_info=True)
317
+ else:
318
+ logger.warning("SYLLABUS_XML_TO_MARKDOWN_FORMATTER not available. Using raw XML (from router).")
319
+
320
+ else:
321
+
322
+ syllabus_generation_was_successful = False # Explicitly false
323
+ logger.error(f"Syllabus XML generation by SYLLABUS_ROUTER failed or returned error: {generated_xml[:200]}")
324
+
325
+ # --- BLOCK 2: Add syllabus to history and state ---
326
+ # This message is the syllabus display itself (or the error from the router if generation failed)
327
+ history.append({
328
+ 'role': 'model',
329
+ 'parts': [{'text': final_syllabus_content_for_frontend}],
330
+ 'message_type': message_content_type_for_syllabus_display
331
+ })
332
+ print(history[-1])
333
+ new_state[STATE_DISPLAY_SYLLABUS_FLAG] = {
334
+ "content": final_syllabus_content_for_frontend,
335
+ "type": message_content_type_for_syllabus_display
336
+ }
337
+
338
+ # --- NEW BLOCK 3: Generate Conversational Reply (Feedback or Error) ---
339
+ if syllabus_generation_was_successful:
340
+ # The syllabus (Markdown or XML) is already in history. Now add the feedback prompt.
341
+ logger.info(f"Syllabus processed for display (type: {message_content_type_for_syllabus_display}). Requesting user feedback.")
342
+ if SYLLABUS_FEEDBACK_REQUESTER:
343
+ try:
344
+
345
+ history_for_feedback_str = format_history_for_dspy(history)
346
+ feedback_prediction = SYLLABUS_FEEDBACK_REQUESTER(
347
+ conversation_history_with_syllabus=history_for_feedback_str
348
+ )
349
+ ai_reply_for_user = feedback_prediction.feedback_query_to_user.strip()
350
+ if not ai_reply_for_user:
351
+ logger.warning("SYLLABUS_FEEDBACK_REQUESTER returned empty, using fallback.")
352
+ ai_reply_for_user = "I've drafted the syllabus. What are your thoughts?"
353
+ except Exception as fb_err:
354
+ logger.error(f"Error calling SYLLABUS_FEEDBACK_REQUESTER: {fb_err}", exc_info=True)
355
+ ai_reply_for_user = "Here is the syllabus draft. How does it look?"
356
+ else:
357
+ logger.error("SYLLABUS_FEEDBACK_REQUESTER not initialized. Using hardcoded feedback prompt.")
358
+ ai_reply_for_user = "I've prepared the syllabus. Please review it."
359
+
360
+ # Add the feedback prompt as the next message in history
361
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
362
+
363
+ else:
364
+
365
+ ai_reply_for_user = final_syllabus_content_for_frontend
366
+ logger.info(f"Syllabus generation failed. AI reply set to the error from router: {ai_reply_for_user[:100]}")
367
+
368
+
369
+ elif action_code == "FINALIZE":
370
+ logger.info("Finalization requested by manager.")
371
+ last_syllabus_in_history = get_last_syllabus_content_from_history(history)
372
+ if last_syllabus_in_history:
373
+ new_state[STATE_FINAL_SYLLABUS] = f"<syllabus>\n{last_syllabus_in_history}\n</syllabus>" # Store it
374
+
375
+ # Ask for learning style
376
+ style_question = LEARNING_STYLE_QUESTIONER.forward(
377
+ conversation_history_str=format_history_for_dspy(history)
378
+ )
379
+ ai_reply_for_user = style_question
380
+ history.append({'role': 'model', 'parts': [{'text': style_question}]})
381
+ else:
382
+ logger.warning("FINALIZE action but no syllabus found in history.")
383
+ ai_reply_for_user = "It seems we don't have a syllabus to finalize yet. Could we create one first?"
384
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
385
+
386
+ elif action_code == "PERSONA":
387
+ logger.info("Persona generation triggered by manager.")
388
+ final_syllabus_xml_str = new_state.get(STATE_FINAL_SYLLABUS)
389
+ if final_syllabus_xml_str:
390
+ logger.info("Generating explainer prompt body...")
391
+ explainer_prompt_body = PERSONA_PROMPT_GENERATOR.forward(
392
+ conversation_history_str=format_history_for_dspy(history)
393
+ )
394
+ if explainer_prompt_body:
395
+ full_explainer_prompt = f"{explainer_prompt_body}\n\nHere is the syllabus we will follow:\n{final_syllabus_xml_str}"
396
+ print(full_explainer_prompt)
397
+ new_state[STATE_EXPLAINER_PROMPT] = full_explainer_prompt
398
+ new_state[STATE_STAGE] = STAGE_EXPLAINING # << TRANSITION STAGE
399
+ new_state[STATE_TRANSITION_EXPLAINER_FLAG] = True
400
+ new_state[STATE_EXPLANATION_START_INDEX] = len(history) # Record index before explainer intro
401
+
402
+ logger.info("Explainer prompt generated. Moving to EXPLAINING stage.")
403
+
404
+
405
+ explainer_intro_query = "Based on your persona (defined in system_instructions) and the syllabus provided, please introduce yourself to the user. Briefly state what you'll be helping them with and adopt a welcoming tone consistent with your persona."
406
+ explainer_intro_response = EXPLAINER_MODULE.forward(
407
+ system_instructions_str=full_explainer_prompt,
408
+ history_str="None", # No prior *explainer* history for this first turn
409
+ user_query_str=explainer_intro_query
410
+ )
411
+ ai_reply_for_user = explainer_intro_response
412
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
413
+ else:
414
+ logger.error("Failed to generate explainer prompt body.")
415
+ ai_reply_for_user = "Sorry, I had trouble setting up the learning session. Please try again."
416
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
417
+ new_state[STATE_STAGE] = STAGE_ERROR
418
+ else:
419
+ logger.warning("PERSONA action but no finalized syllabus in state.")
420
+ ai_reply_for_user = "We need to finalize a syllabus before we can tailor the tutor. Shall we continue with that?"
421
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
422
+
423
+ elif action_code == "CONVERSE":
424
+ # ai_reply_for_user is already set from manager's display_text
425
+ if not ai_reply_for_user: # Should not happen if manager follows rules
426
+ logger.warning("CONVERSE action but manager provided no display_text. Using fallback.")
427
+ ai_reply_for_user = "Okay, how would you like to proceed?"
428
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
429
+
430
+ else:
431
+ logger.error(f"Unknown action_code '{action_code}' from ConversationManager.")
432
+ ai_reply_for_user = "I'm not sure how to proceed with that. Could you clarify?"
433
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
434
+
435
+ # --- Explanation Phase (STAGE_EXPLAINING) ---
436
+ elif stage == STAGE_EXPLAINING:
437
+ logger.info(f"Orchestrator (DSPy): Stage={stage}. Calling ExplainerModule.")
438
+ explainer_sys_prompt = modified_explainer_prompt or new_state.get(STATE_EXPLAINER_PROMPT)
439
+ expl_start_idx = new_state.get(STATE_EXPLANATION_START_INDEX, 0)
440
+
441
+ if not explainer_sys_prompt:
442
+ logger.error("Explainer stage but no explainer_system_prompt in state.")
443
+ ai_reply_for_user = "[SYSTEM ERROR: Explainer setup incomplete. Cannot proceed.]"
444
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
445
+ new_state[STATE_STAGE] = STAGE_ERROR
446
+ else:
447
+ # For explainer, only pass relevant part of history (after persona setup)
448
+ explainer_relevant_history_str = format_history_for_dspy(history[expl_start_idx:])
449
+
450
+ explainer_response = EXPLAINER_MODULE.forward(
451
+ system_instructions_str=explainer_sys_prompt,
452
+ history_str=explainer_relevant_history_str,
453
+ user_query_str=user_message_text
454
+ )
455
+ ai_reply_for_user = explainer_response
456
+ history.append({'role': 'model', 'parts': [{'text': explainer_response}]})
457
+
458
+ # --- Error Stage ---
459
+ elif stage == STAGE_ERROR:
460
+ logger.warning("Orchestrator is in ERROR stage.")
461
+ ai_reply_for_user = "I'm sorry, an internal error occurred. Please try starting a new conversation or contact support."
462
+ # To prevent loops, don't add this generic error to history if user just messaged. Let user try again.
463
+
464
+ # --- Unknown Stage ---
465
+ else:
466
+ logger.error(f"Orchestrator encountered an unknown stage: {stage}")
467
+ ai_reply_for_user = "[SYSTEM ERROR: Invalid application state. Please start over.]"
468
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
469
+ new_state[STATE_STAGE] = STAGE_ERROR
470
+
471
+ # --- Title Generation Logic (Simplified to use DSPy Predict) ---
472
+ final_message_count = len(history)
473
+ if current_title == DEFAULT_CHAT_TITLE and final_message_count >= TITLE_GENERATION_THRESHOLD:
474
+ logger.info("Conditions met for title generation.")
475
+ # Prepare a snippet of history for the title generator
476
+ history_for_title_str = format_history_for_dspy(history[:TITLE_MAX_HISTORY_SNIPPET_FOR_TITLE])
477
+ if TITLE_GENERATOR_PREDICTOR:
478
+ try:
479
+ title_prediction = TITLE_GENERATOR_PREDICTOR(chat_history_summary=history_for_title_str) # await predict
480
+ generated_title_text = title_prediction.chat_title.strip().strip('"\'')
481
+ if generated_title_text and not generated_title_text.lower().startswith(("[error", "[warn", "[empty")):
482
+ new_state[STATE_GENERATED_TITLE] = generated_title_text[:150] # Max length
483
+ logger.info(f"Generated title: '{new_state[STATE_GENERATED_TITLE]}'")
484
+ else:
485
+ logger.warning(f"Title generator returned empty or error-like: {generated_title_text}")
486
+ except Exception as title_e:
487
+ logger.error(f"Error during title generation predictor call: {title_e}", exc_info=True)
488
+ else:
489
+ logger.error("TITLE_GENERATOR_PREDICTOR not initialized.")
490
+
491
+
492
+ except Exception as e:
493
+ logger.error(f"Orchestrator (DSPy): Unhandled exception: {e}", exc_info=True)
494
+ ai_reply_for_user = "[SYSTEM ERROR: An unexpected issue occurred. Please try again.]"
495
+ new_state[STATE_STAGE] = STAGE_ERROR
496
+ # Ensure error is logged to history if not already the last message
497
+ if not history or not (history[-1]['role'] == 'model' and history[-1]['parts'][0]['text'] == ai_reply_for_user):
498
+ history.append({'role': 'model', 'parts': [{'text': ai_reply_for_user}]})
499
+
500
+ # --- Final State Update & Return ---
501
+ new_state[STATE_HISTORY] = history
502
+ logger.debug(f"Orchestrator (DSPy) returning: Stage='{new_state.get(STATE_STAGE)}', History Len={len(history)}, AI Reply starts: '{ai_reply_for_user[:50]}...'")
503
+ logger.debug(f"Flags: DisplaySyllabus='{new_state.get(STATE_DISPLAY_SYLLABUS_FLAG) is not None}', TransitionExplainer='{new_state.get(STATE_TRANSITION_EXPLAINER_FLAG)}'")
504
+
505
+ return ai_reply_for_user, new_state
506
+
507
+