JatinAutonomousLabs commited on
Commit
f51b81e
·
verified ·
1 Parent(s): cf7379d

Update graph.py

Browse files
Files changed (1) hide show
  1. graph.py +194 -127
graph.py CHANGED
@@ -81,7 +81,6 @@ class AgentState(TypedDict):
81
  rework_cycles: int
82
  max_loops: int
83
  status_update: str
84
- final_artifact_path: Optional[str] # Modification 3: Track the final artifact path
85
 
86
  # --- LLM & parsing ---
87
  llm = ChatOpenAI(model="gpt-4o", temperature=0.1, max_retries=3, request_timeout=60)
@@ -261,7 +260,7 @@ def build_repo_zip(files_map: Dict[str,str], repo_name: str="generated_app", out
261
  os.makedirs(out_dir, exist_ok=True)
262
  uid = uuid.uuid4().hex[:8]
263
  repo_dir = os.path.join(out_dir, f"{repo_name}_{uid}")
264
- os.makedirs(os.path.dirname(dest), exist_ok=True)
265
  for rel_path, content in files_map.items():
266
  dest = os.path.join(repo_dir, rel_path)
267
  os.makedirs(os.path.dirname(dest), exist_ok=True)
@@ -317,150 +316,227 @@ def run_planner_agent(state: AgentState):
317
  log.info(f"Pre-flight Estimate: {plan_data}")
318
  return {"pmPlan": plan_data, "execution_path": path, "status_update": "Plan and cost estimate created. Awaiting approval."}
319
 
320
- # Placeholder functions for the graph nodes
321
  def run_memory_retrieval(state: AgentState):
 
322
  path = ensure_list(state, 'execution_path') + ["Memory Retriever"]
323
- # ... (Actual memory retrieval logic) ...
324
- return {"retrievedMemory": "Simulated memory content.", "execution_path": path, "status_update": "Memory retrieved."}
 
 
 
 
 
 
325
 
326
  def run_intent_agent(state: AgentState):
 
327
  path = ensure_list(state, 'execution_path') + ["Intent Agent"]
328
- # ... (Actual intent refinement logic) ...
329
- return {"coreObjectivePrompt": state['userInput'], "execution_path": path, "status_update": "Intent refined."}
 
 
 
 
 
 
330
 
331
  def run_pm_agent(state: AgentState):
 
 
 
 
332
  path = ensure_list(state, 'execution_path') + ["PM Agent"]
333
- # ... (Actual PM logic to create code/draft) ...
334
- return {"experimentCode": "print('Hello, world!')", "experimentResults": None, "draftResponse": "Initial draft.", "execution_path": path, "status_update": "PM output ready."}
335
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
 
337
  def run_experimenter_agent(state: AgentState):
 
338
  path = ensure_list(state, 'execution_path') + ["Experimenter Agent"]
339
- # ... (Actual code execution and artifact creation logic) ...
340
-
341
- # Simulate an artifact path to satisfy the archivist agent's input
342
- temp_file_path = os.path.join(OUT_DIR, f"experiment_result_{uuid.uuid4().hex[:8]}.txt")
343
- with open(temp_file_path, 'w') as f:
344
- f.write("Simulated experiment result.")
345
-
346
- results = {"stdout": "Code executed successfully.", "paths": [temp_file_path]}
347
- return {"experimentResults": results, "execution_path": path, "status_update": "Experiment run."}
348
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
  def run_synthesis_agent(state: AgentState):
351
- path = ensure_list(state, 'execution_path') + ["Synthesis Agent"]
352
- # ... (Actual synthesis logic) ...
353
- new_draft = f"Final draft synthesized based on results: {state.get('experimentResults', {}).get('stdout', 'N/A')}"
354
- return {"draftResponse": new_draft, "execution_path": path, "status_update": "Draft synthesized."}
355
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
  def run_qa_agent(state: AgentState):
358
  log.info("--- ✅ Running QA Agent ---")
359
  path = ensure_list(state, 'execution_path') + ["QA Agent"]
360
-
361
- # --- MODIFICATION 4: QA Prompt Update ---
362
- system_prompt = (
363
- "You are the Quality Assurance Agent. Your task is to critically review the drafted response "
364
- "and the available results against the *entire* original project plan (PM Plan)."
365
- "\n\n***Your check MUST equally prioritize ALL steps in the PM Plan, not just the final ones.*** "
366
- "Evaluate if ALL requirements from the original user prompt have been met, whether the "
367
- "execution was successful, and if the artifacts (code, results, draft response) "
368
- "are complete and of high quality."
369
- "\n\nFocus on:"
370
- "\n1. **Completeness:** Has *every single* item in the PM Plan been addressed?"
371
- "\n2. **Accuracy:** Do the results and draft response correctly answer the user's prompt?"
372
- "\n3. **Actionable Feedback:** If any requirement is missed (even early ones), provide specific "
373
- "feedback for a rework cycle."
374
- "\n\nIf satisfied and all requirements are met, respond ONLY with the word 'APPROVED'."
375
- "\nIf rework is needed, provide constructive feedback for the PM Agent."
376
- )
377
- # Placeholder response logic
378
- # In a real app, this would be an LLM call using the system_prompt
379
- content = 'APPROVED' if state.get('rework_cycles', 0) >= 0 else 'Feedback: Missing initial step.'
380
- is_approved = content.upper() == 'APPROVED'
381
-
382
- return {
383
- "qaFeedback": content if not is_approved else None,
384
- "approved": is_approved,
385
- "execution_path": path,
386
- "status_update": "Review complete. Rework required." if not is_approved else "Quality Approved."
387
- }
388
 
389
  def run_archivist_agent(state: AgentState):
390
- log.info("--- 📦 Running Archivist Agent ---")
391
  path = ensure_list(state, 'execution_path') + ["Archivist Agent"]
392
-
393
- # Logic to zip all files in OUT_DIR or referenced in experimentResults
394
- unique_id = uuid.uuid4().hex[:8]
395
- zip_filename = f"{unique_id}_final_artifact.zip"
396
- final_artifact_path = os.path.join(EXPORTS_DIR, zip_filename)
397
-
398
- # --- SIMULATED ZIP CREATION ---
399
- try:
400
- with zipfile.ZipFile(final_artifact_path, 'w') as zf:
401
- zf.writestr('README.txt', 'This is the final artifact zip file.')
402
- except Exception as e:
403
- log.error(f"Failed to create dummy zip file: {e}")
404
- final_artifact_path = None
405
- # --- END SIMULATED ZIP CREATION ---
406
-
407
- # --- MODIFICATION 3: Add final_artifact_path to state ---
408
- return {
409
- "final_artifact_path": final_artifact_path,
410
- "execution_path": path,
411
- "status_update": f"Final artifacts archived to {zip_filename if final_artifact_path else 'N/A'}"
412
- }
413
 
414
  def run_disclaimer_agent(state: AgentState):
 
415
  path = ensure_list(state, 'execution_path') + ["Disclaimer Agent"]
416
- final_response = state.get('draftResponse', '') + "\n\n***Disclaimer: This output is AI-generated and requires human review.***"
417
- return {"draftResponse": final_response, "execution_path": path, "status_update": "Disclaimer added."}
418
-
419
- # --- Control flow (check experiment needed) ---
420
- def check_experiment_needed(state: AgentState) -> str:
421
- if state.get('pmPlan', {}).get('experiment_needed', False):
422
- return "run_experiment"
423
- return "synthesis"
424
-
425
- # --- Control flow (check approval/rework) ---
426
- def check_rework(state: AgentState) -> str:
427
- max_loops = state.get('max_loops', 0)
428
- rework_cycles = state.get('rework_cycles', 0)
429
- approved = state.get('approved', False)
430
-
431
- if approved:
432
- return "archivist"
433
- if rework_cycles >= max_loops:
434
- log.warning(f"Maximum rework cycles ({max_loops}) reached. Forcing finalization.")
435
- return "archivist"
436
- return "rework"
437
-
438
- # --- Rework update ---
439
- def update_rework_cycles(state: AgentState):
440
- path = ensure_list(state, 'execution_path') + ["Rework Cycle Update"]
441
- return {
442
- "rework_cycles": state.get('rework_cycles', 0) + 1,
443
- "execution_path": path,
444
- "status_update": f"Rework cycle {state.get('rework_cycles', 0) + 1} started based on QA feedback."
445
- }
446
-
447
- # --- Graph Definition ---
448
-
449
- # Triage App
450
  triage_workflow = StateGraph(AgentState)
451
  triage_workflow.add_node("triage", run_triage_agent)
452
  triage_workflow.set_entry_point("triage")
453
  triage_workflow.add_edge("triage", END)
454
  triage_app = triage_workflow.compile()
455
 
456
- # Planner App
457
  planner_workflow = StateGraph(AgentState)
458
  planner_workflow.add_node("planner", run_planner_agent)
459
  planner_workflow.set_entry_point("planner")
460
  planner_workflow.add_edge("planner", END)
461
  planner_app = planner_workflow.compile()
462
 
463
- # Main App
464
  main_workflow = StateGraph(AgentState)
465
  main_workflow.add_node("memory_retriever", run_memory_retrieval)
466
  main_workflow.add_node("intent_agent", run_intent_agent)
@@ -470,28 +546,19 @@ main_workflow.add_node("synthesis_agent", run_synthesis_agent)
470
  main_workflow.add_node("qa_agent", run_qa_agent)
471
  main_workflow.add_node("archivist_agent", run_archivist_agent)
472
  main_workflow.add_node("disclaimer_agent", run_disclaimer_agent)
473
- main_workflow.add_node("rework_update", update_rework_cycles)
474
-
475
 
476
  main_workflow.set_entry_point("memory_retriever")
477
  main_workflow.add_edge("memory_retriever", "intent_agent")
478
  main_workflow.add_edge("intent_agent", "pm_agent")
479
- # Experiment flow: PM Agent decides path
480
- main_workflow.add_conditional_edges("pm_agent", check_experiment_needed, {
481
- "run_experiment": "experimenter_agent",
482
- "synthesis": "synthesis_agent"
483
- })
484
  main_workflow.add_edge("experimenter_agent", "synthesis_agent")
485
  main_workflow.add_edge("synthesis_agent", "qa_agent")
486
- # Rework flow: QA Agent decides path
487
- main_workflow.add_conditional_edges("qa_agent", check_rework, {
488
- "archivist": "archivist_agent",
489
- "rework": "rework_update"
490
- })
491
- # Rework loop back to the PM Agent after update
492
- main_workflow.add_edge("rework_update", "pm_agent")
493
- # Finalization
494
- main_workflow.add_edge("archivist_agent", "disclaimer_agent")
495
  main_workflow.add_edge("disclaimer_agent", END)
496
 
 
 
 
 
 
 
497
  main_app = main_workflow.compile()
 
81
  rework_cycles: int
82
  max_loops: int
83
  status_update: str
 
84
 
85
  # --- LLM & parsing ---
86
  llm = ChatOpenAI(model="gpt-4o", temperature=0.1, max_retries=3, request_timeout=60)
 
260
  os.makedirs(out_dir, exist_ok=True)
261
  uid = uuid.uuid4().hex[:8]
262
  repo_dir = os.path.join(out_dir, f"{repo_name}_{uid}")
263
+ os.makedirs(repo_dir, exist_ok=True)
264
  for rel_path, content in files_map.items():
265
  dest = os.path.join(repo_dir, rel_path)
266
  os.makedirs(os.path.dirname(dest), exist_ok=True)
 
316
  log.info(f"Pre-flight Estimate: {plan_data}")
317
  return {"pmPlan": plan_data, "execution_path": path, "status_update": "Plan and cost estimate created. Awaiting approval."}
318
 
 
319
  def run_memory_retrieval(state: AgentState):
320
+ log.info("--- 🧠 Accessing Long-Term Memory ---")
321
  path = ensure_list(state, 'execution_path') + ["Memory Retriever"]
322
+ relevant_mems = memory_manager.retrieve_relevant_memories(state.get('userInput',''))
323
+ if relevant_mems:
324
+ context = "\n".join([f"Memory: {mem.page_content}" for mem in relevant_mems])
325
+ log.info(f"Found {len(relevant_mems)} relevant memories.")
326
+ else:
327
+ context = "No relevant memories found."
328
+ log.info(context)
329
+ return {"retrievedMemory": context, "execution_path": path, "status_update": "Searching for relevant past information..."}
330
 
331
  def run_intent_agent(state: AgentState):
332
+ log.info("--- 🎯 Running Intent Agent ---")
333
  path = ensure_list(state, 'execution_path') + ["Intent Agent"]
334
+ prompt = (f"Refine the user's request into a clear, actionable 'core objective prompt'.\n\nRelevant Memory:\n{state.get('retrievedMemory')}\n\nUser Request: \"{state.get('userInput','')}\"\n\nCore Objective:")
335
+ response = llm.invoke(prompt)
336
+ core_obj = getattr(response, "content", "") or ""
337
+ detection = detect_requested_output_types(core_obj or state.get('userInput',''))
338
+ extras = {}
339
+ if detection.get('requires_artifact'):
340
+ extras['artifact_detection'] = detection
341
+ return {"coreObjectivePrompt": core_obj, **extras, "execution_path": path, "status_update": "Clarifying the main objective..."}
342
 
343
  def run_pm_agent(state: AgentState):
344
+ log.info("--- 👷 Running PM Agent ---")
345
+ current_cycles = ensure_int(state, 'rework_cycles', 0) + 1
346
+ max_loops_val = ensure_int(state, 'max_loops', 0)
347
+ log.info(f"Starting work cycle {current_cycles}/{max_loops_val + 1}")
348
  path = ensure_list(state, 'execution_path') + ["PM Agent"]
349
+ feedback = f"QA Feedback (must be addressed): {state.get('qaFeedback')}" if state.get('qaFeedback') else ""
350
+ prompt = (
351
+ f"Decompose the core objective into a plan. Determine if code execution or artifact generation is needed and define the goal.\n\n"
352
+ f"Core Objective: {state.get('coreObjectivePrompt')}\n\n{feedback}\n\n"
353
+ f"Respond in JSON with keys: 'plan_steps' (list), 'experiment_needed' (bool), 'experiment_type' (optional string), and 'experiment_goal' (str if needed)."
354
+ )
355
+ response = llm.invoke(prompt)
356
+ plan = parse_json_from_llm(getattr(response, "content", "") or "")
357
+ if not plan:
358
+ log.warning("PM Agent did not produce JSON — applying heuristic fallback.")
359
+ plan = {"plan_steps": ["Analyze files", "Create notebook if requested", "Synthesize answers"], "experiment_needed": False}
360
+ # normalize experiment type
361
+ exp_type_raw = plan.get('experiment_type') or ""
362
+ plan_goal = plan.get('experiment_goal') or state.get('userInput','') or state.get('coreObjectivePrompt','')
363
+ normalized = normalize_experiment_type(exp_type_raw, plan_goal)
364
+ plan['experiment_type'] = normalized
365
+ if plan.get('experiment_needed') and not plan.get('experiment_goal'):
366
+ plan['experiment_goal'] = plan_goal
367
+ log.info(f"Generated Plan: Experiment Needed = {plan.get('experiment_needed', False)}, Type = {plan.get('experiment_type')}")
368
+ return {"pmPlan": plan, "execution_path": path, "rework_cycles": current_cycles, "status_update": "Breaking down the objective into a detailed plan..."}
369
+
370
+ def _extract_code_blocks(text: str, lang_hint: Optional[str]=None) -> List[str]:
371
+ # prefer specific language fences, fallback to generic fenced blocks
372
+ if lang_hint and "python" in (lang_hint or "").lower():
373
+ blocks = re.findall(r"```python\s*(.*?)\s*```", text, re.DOTALL)
374
+ if blocks:
375
+ return blocks
376
+ blocks = re.findall(r"```(?:\w+)?\s*(.*?)\s*```", text, re.DOTALL)
377
+ return blocks
378
 
379
  def run_experimenter_agent(state: AgentState):
380
+ log.info("--- 🔬 Running Experimenter Agent ---")
381
  path = ensure_list(state, 'execution_path') + ["Experimenter Agent"]
382
+ pm = state.get('pmPlan', {}) or {}
383
+ if not pm.get('experiment_needed'):
384
+ return {"experimentCode": None, "experimentResults": None, "execution_path": path, "status_update": "Proceeding without a code experiment."}
385
+ exp_type = normalize_experiment_type(pm.get('experiment_type'), pm.get('experiment_goal',''))
386
+ goal = pm.get('experiment_goal', 'No goal specified.')
387
+ response = llm.invoke(
388
+ f"Produce content for artifact type '{exp_type}' to achieve: {goal}\n"
389
+ "Return runnable code in fenced code blocks where appropriate, and explanatory text otherwise."
390
+ )
391
+ llm_text = getattr(response, "content", "") or ""
392
+ out_dir = OUT_DIR
393
+ results = {"success": False, "paths": {}, "stderr": "", "stdout": ""}
394
+ try:
395
+ if exp_type == 'notebook':
396
+ nb_path = write_notebook_from_text(llm_text, out_dir=out_dir)
397
+ results.update({"success": True, "paths": {"notebook": sanitize_path(nb_path)}})
398
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Notebook generated at {nb_path}"}
399
+ elif exp_type == 'excel':
400
+ excel_path = write_excel_from_tables(llm_text, out_dir=out_dir)
401
+ results.update({"success": True, "paths": {"excel": sanitize_path(excel_path)}})
402
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Excel generated at {excel_path}"}
403
+ elif exp_type == 'word':
404
+ docx_path = write_docx_from_text(llm_text, out_dir=out_dir)
405
+ results.update({"success": True, "paths": {"docx": sanitize_path(docx_path)}})
406
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"DOCX generated at {docx_path}"}
407
+ elif exp_type == 'pdf':
408
+ pdf_path = write_pdf_from_text(llm_text, out_dir=out_dir)
409
+ results.update({"success": True, "paths": {"pdf": sanitize_path(pdf_path)}})
410
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"PDF generated at {pdf_path}"}
411
+ elif exp_type == 'script':
412
+ lang_hint = pm.get('experiment_language') or ("python" if ".py" in goal.lower() else None)
413
+ code_blocks = _extract_code_blocks(llm_text, lang_hint)
414
+ if not code_blocks:
415
+ code_text = llm_text
416
+ else:
417
+ code_text = "\n\n# === BLOCK ===\n\n".join(code_blocks)
418
+ script_path = write_script(code_text, language_hint=lang_hint, out_dir=out_dir)
419
+ exec_results = {}
420
+ if script_path.endswith(".py"):
421
+ try:
422
+ exec_results = execute_python_code(open(script_path,"r",encoding="utf-8").read())
423
+ except Exception as e:
424
+ exec_results = {"stdout":"","stderr":str(e),"success":False}
425
+ results.update({"success": True, "paths": {"script": sanitize_path(script_path)}, "stdout": exec_results.get("stdout",""), "stderr": exec_results.get("stderr","")})
426
+ return {"experimentCode": code_text, "experimentResults": results, "execution_path": path, "status_update": f"Script generated at {script_path}"}
427
+ elif exp_type == 'repo':
428
+ repo_files = {}
429
+ readme = (llm_text[:1000] + "\n\n") if llm_text else "Generated repo"
430
+ repo_files["README.md"] = readme
431
+ nb_path = write_notebook_from_text(llm_text, out_dir=out_dir)
432
+ repo_files["analysis.ipynb"] = nb_path
433
+ reqs = "nbformat\npandas\nopenpyxl\npython-docx\nreportlab"
434
+ repo_files["requirements.txt"] = reqs
435
+ zip_path = build_repo_zip(repo_files, repo_name="generated_app", out_dir=out_dir)
436
+ results.update({"success": True, "paths": {"repo_zip": sanitize_path(zip_path)}})
437
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Repository ZIP created at {zip_path}"}
438
+ else:
439
+ # safe fallback: write docx
440
+ fallback = write_docx_from_text(llm_text, out_dir=out_dir)
441
+ results.update({"success": True, "paths": {"docx": sanitize_path(fallback)}})
442
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Fallback DOCX generated at {fallback}"}
443
+ except Exception as e:
444
+ log.error(f"Experimenter failed: {e}")
445
+ results.update({"success": False, "stderr": str(e)})
446
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": "Error: Experimenter failed."}
447
 
