JatinAutonomousLabs commited on
Commit
6a52df5
·
verified ·
1 Parent(s): 6bd6e19

Update graph.py

Browse files
Files changed (1) hide show
  1. graph.py +260 -233
graph.py CHANGED
@@ -1,4 +1,4 @@
1
- # graph.py (final patched)
2
  import json
3
  import re
4
  import math
@@ -6,37 +6,53 @@ import os
6
  import uuid
7
  import shutil
8
  import zipfile
9
- from typing import TypedDict, List, Dict, Optional
10
  from langchain_openai import ChatOpenAI
11
  from langgraph.graph import StateGraph, END
12
  from memory_manager import memory_manager
13
  from code_executor import execute_python_code
14
  from logging_config import setup_logging, get_logger
15
 
16
- # Artifact libs
17
- import nbformat
18
- from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
19
- import pandas as pd
20
- from docx import Document
21
- from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
22
- from reportlab.lib.styles import getSampleStyleSheet
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # --- Helpers ---
25
- def ensure_list(state, key):
26
  """Return a list from state[key], default [] if missing/None/not-list."""
27
- v = state.get(key) if state else None
28
  if v is None:
29
  return []
30
  if isinstance(v, list):
31
  return v
32
  if isinstance(v, tuple):
33
  return list(v)
 
34
  return [v]
35
 
36
- def ensure_int(state, key, default=0):
37
  """Return an int from state[key], default if missing/invalid."""
38
  try:
39
- v = state.get(key) if state else None
40
  if v is None:
41
  return default
42
  return int(v)
@@ -44,8 +60,17 @@ def ensure_int(state, key, default=0):
44
  return default
45
 
46
  def sanitize_path(path: str) -> str:
47
- """Sanitize/normalize output path for return to UI."""
48
- return os.path.abspath(path)
 
 
 
 
 
 
 
 
 
49
 
50
  # --- Setup & constants ---
51
  setup_logging()
@@ -54,9 +79,10 @@ INITIAL_MAX_REWORK_CYCLES = 3
54
  GPT4O_INPUT_COST_PER_1K_TOKENS = 0.005
55
  GPT4O_OUTPUT_COST_PER_1K_TOKENS = 0.015
56
  AVG_TOKENS_PER_CALL = 2.0
 
57
 
58
- # --- AgentState ---
59
- class AgentState(TypedDict):
60
  userInput: str
61
  chatHistory: List[str]
62
  coreObjectivePrompt: str
@@ -76,14 +102,16 @@ class AgentState(TypedDict):
76
  llm = ChatOpenAI(model="gpt-4o", temperature=0.1, max_retries=3, request_timeout=60)
77
 
78
  def parse_json_from_llm(llm_output: str) -> Optional[dict]:
79
- """Robustly try to extract JSON object from LLM text."""
80
  try:
81
  if not llm_output:
82
  return None
 
83
  match = re.search(r"```json\s*({.*?})\s*```", llm_output, re.DOTALL)
84
  if match:
85
  json_str = match.group(1)
86
  else:
 
87
  start = llm_output.find('{')
88
  end = llm_output.rfind('}')
89
  if start == -1 or end == -1:
@@ -91,14 +119,14 @@ def parse_json_from_llm(llm_output: str) -> Optional[dict]:
91
  json_str = llm_output[start:end+1]
92
  return json.loads(json_str)
93
  except Exception as e:
94
- log.error(f"JSON parsing failed. Error: {e}. Raw head: {llm_output[:300]}")
95
  return None
96
 
97
- # --- Artifact detection & normalization ---
98
- KNOWN_ARTIFACT_TYPES = {"notebook","excel","word","pdf","image","repo","script"}
99
 
100
- def detect_requested_output_types(text: str) -> Dict:
101
- """Heuristic detect requested artifact type from text."""
102
  if not text:
103
  return {"requires_artifact": False, "artifact_type": None, "artifact_hint": None}
104
  t = text.lower()
@@ -108,65 +136,65 @@ def detect_requested_output_types(text: str) -> Dict:
108
  return {"requires_artifact": True, "artifact_type": "excel", "artifact_hint": "Excel/CSV file"}
109
  if any(k in t for k in ["word document", ".docx", "docx", "word file"]):
110
  return {"requires_artifact": True, "artifact_type": "word", "artifact_hint": "Word document (.docx)"}
111
- if any(k in t for k in ["pdf", "pdf file"]):
112
  return {"requires_artifact": True, "artifact_type": "pdf", "artifact_hint": "PDF document"}
113
- if any(k in t for k in ["image", "plot", "chart", "png", "jpg", "jpeg"]):
114
- return {"requires_artifact": True, "artifact_type": "image", "artifact_hint": "image/plot"}
115
  if any(k in t for k in ["repo", "repository", "app repo", "dockerfile", "requirements.txt", "package.json"]):
116
  return {"requires_artifact": True, "artifact_type": "repo", "artifact_hint": "application repository (zip)"}
117
- if any(k in t for k in [".py", "python script", "r script", ".R", ".r", "java", ".java", "javascript", ".js"]):
118
- return {"requires_artifact": True, "artifact_type": "script", "artifact_hint": "language script (py/r/java/js/etc.)"}
119
  return {"requires_artifact": False, "artifact_type": None, "artifact_hint": None}
120
 
121
  def normalize_experiment_type(exp_type: Optional[str], goal_text: str) -> str:
122
- """Map arbitrary LLM returned experiment_type into known set or infer from goal_text."""
123
- if not exp_type:
124
- detection = detect_requested_output_types(goal_text or "")
125
- return detection.get("artifact_type") or "docx"
126
- s = exp_type.strip().lower()
127
- # direct mapping heuristics
128
- if s in KNOWN_ARTIFACT_TYPES:
129
- return s
130
- # common synonyms
131
- if "notebook" in s or "ipynb" in s:
132
- return "notebook"
133
- if "excel" in s or "xlsx" in s or "spreadsheet" in s:
134
- return "excel"
135
- if "word" in s or "docx" in s:
136
- return "word"
137
- if "pdf" in s:
138
- return "pdf"
139
- if "repo" in s or "repository" in s or "app" in s:
140
- return "repo"
141
- if "script" in s or "python" in s or ".py" in s:
142
- return "script"
143
- # fallback to detection from goal
144
  detection = detect_requested_output_types(goal_text or "")
145
  return detection.get("artifact_type") or "docx"
146
 
147
- # --- Notebook & artifact builders ---
148
- def write_notebook_from_text(llm_text: str, out_dir: str="/tmp") -> str:
149
- code_blocks = re.findall(r"```python\s*(.*?)\s*```", llm_text, re.DOTALL)
150
- if not code_blocks:
151
- code_blocks = re.findall(r"```\s*(.*?)\s*```", llm_text, re.DOTALL)
152
- md_parts = re.split(r"```(?:python)?\s*.*?\s*```", llm_text, flags=re.DOTALL)
153
- nb = new_notebook()
154
- cells = []
155
- max_len = max(len(md_parts), len(code_blocks))
156
- for i in range(max_len):
157
- if i < len(md_parts) and md_parts[i].strip():
158
- cells.append(new_markdown_cell(md_parts[i].strip()))
159
- if i < len(code_blocks) and code_blocks[i].strip():
160
- cells.append(new_code_cell(code_blocks[i].strip()))
161
- if not cells:
162
- cells = [new_markdown_cell("# Notebook\n\nNo content parsed from LLM output.")]
163
- nb['cells'] = cells
164
  uid = uuid.uuid4().hex[:10]
