Skip to content

Commit af4b907

Browse files
rlafurudReokyoungKimclaude
authored
Remove unused verify/refine analyst code from script_builder (#13)
The simplified build drops the analyst/verify loop, leaving verify_script, refine_script, _log_feedback, check_script_validity (and REFINE_SCRIPT_PROMPT) as dead code. Remove them. Graph build + import verified. Closes #11 Co-authored-by: ReokyoungKim <zmffhem1207@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent a5cd42a commit af4b907

1 file changed

Lines changed: 1 addition & 151 deletions

File tree

backend/script_builder.py

Lines changed: 1 addition & 151 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from langchain_core.output_parsers import JsonOutputParser, StrOutputParser
1010
from dotenv import load_dotenv
1111
from pathlib import Path
12-
from developer_prompt import SELECT_MAP_PROMPT, PLACE_UNITS_PROMPT, RULE_CONFIG_PROMPT, GET_CONDITION_PROMPT, REFINE_SCRIPT_PROMPT
12+
from developer_prompt import SELECT_MAP_PROMPT, PLACE_UNITS_PROMPT, RULE_CONFIG_PROMPT, GET_CONDITION_PROMPT
1313
from db_call import DBCall
1414

1515
import common
@@ -413,156 +413,6 @@ def assemble_draft(self, state: ScriptDeveloperState) -> Dict:
413413
"loop_count": 1 # Start at 1 so initial verify + MAX_LOOPS-1 refines = 3 total
414414
}
415415

416-
def verify_script(self, state: ScriptDeveloperState) -> Dict:
417-
print("\n Verifying Script with Analyst...")
418-
current_json = state.get("final_json", {})
419-
420-
analyst_input_state = {
421-
"current_script": current_json,
422-
"current_phase": "compiler",
423-
"loop_count": state.get("loop_count", 0),
424-
"target_diffs": state.get("refined_diffs", None)
425-
}
426-
427-
try:
428-
# Call Analyst's verification logic
429-
result = self.analyst.verify_script(analyst_input_state)
430-
431-
is_valid = result.get("game_script_valid", False)
432-
feedback_list = result.get("game_script_feedback", [])
433-
434-
# Format feedback for LLM if it's a list
435-
feedback_str = "\n".join(feedback_list) if isinstance(feedback_list, list) else str(feedback_list)
436-
437-
if is_valid:
438-
print(" ✅ Analyst: Script is VALID.")
439-
# Log successful validation
440-
self._log_feedback(
441-
feedback="Script validation passed",
442-
is_valid=True,
443-
loop_count=state.get("loop_count", 0),
444-
step_num=getattr(self, 'current_step_num', None)
445-
)
446-
else:
447-
print(f" ❌ Analyst: Script is INVALID.\n Errors: {feedback_str}")
448-
# Log failed validation
449-
self._log_feedback(
450-
feedback=feedback_str,
451-
is_valid=False,
452-
loop_count=state.get("loop_count", 0),
453-
step_num=getattr(self, 'current_step_num', None)
454-
)
455-
456-
return {
457-
"is_script_valid": is_valid,
458-
"script_feedback": feedback_str
459-
}
460-
461-
except Exception as e:
462-
print(f" ⚠️ Analyst Verification Error: {e}")
463-
return {"is_script_valid": False, "script_feedback": str(e)}
464-
465-
def refine_script(self, state: ScriptDeveloperState) -> Dict:
466-
print("\n[ScriptDev] 🔧 Refining Script...")
467-
468-
current_json = state.get("final_json", {})
469-
feedback = state.get("script_feedback", "")
470-
user_intent = state.get("user_intent", "")
471-
loop_count = state.get("loop_count", 0) + 1
472-
473-
# Single difficulty — always refine "normal"
474-
failed_diffs = {"normal"}
475-
476-
prompt = ChatPromptTemplate.from_messages([
477-
("system", REFINE_SCRIPT_PROMPT),
478-
("user", """
479-
[User Intent]: {user_intent}
480-
[Error Feedback]: {feedback}
481-
[Current JSON]: {current_json}
482-
""")
483-
])
484-
chain = prompt | self.client | self.parser
485-
486-
merged_json = dict(current_json)
487-
any_fixed = False
488-
489-
for diff in failed_diffs:
490-
if diff not in current_json:
491-
continue
492-
diff_feedback = "\n".join(
493-
line for line in feedback.splitlines()
494-
if f"[{diff.upper()}]" in line.upper() or f"[{diff}]" in line.lower()
495-
) or feedback # fallback to full feedback if no per-diff lines
496-
497-
print(f" Fixing [{diff.upper()}]...")
498-
try:
499-
fixed = chain.invoke({
500-
"user_intent": user_intent,
501-
"feedback": diff_feedback,
502-
"current_json": json.dumps(current_json[diff], ensure_ascii=False)
503-
})
504-
if isinstance(fixed, dict):
505-
merged_json[diff] = fixed
506-
any_fixed = True
507-
print(f" ✅ [{diff.upper()}] Fixed")
508-
else:
509-
print(f" ⚠️ [{diff.upper()}] LLM returned non-dict, skipping")
510-
except Exception as e:
511-
print(f" ❌ [{diff.upper()}] Fix failed: {e}")
512-
513-
if any_fixed:
514-
print(f" ✅ Script Refined (Loop {loop_count})")
515-
else:
516-
print(f" ⚠️ No difficulties were fixed (Loop {loop_count})")
517-
518-
return {
519-
"final_json": merged_json,
520-
"loop_count": loop_count,
521-
"is_script_valid": False,
522-
"refined_diffs": list(failed_diffs)
523-
}
524-
525-
def _log_feedback(self, feedback: str, is_valid: bool, loop_count: int, step_num: int = None):
526-
"""Log feedback for script validation/refinement."""
527-
feedback_entry = {
528-
"timestamp": datetime.datetime.now().isoformat(),
529-
"source": "script_developer",
530-
"phase": "script_developer",
531-
"loop_count": loop_count,
532-
"is_valid": is_valid,
533-
"feedback": feedback
534-
}
535-
if step_num is not None:
536-
feedback_entry["step_num"] = step_num
537-
538-
self.feedback_logs.append(feedback_entry)
539-
540-
# Save immediately
541-
try:
542-
with open(self.feedback_log_path, "w", encoding="utf-8") as f:
543-
json.dump(self.feedback_logs, f, indent=2, ensure_ascii=False)
544-
except Exception as e:
545-
print(f" ⚠️ Failed to save feedback log: {e}")
546-
547-
def check_script_validity(self, state: ScriptDeveloperState):
548-
is_valid = state.get("is_script_valid", False)
549-
loop_count = state.get("loop_count", 0)
550-
MAX_LOOPS = 3
551-
552-
if is_valid:
553-
return "valid"
554-
elif loop_count >= MAX_LOOPS:
555-
print(f" ⚠️ Max refine loops ({MAX_LOOPS}) reached. Returning to router.")
556-
self._log_feedback(
557-
feedback=f"Max refine loops ({MAX_LOOPS}) reached — returning to router",
558-
is_valid=False,
559-
loop_count=loop_count,
560-
step_num=getattr(self, 'current_step_num', None)
561-
)
562-
return "max_retries"
563-
else:
564-
return "invalid"
565-
566416
def run(self, user_intent: str, gdd: Dict, meta_feedback: str = None, step_num: int = None) -> Dict[str, Any]:
567417
self.current_step_num = step_num # Store for use in other methods
568418
print(f"\n[ScriptDev] 🚀 Starting Script Generation Workflow for: '{user_intent}' (Step {step_num})")

0 commit comments

Comments
 (0)