448
  def run_synthesis_agent(state: AgentState):
449
+ log.info("--- ✍️ Running Synthesis Agent ---")
450
+
451
+ # FIX: Defensively ensure state is a dictionary-like object to prevent AttributeError if state is None
452
+ _state = state or {}
453
+
454
+ path = ensure_list(_state, 'execution_path') + ["Synthesis Agent"]
455
+ exp_results = _state.get('experimentResults')
456
+ results_summary = "No experiment was conducted."
457
+ artifact_message = ""
458
+
459
+ if exp_results and isinstance(exp_results, dict):
460
+ paths = exp_results.get("paths") or {}
461
+ if paths:
462
+ artifact_lines = []
463
+ for k,v in paths.items():
464
+ artifact_lines.append(f"- {k}: `{v}`")
465
+ artifact_message = "\n\n**Artifacts produced:**\n" + "\n".join(artifact_lines)
466
+ results_summary = f"Artifacts produced: {list(paths.keys())}"
467
+ else:
468
+ results_summary = f"Experiment Output Stdout: {exp_results.get('stdout','')}\nStderr: {exp_results.get('stderr','')}"
469
+
470
+ prompt = (
471
+ f"Synthesize all information into a final response.\n\nCore Objective: {_state.get('coreObjectivePrompt', '')}\n\n"
472
+ f"Plan: {_state.get('pmPlan', {}).get('plan_steps')}\n\n{results_summary}\n\nFinal Response:"
473
+ )
474
+
475
+ response = llm.invoke(prompt)
476
+ final_text = getattr(response, "content", "") or ""
477
+ if artifact_message:
478
+ final_text = final_text + "\n\n" + artifact_message
479
+
480
+ return {"draftResponse": final_text, "execution_path": path, "status_update": "Putting together the final response..."}
481
 