165
  filename = os.path.join(out_dir, f"generated_notebook_{uid}.ipynb")
166
- nbformat.write(nb, filename)
167
- return filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
- def write_script(code_text: str, language_hint: Optional[str]=None, out_dir: str="/tmp") -> str:
 
170
  ext = ".txt"
171
  if language_hint:
172
  l = language_hint.lower()
@@ -174,79 +202,95 @@ def write_script(code_text: str, language_hint: Optional[str]=None, out_dir: str
174
  ext = ".py"
175
  elif l == "r" or l == ".r":
176
  ext = ".R"
177
- elif "java" in l or ".java" in l:
178
  ext = ".java"
179
- elif "javascript" in l or ".js" in l:
180
  ext = ".js"
181
  elif "bash" in l or "sh" in l:
182
  ext = ".sh"
183
  uid = uuid.uuid4().hex[:10]
184
  filename = os.path.join(out_dir, f"generated_script_{uid}{ext}")
185
- with open(filename, "w", encoding="utf-8") as f:
186
- f.write(code_text)
187
- return filename
188
-
189
- def write_docx_from_text(text: str, out_dir: str="/tmp") -> str:
190
- doc = Document()
191
- for para in [p.strip() for p in text.split("\n\n") if p.strip()]:
192
- doc.add_paragraph(para)
193
  uid = uuid.uuid4().hex[:10]
194
  filename = os.path.join(out_dir, f"generated_doc_{uid}.docx")
195
- doc.save(filename)
196
- return filename
 
 
 
 
 
 
197
 
198
- def write_excel_from_tables(maybe_table_text: str, out_dir: str="/tmp") -> str:
 
199
  uid = uuid.uuid4().hex[:10]
200
  filename = os.path.join(out_dir, f"generated_excel_{uid}.xlsx")
201
- try:
202
  try:
203
- parsed = json.loads(maybe_table_text)
 
 
 
 
 
204
  if isinstance(parsed, list):
205
  df = pd.DataFrame(parsed)
206
  elif isinstance(parsed, dict):
207
  df = pd.DataFrame([parsed])
208
  else:
209
- df = pd.DataFrame({"content":[str(maybe_table_text)]})
210
- except Exception:
211
- if "," in maybe_table_text or "\t" in maybe_table_text:
212
- from io import StringIO
213
- df = pd.read_csv(StringIO(maybe_table_text))
214
- else:
215
- df = pd.DataFrame({"content":[maybe_table_text]})
216
- df.to_excel(filename, index=False, engine="openpyxl")
217
- return filename
218
- except Exception as e:
219
- log.error(f"Excel creation failed: {e}")
220
- return write_docx_from_text(f"Failed to create excel. Error: {e}\n\nOriginal:\n{maybe_table_text}", out_dir=out_dir)
221
-
222
- def write_pdf_from_text(text: str, out_dir: str="/tmp") -> str:
 
 
 
 
 
223
  uid = uuid.uuid4().hex[:10]
224
  filename = os.path.join(out_dir, f"generated_doc_{uid}.pdf")
225
- try:
226
- doc = SimpleDocTemplate(filename)
227
- styles = getSampleStyleSheet()
228
- flowables = []
229
- for para in [p.strip() for p in text.split("\n\n") if p.strip()]:
230
- flowables.append(Paragraph(para.replace("\n","<br/>"), styles["Normal"]))
231
- flowables.append(Spacer(1, 8))
232
- doc.build(flowables)
233
- return filename
234
- except Exception as e:
235
- log.error(f"PDF creation failed: {e}")
236
- return write_docx_from_text(f"Failed to create PDF. Error: {e}\n\nOriginal:\n{text}", out_dir=out_dir)
237
-
238
- def build_repo_zip(files_map: Dict[str,str], repo_name: str="generated_app", out_dir: str="/tmp") -> str:
 
 
 
239
  uid = uuid.uuid4().hex[:8]
240
  repo_dir = os.path.join(out_dir, f"{repo_name}_{uid}")
241
  os.makedirs(repo_dir, exist_ok=True)
242
- for rel_path, content in files_map.items():
243
  dest = os.path.join(repo_dir, rel_path)
244
  os.makedirs(os.path.dirname(dest), exist_ok=True)
245
  if isinstance(content, str) and os.path.exists(content):
246
  shutil.copyfile(content, dest)
247
  else:
248
  with open(dest, "w", encoding="utf-8") as fh:
249
- fh.write(str(content))
250
  zip_path = os.path.join(out_dir, f"{repo_name}_{uid}.zip")
251
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
252
  for root, _, files in os.walk(repo_dir):
@@ -256,97 +300,91 @@ def build_repo_zip(files_map: Dict[str,str], repo_name: str="generated_app", out
256
  zf.write(full, arc)
257
  return zip_path
258
 
259
- # --- Node functions ---
260
  def run_triage_agent(state: AgentState):
261
- log.info("--- triage ---")
262
- prompt = f"Analyze the user input. Is it a simple conversational greeting or a task? Respond with 'greeting' or 'task'.\n\nUser Input: \"{state.get('userInput','')}\""
263
  response = llm.invoke(prompt)
264
  content = getattr(response, "content", "") or ""
265
- if 'greeting' in content.lower():
266
- log.info("Triage result: Simple Greeting.")
267
- return {"draftResponse": "Hello! How can I help you today?", "execution_path": ["Triage Agent"], "status_update": "Responding to greeting."}
268
- else:
269
- log.info("Triage result: Complex Task.")
270
- return {"execution_path": ["Triage Agent"], "status_update": "Request requires a plan. Proceeding..."}
271
 
272
  def run_planner_agent(state: AgentState):
273
- log.info("--- ✈️ Running Planner Agent ---")
274
  path = ensure_list(state, 'execution_path') + ["Planner Agent"]
275
  prompt = (
276
  f"Analyze the user's request. Provide a high-level plan and estimate the number of LLM calls for one loop. "
277
- f"User Request: \"{state.get('userInput','')}\". Respond in JSON with keys: 'plan' (list of strings), 'estimated_llm_calls_per_loop' (integer)."
278
  )
279
  response = llm.invoke(prompt)
280
  plan_data = parse_json_from_llm(getattr(response, "content", "") or "")
281
  if not plan_data:
282
- return {"pmPlan": {"error": "Failed to create a valid plan."}, "execution_path": path, "status_update": "Error: Could not create a plan."}
283
- calls_per_loop = plan_data.get('estimated_llm_calls_per_loop', 3)
 
284
  cost_per_loop = (calls_per_loop * AVG_TOKENS_PER_CALL) * ((GPT4O_INPUT_COST_PER_1K_TOKENS + GPT4O_OUTPUT_COST_PER_1K_TOKENS) / 2)
285
  estimated_cost = cost_per_loop * (INITIAL_MAX_REWORK_CYCLES + 1)
286
- plan_data['max_loops_initial'] = INITIAL_MAX_REWORK_CYCLES
287
  plan_data['estimated_cost_usd'] = round(estimated_cost, 2)
288
  plan_data['cost_per_loop_usd'] = max(0.01, round(cost_per_loop, 3))
289
- detection = detect_requested_output_types(state.get('userInput','') or state.get('coreObjectivePrompt','') or '')
290
- if detection.get('requires_artifact'):
 
291
  plan_data.setdefault('experiment_needed', True)
292
  plan_data.setdefault('experiment_type', detection.get('artifact_type'))
293
  plan_data.setdefault('experiment_goal', f"Produce an artifact: {detection.get('artifact_hint')}. {state.get('userInput','')}")
294
- log.info(f"Pre-flight Estimate: {plan_data}")
295
  return {"pmPlan": plan_data, "execution_path": path, "status_update": "Plan and cost estimate created. Awaiting approval."}
296
 
297
  def run_memory_retrieval(state: AgentState):
298
- log.info("--- 🧠 Accessing Long-Term Memory ---")
299
  path = ensure_list(state, 'execution_path') + ["Memory Retriever"]
300
- relevant_mems = memory_manager.retrieve_relevant_memories(state.get('userInput',''))
 
 
 
301
  if relevant_mems:
302
- context = "\n".join([f"Memory: {mem.page_content}" for mem in relevant_mems])
303
- log.info(f"Found {len(relevant_mems)} relevant memories.")
304
  else:
305
  context = "No relevant memories found."
306
- log.info(context)
307
  return {"retrievedMemory": context, "execution_path": path, "status_update": "Searching for relevant past information..."}
308
 
309
  def run_intent_agent(state: AgentState):
310
- log.info("--- 🎯 Running Intent Agent ---")
311
  path = ensure_list(state, 'execution_path') + ["Intent Agent"]
312
- 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:")
 
 
 
313
  response = llm.invoke(prompt)
314
- core_obj = getattr(response, "content", "") or ""
315
- detection = detect_requested_output_types(core_obj or state.get('userInput',''))
316
  extras = {}
317
  if detection.get('requires_artifact'):
318
  extras['artifact_detection'] = detection
319
  return {"coreObjectivePrompt": core_obj, **extras, "execution_path": path, "status_update": "Clarifying the main objective..."}
320
 
321
  def run_pm_agent(state: AgentState):
322
- log.info("--- 👷 Running PM Agent ---")
323
  current_cycles = ensure_int(state, 'rework_cycles', 0) + 1
324
  max_loops_val = ensure_int(state, 'max_loops', 0)
325
- log.info(f"Starting work cycle {current_cycles}/{max_loops_val + 1}")
326
  path = ensure_list(state, 'execution_path') + ["PM Agent"]
327
- feedback = f"QA Feedback (must be addressed): {state.get('qaFeedback')}" if state.get('qaFeedback') else ""
328
  prompt = (
329
  f"Decompose the core objective into a plan. Determine if code execution or artifact generation is needed and define the goal.\n\n"
330
  f"Core Objective: {state.get('coreObjectivePrompt')}\n\n{feedback}\n\n"
331
- f"Respond in JSON with keys: 'plan_steps' (list), 'experiment_needed' (bool), 'experiment_type' (optional string), and 'experiment_goal' (str if needed)."
332
  )
333
  response = llm.invoke(prompt)
334
  plan = parse_json_from_llm(getattr(response, "content", "") or "")
335
  if not plan:
336
- log.warning("PM Agent did not produce JSON — applying heuristic fallback.")
337
- plan = {"plan_steps": ["Analyze files", "Create notebook if requested", "Synthesize answers"], "experiment_needed": False}
338
- # normalize experiment type
339
  exp_type_raw = plan.get('experiment_type') or ""
340
- plan_goal = plan.get('experiment_goal') or state.get('userInput','') or state.get('coreObjectivePrompt','')
341
  normalized = normalize_experiment_type(exp_type_raw, plan_goal)
342
  plan['experiment_type'] = normalized
343
  if plan.get('experiment_needed') and not plan.get('experiment_goal'):
344
  plan['experiment_goal'] = plan_goal
345
- log.info(f"Generated Plan: Experiment Needed = {plan.get('experiment_needed', False)}, Type = {plan.get('experiment_type')}")
346
  return {"pmPlan": plan, "execution_path": path, "rework_cycles": current_cycles, "status_update": "Breaking down the objective into a detailed plan..."}
347
 
348
- def _extract_code_blocks(text: str, lang_hint: Optional[str]=None) -> List[str]:
349
- # prefer specific language fences, fallback to generic fenced blocks
350
  if lang_hint and "python" in (lang_hint or "").lower():
351
  blocks = re.findall(r"```python\s*(.*?)\s*```", text, re.DOTALL)
352
  if blocks:
@@ -355,143 +393,130 @@ def _extract_code_blocks(text: str, lang_hint: Optional[str]=None) -> List[str]:
355
  return blocks
356
 
357
  def run_experimenter_agent(state: AgentState):
358
- log.info("--- 🔬 Running Experimenter Agent ---")
359
  path = ensure_list(state, 'execution_path') + ["Experimenter Agent"]
360
- pm = state.get('pmPlan', {}) or {}
361
  if not pm.get('experiment_needed'):
362
- return {"experimentCode": None, "experimentResults": None, "execution_path": path, "status_update": "Proceeding without a code experiment."}
 
363
  exp_type = normalize_experiment_type(pm.get('experiment_type'), pm.get('experiment_goal',''))
364
- goal = pm.get('experiment_goal', 'No goal specified.')
365
- response = llm.invoke(
366
- f"Produce content for artifact type '{exp_type}' to achieve: {goal}\n"
367
- "Return runnable code in fenced code blocks where appropriate, and explanatory text otherwise."
368
- )
369
  llm_text = getattr(response, "content", "") or ""
370
- out_dir = "/tmp"
371
- results = {"success": False, "paths": {}, "stderr": "", "stdout": ""}
372
  try:
373
- if exp_type == 'notebook':
374
- nb_path = write_notebook_from_text(llm_text, out_dir=out_dir)
375
  results.update({"success": True, "paths": {"notebook": sanitize_path(nb_path)}})
376
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Notebook generated at {nb_path}"}
377
- elif exp_type == 'excel':
378
- excel_path = write_excel_from_tables(llm_text, out_dir=out_dir)
379
  results.update({"success": True, "paths": {"excel": sanitize_path(excel_path)}})
380
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Excel generated at {excel_path}"}
381
- elif exp_type == 'word':
382
- docx_path = write_docx_from_text(llm_text, out_dir=out_dir)
383
  results.update({"success": True, "paths": {"docx": sanitize_path(docx_path)}})
384
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"DOCX generated at {docx_path}"}
385
- elif exp_type == 'pdf':
386
- pdf_path = write_pdf_from_text(llm_text, out_dir=out_dir)
387
  results.update({"success": True, "paths": {"pdf": sanitize_path(pdf_path)}})
388
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"PDF generated at {pdf_path}"}
389
- elif exp_type == 'script':
390
- lang_hint = pm.get('experiment_language') or ("python" if ".py" in goal.lower() else None)
391
  code_blocks = _extract_code_blocks(llm_text, lang_hint)
392
- if not code_blocks:
393
- code_text = llm_text
394
- else:
395
- code_text = "\n\n# === BLOCK ===\n\n".join(code_blocks)
396
- script_path = write_script(code_text, language_hint=lang_hint, out_dir=out_dir)
397
  exec_results = {}
398
  if script_path.endswith(".py"):
399
  try:
400
  exec_results = execute_python_code(open(script_path,"r",encoding="utf-8").read())
401
  except Exception as e:
402
- exec_results = {"stdout":"","stderr":str(e),"success":False}
403
  results.update({"success": True, "paths": {"script": sanitize_path(script_path)}, "stdout": exec_results.get("stdout",""), "stderr": exec_results.get("stderr","")})
404
- return {"experimentCode": code_text, "experimentResults": results, "execution_path": path, "status_update": f"Script generated at {script_path}"}
405
- elif exp_type == 'repo':
406
- repo_files = {}
407
- readme = (llm_text[:1000] + "\n\n") if llm_text else "Generated repo"
408
- repo_files["README.md"] = readme
409
- nb_path = write_notebook_from_text(llm_text, out_dir=out_dir)
410
- repo_files["analysis.ipynb"] = nb_path
411
- reqs = "nbformat\npandas\nopenpyxl\npython-docx\nreportlab"
412
- repo_files["requirements.txt"] = reqs
413
- zip_path = build_repo_zip(repo_files, repo_name="generated_app", out_dir=out_dir)
414
  results.update({"success": True, "paths": {"repo_zip": sanitize_path(zip_path)}})