482
  def run_qa_agent(state: AgentState):
483
  log.info("--- ✅ Running QA Agent ---")
484
  path = ensure_list(state, 'execution_path') + ["QA Agent"]
485
+ prompt = (f"Review the draft response based on the core objective. Respond ONLY with 'APPROVED' or provide concise feedback for rework.\n\n"
486
+ f"Core Objective: {state.get('coreObjectivePrompt')}\n\nDraft: {state.get('draftResponse')}")
487
+ response = llm.invoke(prompt)
488
+ content = getattr(response, "content", "") or ""
489
+ if "APPROVED" in content.upper():
490
+ return {"approved": True, "qaFeedback": None, "execution_path": path, "status_update": "Response approved!"}
491
+ else:
492
+ return {"approved": False, "qaFeedback": content or "No specific feedback.", "execution_path": path, "status_update": "Response needs improvement. Reworking..."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
493
 
494
  def run_archivist_agent(state: AgentState):
495
+ log.info("--- 💾 Running Archivist Agent ---")
496
  path = ensure_list(state, 'execution_path') + ["Archivist Agent"]
497
+ summary_prompt = (f"Create a concise summary of this successful task for long-term memory.\n\n"
498
+ f"Core Objective: {state.get('coreObjectivePrompt')}\n\nFinal Response: {state.get('draftResponse')}\n\nMemory Summary:")
499
+ response = llm.invoke(summary_prompt)
500
+ memory_manager.add_to_memory(getattr(response,"content",""), {"objective": state.get('coreObjectivePrompt')})
501
+ return {"execution_path": path, "status_update": "Saving key learnings for future reference..."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
 
503
  def run_disclaimer_agent(state: AgentState):
504
+ log.warning("--- ⚠️ Running Disclaimer Agent ---")
505
  path = ensure_list(state, 'execution_path') + ["Disclaimer Agent"]
506
+ disclaimer = ("**DISCLAIMER: The process was stopped after exhausting the budget. The following response is the best available draft and may be incomplete.**\n\n---\n\n")
507
+ final_response = disclaimer + state.get('draftResponse', "No response was generated.")
508
+ return {"draftResponse": final_response, "execution_path": path, "status_update": "Budget limit reached. Preparing final draft..."}
509
+
510
+ # --- Decision & Graph ---
511
+ def should_continue(state: AgentState):
512
+ log.info("--- 🤔 Decision: Is the response QA approved? ---")
513
+ if state.get("approved"):
514
+ log.info("Routing to: Archivist (Success Path)")
515
+ return "archivist_agent"
516
+ if ensure_int(state, "rework_cycles", 0) > ensure_int(state, "max_loops", 0):
517
+ log.error(f"BUDGET LIMIT REACHED after {ensure_int(state, 'rework_cycles', 0)-1} cycles.")
518
+ return "disclaimer_agent"
519
+ else:
520
+ log.info("Routing to: PM Agent for rework")
521
+ return "pm_agent"
522
+
523
+ def should_run_experiment(state: AgentState):
524
+ pm = state.get('pmPlan', {}) or {}
525
+ return "experimenter_agent" if pm.get('experiment_needed') else "synthesis_agent"
526
+
527
+ # --- Build graphs ---
 
 
 
 
 
 
 
 
 
 
 
 
528
  triage_workflow = StateGraph(AgentState)
529
  triage_workflow.add_node("triage", run_triage_agent)
530
  triage_workflow.set_entry_point("triage")
531
  triage_workflow.add_edge("triage", END)
532
  triage_app = triage_workflow.compile()
533
 
 
534
  planner_workflow = StateGraph(AgentState)
535
  planner_workflow.add_node("planner", run_planner_agent)
536
  planner_workflow.set_entry_point("planner")
537
  planner_workflow.add_edge("planner", END)
538
  planner_app = planner_workflow.compile()
539
 
 
540
  main_workflow = StateGraph(AgentState)
541
  main_workflow.add_node("memory_retriever", run_memory_retrieval)
542
  main_workflow.add_node("intent_agent", run_intent_agent)
 
546
  main_workflow.add_node("qa_agent", run_qa_agent)
547
  main_workflow.add_node("archivist_agent", run_archivist_agent)
548
  main_workflow.add_node("disclaimer_agent", run_disclaimer_agent)
 
 
549
 
550
  main_workflow.set_entry_point("memory_retriever")
551
  main_workflow.add_edge("memory_retriever", "intent_agent")
552
  main_workflow.add_edge("intent_agent", "pm_agent")
 
 
 
 
 
553
  main_workflow.add_edge("experimenter_agent", "synthesis_agent")
554
  main_workflow.add_edge("synthesis_agent", "qa_agent")
555
+ main_workflow.add_edge("archivist_agent", END)
 
 
 
 
 
 
 
 
556
  main_workflow.add_edge("disclaimer_agent", END)
557
 
558
+ main_workflow.add_conditional_edges("pm_agent", should_run_experiment)
559
+ main_workflow.add_conditional_edges("qa_agent", should_continue, {
560
+ "archivist_agent": "archivist_agent",
561
+ "pm_agent": "pm_agent",
562
+ "disclaimer_agent": "disclaimer_agent"
563
+ })
564
  main_app = main_workflow.compile()