415
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Repository ZIP created at {zip_path}"}
416
- else:
417
- # safe fallback: write docx
418
- fallback = write_docx_from_text(llm_text, out_dir=out_dir)
419
- results.update({"success": True, "paths": {"docx": sanitize_path(fallback)}})
420
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Fallback DOCX generated at {fallback}"}
421
  except Exception as e:
422
- log.error(f"Experimenter failed: {e}")
423
  results.update({"success": False, "stderr": str(e)})
424
- return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": "Error: Experimenter failed."}
425
 
426
  def run_synthesis_agent(state: AgentState):
427
- log.info("--- ✍️ Running Synthesis Agent ---")
428
  path = ensure_list(state, 'execution_path') + ["Synthesis Agent"]
429
- exp_results = state.get('experimentResults')
430
- results_summary = "No experiment was conducted."
431
  artifact_message = ""
432
  if exp_results and isinstance(exp_results, dict):
433
  paths = exp_results.get("paths") or {}
434
  if paths:
435
- artifact_lines = []
436
- for k,v in paths.items():
437
- artifact_lines.append(f"- {k}: `{v}`")
438
  artifact_message = "\n\n**Artifacts produced:**\n" + "\n".join(artifact_lines)
439
- results_summary = f"Artifacts produced: {list(paths.keys())}"
440
- else:
441
- results_summary = f"Experiment Output Stdout: {exp_results.get('stdout','')}\nStderr: {exp_results.get('stderr','')}"
442
  prompt = (
443
  f"Synthesize all information into a final response.\n\nCore Objective: {state.get('coreObjectivePrompt')}\n\n"
444
- f"Plan: {state.get('pmPlan', {}).get('plan_steps')}\n\n{results_summary}\n\nFinal Response:"
 
445
  )
446
  response = llm.invoke(prompt)
447
  final_text = getattr(response, "content", "") or ""
 
 
448
  if artifact_message:
449
  final_text = final_text + "\n\n" + artifact_message
450
  return {"draftResponse": final_text, "execution_path": path, "status_update": "Putting together the final response..."}
451
 
452
  def run_qa_agent(state: AgentState):
453
- log.info("--- ✅ Running QA Agent ---")
454
  path = ensure_list(state, 'execution_path') + ["QA Agent"]
455
- prompt = (f"Review the draft response based on the core objective. Respond ONLY with 'APPROVED' or provide concise feedback for rework.\n\n"
456
- f"Core Objective: {state.get('coreObjectivePrompt')}\n\nDraft: {state.get('draftResponse')}")
 
 
457
  response = llm.invoke(prompt)
458
  content = getattr(response, "content", "") or ""
459
  if "APPROVED" in content.upper():
460
  return {"approved": True, "qaFeedback": None, "execution_path": path, "status_update": "Response approved!"}
461
- else:
462
- return {"approved": False, "qaFeedback": content or "No specific feedback.", "execution_path": path, "status_update": "Response needs improvement. Reworking..."}
463
 
464
  def run_archivist_agent(state: AgentState):
465
- log.info("--- 💾 Running Archivist Agent ---")
466
  path = ensure_list(state, 'execution_path') + ["Archivist Agent"]
467
- summary_prompt = (f"Create a concise summary of this successful task for long-term memory.\n\n"
468
- f"Core Objective: {state.get('coreObjectivePrompt')}\n\nFinal Response: {state.get('draftResponse')}\n\nMemory Summary:")
469
- response = llm.invoke(summary_prompt)
470
- memory_manager.add_to_memory(getattr(response,"content",""), {"objective": state.get('coreObjectivePrompt')})
471
- return {"execution_path": path, "status_update": "Saving key learnings for future reference..."}
 
 
 
 
 
 
472
 
473
  def run_disclaimer_agent(state: AgentState):
474
- log.warning("--- ⚠️ Running Disclaimer Agent ---")
475
  path = ensure_list(state, 'execution_path') + ["Disclaimer Agent"]
476
- 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")
477
- final_response = disclaimer + state.get('draftResponse', "No response was generated.")
478
- return {"draftResponse": final_response, "execution_path": path, "status_update": "Budget limit reached. Preparing final draft..."}
479
 
480
- # --- Decision & Graph ---
481
  def should_continue(state: AgentState):
482
- log.info("--- 🤔 Decision: Is the response QA approved? ---")
483
  if state.get("approved"):
484
- log.info("Routing to: Archivist (Success Path)")
485
  return "archivist_agent"
486
  if ensure_int(state, "rework_cycles", 0) > ensure_int(state, "max_loops", 0):
487
- log.error(f"BUDGET LIMIT REACHED after {ensure_int(state, 'rework_cycles', 0)-1} cycles.")
488
  return "disclaimer_agent"
489
- else:
490
- log.info("Routing to: PM Agent for rework")
491
- return "pm_agent"
492
 
493
  def should_run_experiment(state: AgentState):
494
- pm = state.get('pmPlan', {}) or {}
495
  return "experimenter_agent" if pm.get('experiment_needed') else "synthesis_agent"
496
 
497
  # --- Build graphs ---
@@ -520,6 +545,8 @@ main_workflow.add_node("disclaimer_agent", run_disclaimer_agent)
520
  main_workflow.set_entry_point("memory_retriever")
521
  main_workflow.add_edge("memory_retriever", "intent_agent")
522
  main_workflow.add_edge("intent_agent", "pm_agent")
 
 
523
  main_workflow.add_edge("experimenter_agent", "synthesis_agent")
524
  main_workflow.add_edge("synthesis_agent", "qa_agent")
525
  main_workflow.add_edge("archivist_agent", END)
 
1
+ # graph.py (revised, robust)
2
  import json
3
  import re
4
  import math
 
6
  import uuid
7
  import shutil
8
  import zipfile
9
+ from typing import TypedDict, List, Dict, Optional, Any
10
  from langchain_openai import ChatOpenAI
11
  from langgraph.graph import StateGraph, END
12
  from memory_manager import memory_manager
13
  from code_executor import execute_python_code
14
  from logging_config import setup_logging, get_logger
15
 
16
+ # Artifact libs (optional — if not installed, artifact-writing functions will fallback to writing text)
17
+ try:
18
+ import nbformat
19
+ from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
20
+ except Exception:
21
+ nbformat = None
22
+
23
+ try:
24
+ import pandas as pd
25
+ except Exception:
26
+ pd = None
27
+
28
+ try:
29
+ from docx import Document
30
+ except Exception:
31
+ Document = None
32
+
33
+ try:
34
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
35
+ from reportlab.lib.styles import getSampleStyleSheet
36
+ except Exception:
37
+ SimpleDocTemplate = None
38
 
39
  # --- Helpers ---
40
+ def ensure_list(state: Optional[dict], key: str) -> List[Any]:
41
  """Return a list from state[key], default [] if missing/None/not-list."""
42
+ v = (state or {}).get(key)
43
  if v is None:
44
  return []
45
  if isinstance(v, list):
46
  return v
47
  if isinstance(v, tuple):
48
  return list(v)
49
+ # if e.g. a single string, keep as list
50
  return [v]
51
 
52
+ def ensure_int(state: Optional[dict], key: str, default: int = 0) -> int:
53
  """Return an int from state[key], default if missing/invalid."""
54
  try:
55
+ v = (state or {}).get(key)
56
  if v is None:
57
  return default
58
  return int(v)
 
60
  return default
61
 
62
  def sanitize_path(path: str) -> str:
63
+ """Return an absolute normalized path, safe for UI linking."""
64
+ try:
65
+ return os.path.abspath(path)
66
+ except Exception:
67
+ return path
68
+
69
+ def safe_write_text_file(text: str, out_path: str) -> str:
70
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
71
+ with open(out_path, "w", encoding="utf-8") as fh:
72
+ fh.write(text or "")
73
+ return out_path
74
 
75
  # --- Setup & constants ---
76
  setup_logging()
 
79
  GPT4O_INPUT_COST_PER_1K_TOKENS = 0.005
80
  GPT4O_OUTPUT_COST_PER_1K_TOKENS = 0.015
81
  AVG_TOKENS_PER_CALL = 2.0
82
+ OUT_DIR = "/tmp" # change if you want artifacts in a different place
83
 
84
+ # --- AgentState definition (non-total so keys optional) ---
85
+ class AgentState(TypedDict, total=False):
86
  userInput: str
87
  chatHistory: List[str]
88
  coreObjectivePrompt: str
 
102
  llm = ChatOpenAI(model="gpt-4o", temperature=0.1, max_retries=3, request_timeout=60)
103
 
104
  def parse_json_from_llm(llm_output: str) -> Optional[dict]:
105
+ """Robustly try to extract a single JSON object from LLM text."""
106
  try:
107
  if not llm_output:
108
  return None
109
+ # Prefer fenced json blocks
110
  match = re.search(r"```json\s*({.*?})\s*```", llm_output, re.DOTALL)
111
  if match:
112
  json_str = match.group(1)
113
  else:
114
+ # fallback: first {...}
115
  start = llm_output.find('{')
116
  end = llm_output.rfind('}')
117
  if start == -1 or end == -1:
 
119
  json_str = llm_output[start:end+1]
120
  return json.loads(json_str)
121
  except Exception as e:
122
+ log.debug(f"parse_json_from_llm failed: {e}. snippet: {str(llm_output)[:300]}")
123
  return None
124
 
125
+ # --- Artifact type detection & normalization ---
126
+ KNOWN_ARTIFACT_TYPES = {"notebook", "excel", "word", "pdf", "image", "repo", "script", "docx"}
127
 
128
+ def detect_requested_output_types(text: str) -> Dict[str, Optional[str]]:
129
+ """Simple heuristics to detect requested artifact types from user text."""
130
  if not text:
131
  return {"requires_artifact": False, "artifact_type": None, "artifact_hint": None}
132
  t = text.lower()
 
136
  return {"requires_artifact": True, "artifact_type": "excel", "artifact_hint": "Excel/CSV file"}
137
  if any(k in t for k in ["word document", ".docx", "docx", "word file"]):
138
  return {"requires_artifact": True, "artifact_type": "word", "artifact_hint": "Word document (.docx)"}
139
+ if "pdf" in t:
140
  return {"requires_artifact": True, "artifact_type": "pdf", "artifact_hint": "PDF document"}
 
 
141
  if any(k in t for k in ["repo", "repository", "app repo", "dockerfile", "requirements.txt", "package.json"]):
142
  return {"requires_artifact": True, "artifact_type": "repo", "artifact_hint": "application repository (zip)"}
143
+ if any(k in t for k in [".py", "python script", "r script", ".R", ".r", ".java", ".js"]):
144
+ return {"requires_artifact": True, "artifact_type": "script", "artifact_hint": "language script file"}
145
  return {"requires_artifact": False, "artifact_type": None, "artifact_hint": None}
146
 
147
  def normalize_experiment_type(exp_type: Optional[str], goal_text: str) -> str:
148
+ """Map arbitrary LLM experiment_type to a known artifact type; fallback to detection."""
149
+ if exp_type:
150
+ s = exp_type.strip().lower()
151
+ if s in KNOWN_ARTIFACT_TYPES:
152
+ return s
153
+ if "notebook" in s or "ipynb" in s:
154
+ return "notebook"
155
+ if "excel" in s or "xlsx" in s:
156
+ return "excel"
157
+ if "word" in s or "docx" in s:
158
+ return "word"
159
+ if "pdf" in s:
160
+ return "pdf"
161
+ if "repo" in s or "repository" in s:
162
+ return "repo"
163
+ if "script" in s or ".py" in s or "python" in s:
164
+ return "script"
 
 
 
 
 
165
  detection = detect_requested_output_types(goal_text or "")
166
  return detection.get("artifact_type") or "docx"
167
 
168
+ # --- Artifact writers (safe fallbacks) ---
169
+ def write_notebook_from_text(llm_text: str, out_dir: str = OUT_DIR) -> str:
170
+ """Create an .ipynb from free text/code blocks using nbformat if available."""
171
+ os.makedirs(out_dir, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  uid = uuid.uuid4().hex[:10]
173
  filename = os.path.join(out_dir, f"generated_notebook_{uid}.ipynb")
174
+ if nbformat:
175
+ code_blocks = re.findall(r"```python\s*(.*?)\s*```", llm_text, re.DOTALL)
176
+ generic_code = re.findall(r"```(?:\w+)?\s*(.*?)\s*```", llm_text, re.DOTALL)
177
+ # if language-specific code found, use that; otherwise use generic fenced blocks
178
+ code_blocks = code_blocks or generic_code
179
+ md_parts = re.split(r"```(?:\w+)?\s*.*?\s*```", llm_text, flags=re.DOTALL)
180
+ nb = new_notebook()
181
+ cells = []
182
+ max_len = max(len(md_parts), len(code_blocks))
183
+ for i in range(max_len):
184
+ if i < len(md_parts) and md_parts[i].strip():
185
+ cells.append(new_markdown_cell(md_parts[i].strip()))
186
+ if i < len(code_blocks) and code_blocks[i].strip():
187
+ cells.append(new_code_cell(code_blocks[i].strip()))
188
+ if not cells:
189
+ cells = [new_markdown_cell("# Notebook\nNo content parsed from LLM output.")]
190
+ nb["cells"] = cells
191
+ nbformat.write(nb, filename)
192
+ return filename
193
+ # fallback: write plain text file with .ipynb extension (so downloads still work)
194
+ return safe_write_text_file("# nbformat not installed\n\n" + (llm_text or ""), filename)
195
 
196
+ def write_script(code_text: str, language_hint: Optional[str] = None, out_dir: str = OUT_DIR) -> str:
197
+ os.makedirs(out_dir, exist_ok=True)
198
  ext = ".txt"
199
  if language_hint:
200
  l = language_hint.lower()
 
202
  ext = ".py"
203
  elif l == "r" or l == ".r":
204
  ext = ".R"
205
+ elif "java" in l:
206
  ext = ".java"
207
+ elif "javascript" in l or "js" in l:
208
  ext = ".js"
209
  elif "bash" in l or "sh" in l:
210
  ext = ".sh"
211
  uid = uuid.uuid4().hex[:10]
212
  filename = os.path.join(out_dir, f"generated_script_{uid}{ext}")
213
+ return safe_write_text_file(code_text or "", filename)
214
+
215
+ def write_docx_from_text(text: str, out_dir: str = OUT_DIR) -> str:
216
+ os.makedirs(out_dir, exist_ok=True)
 
 
 
 
217
  uid = uuid.uuid4().hex[:10]
218
  filename = os.path.join(out_dir, f"generated_doc_{uid}.docx")
219
+ if Document:
220
+ doc = Document()
221
+ for para in [p.strip() for p in (text or "").split("\n\n") if p.strip()]:
222
+ doc.add_paragraph(para)
223
+ doc.save(filename)
224
+ return filename
225
+ # fallback to txt file with .docx extension
226
+ return safe_write_text_file((text or ""), filename)
227
 
228
+ def write_excel_from_tables(maybe_table_text: str, out_dir: str = OUT_DIR) -> str:
229
+ os.makedirs(out_dir, exist_ok=True)
230
  uid = uuid.uuid4().hex[:10]
231
  filename = os.path.join(out_dir, f"generated_excel_{uid}.xlsx")
232
+ if pd:
233
  try:
234
+ # try JSON table first
235
+ parsed = None
236
+ try:
237
+ parsed = json.loads(maybe_table_text)
238
+ except Exception:
239
+ parsed = None
240
  if isinstance(parsed, list):
241
  df = pd.DataFrame(parsed)
242
  elif isinstance(parsed, dict):
243
  df = pd.DataFrame([parsed])
244
  else:
245
+ # try csv-like
246
+ if "," in (maybe_table_text or "") or "\t" in (maybe_table_text or ""):
247
+ from io import StringIO
248
+ df = pd.read_csv(StringIO(maybe_table_text))
249
+ else:
250
+ df = pd.DataFrame({"content": [maybe_table_text or ""]})
251
+ # write with engine openpyxl if available
252
+ try:
253
+ df.to_excel(filename, index=False, engine="openpyxl")
254
+ except Exception:
255
+ df.to_excel(filename, index=False)
256
+ return filename
257
+ except Exception as e:
258
+ log.debug(f"write_excel_from_tables failed: {e}")
259
+ return write_docx_from_text(f"Failed to create excel: {e}\n\nOriginal:\n{maybe_table_text}", out_dir=out_dir)
260
+ return write_docx_from_text(maybe_table_text, out_dir=out_dir)
261
+
262
+ def write_pdf_from_text(text: str, out_dir: str = OUT_DIR) -> str:
263
+ os.makedirs(out_dir, exist_ok=True)
264
  uid = uuid.uuid4().hex[:10]
265
  filename = os.path.join(out_dir, f"generated_doc_{uid}.pdf")
266
+ if SimpleDocTemplate:
267
+ try:
268
+ doc = SimpleDocTemplate(filename)
269
+ styles = getSampleStyleSheet()
270
+ flowables = []
271
+ for para in [p.strip() for p in (text or "").split("\n\n") if p.strip()]:
272
+ flowables.append(Paragraph(para.replace("\n", "<br/>"), styles["Normal"]))
273
+ flowables.append(Spacer(1, 8))
274
+ doc.build(flowables)
275
+ return filename
276
+ except Exception as e:
277
+ log.debug(f"write_pdf_from_text failed: {e}")
278
+ return write_docx_from_text(f"Failed to create PDF: {e}\n\nOriginal:\n{text}", out_dir=out_dir)
279
+ return write_docx_from_text(text, out_dir=out_dir)
280
+
281
+ def build_repo_zip(files_map: Dict[str, str], repo_name: str = "generated_app", out_dir: str = OUT_DIR) -> str:
282
+ os.makedirs(out_dir, exist_ok=True)
283
  uid = uuid.uuid4().hex[:8]
284
  repo_dir = os.path.join(out_dir, f"{repo_name}_{uid}")
285
  os.makedirs(repo_dir, exist_ok=True)
286
+ for rel_path, content in (files_map or {}).items():
287
  dest = os.path.join(repo_dir, rel_path)
288
  os.makedirs(os.path.dirname(dest), exist_ok=True)
289
  if isinstance(content, str) and os.path.exists(content):
290
  shutil.copyfile(content, dest)
291
  else:
292
  with open(dest, "w", encoding="utf-8") as fh:
293
+ fh.write(str(content or ""))
294
  zip_path = os.path.join(out_dir, f"{repo_name}_{uid}.zip")
295
  with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
296
  for root, _, files in os.walk(repo_dir):
 
300
  zf.write(full, arc)
301
  return zip_path
302
 
303
+ # --- Node functions (all robust) ---
304
  def run_triage_agent(state: AgentState):
305
+ path = ensure_list(state, 'execution_path') + ["Triage Agent"]
306
+ prompt = f"Analyze the user input. Is it a simple conversational greeting or a task? Respond with 'greeting' or 'task'.\n\nUser Input: \"{(state or {}).get('userInput','')}\""
307
  response = llm.invoke(prompt)
308
  content = getattr(response, "content", "") or ""
309
+ if "greeting" in content.lower():
310
+ return {"draftResponse": "Hello! How can I help you today?", "execution_path": path, "status_update": "Responding to greeting."}
311
+ return {"execution_path": path, "status_update": "Request requires a plan. Proceeding..."}
 
 
 
312
 
313
  def run_planner_agent(state: AgentState):
 
314
  path = ensure_list(state, 'execution_path') + ["Planner Agent"]
315
  prompt = (
316
  f"Analyze the user's request. Provide a high-level plan and estimate the number of LLM calls for one loop. "
317
+ f"User Request: \"{(state or {}).get('userInput','')}\". Respond in JSON with keys: 'plan' (list of strings), 'estimated_llm_calls_per_loop' (integer)."
318
  )
319
  response = llm.invoke(prompt)
320
  plan_data = parse_json_from_llm(getattr(response, "content", "") or "")
321
  if not plan_data:
322
+ plan_data = {"plan": ["Could not parse plan — defaulting minimal plan."], "estimated_llm_calls_per_loop": 3}
323
+ # cost math
324
+ calls_per_loop = int(plan_data.get('estimated_llm_calls_per_loop', 3))
325
  cost_per_loop = (calls_per_loop * AVG_TOKENS_PER_CALL) * ((GPT4O_INPUT_COST_PER_1K_TOKENS + GPT4O_OUTPUT_COST_PER_1K_TOKENS) / 2)
326
  estimated_cost = cost_per_loop * (INITIAL_MAX_REWORK_CYCLES + 1)
327
+ plan_data.setdefault('max_loops_initial', INITIAL_MAX_REWORK_CYCLES)
328
  plan_data['estimated_cost_usd'] = round(estimated_cost, 2)
329
  plan_data['cost_per_loop_usd'] = max(0.01, round(cost_per_loop, 3))
330
+ # If user requested artifact, set experiment flags
331
+ detection = detect_requested_output_types((state or {}).get('userInput','') or (state or {}).get('coreObjectivePrompt','') or "")
332
+ if detection.get("requires_artifact"):
333
  plan_data.setdefault('experiment_needed', True)
334
  plan_data.setdefault('experiment_type', detection.get('artifact_type'))
335
  plan_data.setdefault('experiment_goal', f"Produce an artifact: {detection.get('artifact_hint')}. {state.get('userInput','')}")
 
336
  return {"pmPlan": plan_data, "execution_path": path, "status_update": "Plan and cost estimate created. Awaiting approval."}
337
 
338
  def run_memory_retrieval(state: AgentState):
 
339
  path = ensure_list(state, 'execution_path') + ["Memory Retriever"]
340
+ try:
341
+ relevant_mems = memory_manager.retrieve_relevant_memories((state or {}).get('userInput',''))
342
+ except Exception:
343
+ relevant_mems = []
344
  if relevant_mems:
345
+ context = "\n".join([f"Memory: {getattr(mem,'page_content',str(mem))}" for mem in relevant_mems])
 
346
  else:
347
  context = "No relevant memories found."
 
348
  return {"retrievedMemory": context, "execution_path": path, "status_update": "Searching for relevant past information..."}
349
 
350
  def run_intent_agent(state: AgentState):
 
351
  path = ensure_list(state, 'execution_path') + ["Intent Agent"]
352
+ prompt = (
353
+ f"Refine the user's request into a clear, actionable 'core objective prompt'.\n\nRelevant Memory:\n{(state or {}).get('retrievedMemory')}\n\n"
354
+ f"User Request: \"{(state or {}).get('userInput','')}\"\n\nCore Objective:"
355
+ )
356
  response = llm.invoke(prompt)
357
+ core_obj = getattr(response, "content", "") or (state or {}).get('coreObjectivePrompt', "")
358
+ detection = detect_requested_output_types(core_obj or (state or {}).get('userInput',''))
359
  extras = {}
360
  if detection.get('requires_artifact'):
361
  extras['artifact_detection'] = detection
362
  return {"coreObjectivePrompt": core_obj, **extras, "execution_path": path, "status_update": "Clarifying the main objective..."}
363
 
364
  def run_pm_agent(state: AgentState):
365
+ # increment cycles safely
366
  current_cycles = ensure_int(state, 'rework_cycles', 0) + 1
367
  max_loops_val = ensure_int(state, 'max_loops', 0)
 
368
  path = ensure_list(state, 'execution_path') + ["PM Agent"]
369
+ feedback = f"QA Feedback: {state.get('qaFeedback')}" if state.get('qaFeedback') else ""
370
  prompt = (
371
  f"Decompose the core objective into a plan. Determine if code execution or artifact generation is needed and define the goal.\n\n"
372
  f"Core Objective: {state.get('coreObjectivePrompt')}\n\n{feedback}\n\n"
373
+ "Respond in JSON with keys: 'plan_steps' (list), 'experiment_needed' (bool), 'experiment_type' (optional), 'experiment_goal' (optional)."
374
  )
375
  response = llm.invoke(prompt)
376
  plan = parse_json_from_llm(getattr(response, "content", "") or "")
377
  if not plan:
378
+ plan = {"plan_steps": ["Analyze files", "If asked, generate artifact", "Synthesize results"], "experiment_needed": False}
 
 
379
  exp_type_raw = plan.get('experiment_type') or ""
380
+ plan_goal = plan.get('experiment_goal') or (state or {}).get('userInput','') or (state or {}).get('coreObjectivePrompt','')
381
  normalized = normalize_experiment_type(exp_type_raw, plan_goal)
382
  plan['experiment_type'] = normalized
383
  if plan.get('experiment_needed') and not plan.get('experiment_goal'):
384
  plan['experiment_goal'] = plan_goal
 
385
  return {"pmPlan": plan, "execution_path": path, "rework_cycles": current_cycles, "status_update": "Breaking down the objective into a detailed plan..."}
386
 
387
+ def _extract_code_blocks(text: str, lang_hint: Optional[str] = None) -> List[str]:
 
388
  if lang_hint and "python" in (lang_hint or "").lower():
389
  blocks = re.findall(r"```python\s*(.*?)\s*```", text, re.DOTALL)
390
  if blocks:
 
393
  return blocks
394
 
395
  def run_experimenter_agent(state: AgentState):
 
396
  path = ensure_list(state, 'execution_path') + ["Experimenter Agent"]
397
+ pm = (state or {}).get('pmPlan') or {}
398
  if not pm.get('experiment_needed'):
399
+ # return consistent shape: experimentResults.paths is empty dict
400
+ return {"experimentCode": None, "experimentResults": {"success": False, "paths": {}, "stdout": "", "stderr": ""}, "execution_path": path, "status_update": "No experiment required."}
401
  exp_type = normalize_experiment_type(pm.get('experiment_type'), pm.get('experiment_goal',''))
402
+ goal = pm.get('experiment_goal') or "Produce artifact"
403
+ response = llm.invoke(f"Produce content for artifact type '{exp_type}' to achieve: {goal}\nReturn runnable code in fenced code blocks where appropriate, and explanatory text otherwise.")
 
 
 
404
  llm_text = getattr(response, "content", "") or ""
405
+ results = {"success": False, "paths": {}, "stdout": "", "stderr": ""}
 
406
  try:
407
+ if exp_type == "notebook":
408
+ nb_path = write_notebook_from_text(llm_text, out_dir=OUT_DIR)
409
  results.update({"success": True, "paths": {"notebook": sanitize_path(nb_path)}})
410
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Notebook generated."}
411
+ if exp_type == "excel":
412
+ excel_path = write_excel_from_tables(llm_text, out_dir=OUT_DIR)
413
  results.update({"success": True, "paths": {"excel": sanitize_path(excel_path)}})
414
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Excel generated."}
415
+ if exp_type in ("word", "docx"):
416
+ docx_path = write_docx_from_text(llm_text, out_dir=OUT_DIR)
417
  results.update({"success": True, "paths": {"docx": sanitize_path(docx_path)}})
418
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"DOCX generated."}
419
+ if exp_type == "pdf":
420
+ pdf_path = write_pdf_from_text(llm_text, out_dir=OUT_DIR)
421
  results.update({"success": True, "paths": {"pdf": sanitize_path(pdf_path)}})
422
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"PDF generated."}
423
+ if exp_type == "script":
424
+ lang_hint = pm.get('experiment_language') or ("python" if ".py" in (pm.get('experiment_goal','') or "").lower() else None)
425
  code_blocks = _extract_code_blocks(llm_text, lang_hint)
426
+ code_text = "\n\n# === BLOCK ===\n\n".join(code_blocks) if code_blocks else llm_text
427
+ script_path = write_script(code_text, language_hint=lang_hint, out_dir=OUT_DIR)
 
 
 
428
  exec_results = {}
429
  if script_path.endswith(".py"):
430
  try:
431
  exec_results = execute_python_code(open(script_path,"r",encoding="utf-8").read())
432
  except Exception as e:
433
+ exec_results = {"stdout": "", "stderr": str(e), "success": False}
434
  results.update({"success": True, "paths": {"script": sanitize_path(script_path)}, "stdout": exec_results.get("stdout",""), "stderr": exec_results.get("stderr","")})
435
+ return {"experimentCode": code_text, "experimentResults": results, "execution_path": path, "status_update": f"Script generated."}
436
+ if exp_type == "repo":
437
+ files_map = {"README.md": llm_text or "Generated repo"}
438
+ try:
439
+ nb_path = write_notebook_from_text(llm_text, out_dir=OUT_DIR)
440
+ files_map["analysis.ipynb"] = open(nb_path,"r",encoding="utf-8").read() if os.path.exists(nb_path) else llm_text
441
+ except Exception:
442
+ files_map["analysis.ipynb"] = llm_text
443
+ files_map["requirements.txt"] = "nbformat\npandas\nopenpyxl\npython-docx\nreportlab"
444
+ zip_path = build_repo_zip(files_map, repo_name="generated_app", out_dir=OUT_DIR)
445
  results.update({"success": True, "paths": {"repo_zip": sanitize_path(zip_path)}})
446
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": f"Repository ZIP created."}
447
+ # fallback: write docx
448
+ fallback = write_docx_from_text(llm_text, out_dir=OUT_DIR)
449
+ results.update({"success": True, "paths": {"docx": sanitize_path(fallback)}})
450
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": "Fallback DOCX generated."}
 
451
  except Exception as e:
452
+ log.exception("Experimenter failed")
453
  results.update({"success": False, "stderr": str(e)})
454
+ return {"experimentCode": None, "experimentResults": results, "execution_path": path, "status_update": "Experimenter error."}
455
 
456
  def run_synthesis_agent(state: AgentState):
 
457
  path = ensure_list(state, 'execution_path') + ["Synthesis Agent"]
458
+ exp_results = (state or {}).get('experimentResults') or {}
 
459
  artifact_message = ""
460
  if exp_results and isinstance(exp_results, dict):
461
  paths = exp_results.get("paths") or {}
462
  if paths:
463
+ artifact_lines = [f"- {k}: `{v}`" for k,v in paths.items()]
 
 
464
  artifact_message = "\n\n**Artifacts produced:**\n" + "\n".join(artifact_lines)
 
 
 
465
  prompt = (
466
  f"Synthesize all information into a final response.\n\nCore Objective: {state.get('coreObjectivePrompt')}\n\n"
467
+ f"Plan: {state.get('pmPlan', {}).get('plan_steps')}\n\n"
468
+ f"{artifact_message}\n\nFinal Response:"
469
  )
470
  response = llm.invoke(prompt)
471
  final_text = getattr(response, "content", "") or ""
472
+ if not final_text.strip():
473
+ final_text = "I prepared the requested artifact(s). Please download them from the provided paths."
474
  if artifact_message:
475
  final_text = final_text + "\n\n" + artifact_message
476
  return {"draftResponse": final_text, "execution_path": path, "status_update": "Putting together the final response..."}
477
 
478
  def run_qa_agent(state: AgentState):
 
479
  path = ensure_list(state, 'execution_path') + ["QA Agent"]
480
+ prompt = (
481
+ f"Review the draft response based on the core objective. Respond ONLY with 'APPROVED' or provide concise feedback for rework.\n\n"
482
+ f"Core Objective: {state.get('coreObjectivePrompt')}\n\nDraft: {state.get('draftResponse','')}"
483
+ )
484
  response = llm.invoke(prompt)
485
  content = getattr(response, "content", "") or ""
486
  if "APPROVED" in content.upper():
487
  return {"approved": True, "qaFeedback": None, "execution_path": path, "status_update": "Response approved!"}
488
+ return {"approved": False, "qaFeedback": content or "No specific feedback.", "execution_path": path, "status_update": "Response needs rework."}
 
489
 
490
  def run_archivist_agent(state: AgentState):
 
491
  path = ensure_list(state, 'execution_path') + ["Archivist Agent"]
492
+ prompt = (
493
+ f"Create a concise summary of this successful task for long-term memory.\n\n"
494
+ f"Core Objective: {state.get('coreObjectivePrompt')}\n\nFinal Response: {state.get('draftResponse')}\n\nMemory Summary:"
495
+ )
496
+ response = llm.invoke(prompt)
497
+ memory_text = getattr(response, "content", "") or state.get('draftResponse','') or ""
498
+ try:
499
+ memory_manager.add_to_memory(memory_text, {"objective": state.get('coreObjectivePrompt')})
500
+ except Exception:
501
+ log.debug("Failed to write memory; continuing.")
502
+ return {"execution_path": path, "status_update": "Saved learnings to memory."}
503
 
504
  def run_disclaimer_agent(state: AgentState):
 
505
  path = ensure_list(state, 'execution_path') + ["Disclaimer Agent"]
506
+ disclaimer = ("**DISCLAIMER: The process was stopped after exhausting the budget. The following response may be incomplete.**\n\n---\n\n")
507
+ final_response = disclaimer + (state.get('draftResponse') or "No response was generated.")
508
+ return {"draftResponse": final_response, "execution_path": path, "status_update": "Budget limit reached."}
509
 
510
+ # --- Decision functions ---
511
  def should_continue(state: AgentState):
 
512
  if state.get("approved"):
 
513
  return "archivist_agent"
514
  if ensure_int(state, "rework_cycles", 0) > ensure_int(state, "max_loops", 0):
 
515
  return "disclaimer_agent"
516
+ return "pm_agent"
 
 
517
 
518
  def should_run_experiment(state: AgentState):
519
+ pm = (state or {}).get('pmPlan') or {}
520
  return "experimenter_agent" if pm.get('experiment_needed') else "synthesis_agent"
521
 
522
  # --- Build graphs ---
 
545
  main_workflow.set_entry_point("memory_retriever")
546
  main_workflow.add_edge("memory_retriever", "intent_agent")
547
  main_workflow.add_edge("intent_agent", "pm_agent")
548
+ # add direct edges; conditional edges override routing internally
549
+ main_workflow.add_edge("pm_agent", "experimenter_agent")
550
  main_workflow.add_edge("experimenter_agent", "synthesis_agent")
551
  main_workflow.add_edge("synthesis_agent", "qa_agent")
552
  main_workflow.add_edge("archivist_agent", END)