|
| 1 | +""" |
| 2 | +ExplainerAgent — full-state returns, collision-safe |
| 3 | +- Returns a full state dict but NEVER writes 'code' back to the graph. |
| 4 | +- Uses PromptManager if available; otherwise falls back to an inline prompt. |
| 5 | +""" |
| 6 | +from __future__ import annotations |
| 7 | +from typing import Dict, Any |
| 8 | +import json |
| 9 | + |
| 10 | +from langchain_core.language_models import BaseLanguageModel |
| 11 | +from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder |
| 12 | +from langchain_core.prompts import PromptTemplate |
| 13 | +from ..prompt import PromptManager |
| 14 | +from src.core.utils import extract_first_json |
| 15 | + |
| 16 | +PROMPT_KEY = "explainer" |
| 17 | + |
| 18 | + |
| 19 | +class ExplainerAgent: |
| 20 | + def __init__(self, llm: BaseLanguageModel, prompt_manager: PromptManager): |
| 21 | + self.llm = llm |
| 22 | + self.prompt_manager = prompt_manager |
| 23 | + |
| 24 | + # Merge helper: return a FULL state but drop keys we must not rewrite. |
| 25 | + @staticmethod |
| 26 | + def _merge_return_state(state: Dict[str, Any], updates: Dict[str, Any], drop_keys=("code",)) -> Dict[str, Any]: |
| 27 | + merged = dict(state) |
| 28 | + # don't write to LastValue 'code' to avoid concurrent updates |
| 29 | + for k in drop_keys: |
| 30 | + if k in merged: |
| 31 | + merged.pop(k) |
| 32 | + merged.update(updates or {}) |
| 33 | + return merged |
| 34 | + |
| 35 | + def explain_antipattern(self, state: Dict[str, Any]) -> Dict[str, Any]: |
| 36 | + """Generate explanation JSON for detected antipatterns and refactor.""" |
| 37 | + print("Preparing to Explain...") |
| 38 | + kwargs = dict( |
| 39 | + code=state.get("code", ""), |
| 40 | + context=state.get("context", ""), |
| 41 | + refactored_code=state.get("refactored_code", ""), |
| 42 | + refactoring_strategy=state.get("refactoring_strategy_results", ""), |
| 43 | + antipattern_name=state.get("antipatterns_scanner_results", "Unknown antipattern"), |
| 44 | + antipatterns_json=json.dumps(state.get("antipatterns_json", []), ensure_ascii=False), |
| 45 | + msgs=state.get("msgs", []), |
| 46 | + ) |
| 47 | + |
| 48 | + messages = self._build_messages(**kwargs) |
| 49 | + |
| 50 | + try: |
| 51 | + response = self.llm.invoke(messages) |
| 52 | + raw = getattr(response, "content", None) or str(response) |
| 53 | + except Exception as e: |
| 54 | + raw = f"LLM error: {e}" |
| 55 | + |
| 56 | + # Robust parse |
| 57 | + try: |
| 58 | + parsed = extract_first_json(raw) |
| 59 | + except Exception: |
| 60 | + parsed = None |
| 61 | + |
| 62 | + if isinstance(parsed, dict): |
| 63 | + exp_json = parsed |
| 64 | + elif isinstance(parsed, list): |
| 65 | + exp_json = {"items": parsed} |
| 66 | + else: |
| 67 | + exp_json = self._fallback_payload(state) |
| 68 | + |
| 69 | + updates = { |
| 70 | + "explanation_response_raw": raw, |
| 71 | + "explanation_json": exp_json, |
| 72 | + } |
| 73 | + # Return FULL state but with 'code' removed to avoid LastValue collision |
| 74 | + return self._merge_return_state(state, updates, drop_keys=("code",)) |
| 75 | + |
| 76 | + def display_explanation(self, state: Dict[str, Any]) -> Dict[str, Any]: |
| 77 | + print("\n=== Explanation (raw) ===\n", state.get("explanation_response_raw", "N/A")) |
| 78 | + if state.get("explanation_json"): |
| 79 | + print( |
| 80 | + "\n=== Explanation (JSON) ===\n", |
| 81 | + json.dumps(state["explanation_json"], indent=2, ensure_ascii=False), |
| 82 | + ) |
| 83 | + # Return FULL state but again ensure 'code' isn't echoed back |
| 84 | + return self._merge_return_state(state, {}, drop_keys=("code",)) |
| 85 | + |
| 86 | + def _build_messages(self, **kwargs) -> Any: |
| 87 | + """ |
| 88 | + Build a list of messages for the LLM. |
| 89 | + Uses the user‑supplied prompt if available; otherwise falls back to an |
| 90 | + inline prompt that safely injects JSON strings via placeholders. |
| 91 | + """ |
| 92 | + if "msgs" not in kwargs or kwargs["msgs"] is None: |
| 93 | + kwargs = {**kwargs, "msgs": []} |
| 94 | + |
| 95 | + # Try to get a prompt from the PromptManager |
| 96 | + prompt = None |
| 97 | + getp = getattr(self.prompt_manager, "get_prompt", None) |
| 98 | + if callable(getp): |
| 99 | + prompt = getp(PROMPT_KEY) |
| 100 | + |
| 101 | + if prompt is not None: |
| 102 | + # The prompt from PromptManager should already be a PromptTemplate |
| 103 | + # or a string that can be formatted safely. |
| 104 | + try: |
| 105 | + return prompt.format_messages(**kwargs) |
| 106 | + except KeyError: |
| 107 | + # Fall back if the prompt contains unexpected placeholders |
| 108 | + pass |
| 109 | + |
| 110 | + # ------------------------------------------------------------------ |
| 111 | + # Inline fallback – use direct string template instead of nested PromptTemplate |
| 112 | + # ------------------------------------------------------------------ |
| 113 | + schema = { |
| 114 | + "items": [{ |
| 115 | + "antipattern_name": "", |
| 116 | + "antipattern_description": "", |
| 117 | + "impact": "", |
| 118 | + "why_it_is_bad": "", |
| 119 | + "how_we_fixed_it": "", |
| 120 | + "refactored_code": "", |
| 121 | + "summary": "" |
| 122 | + }], |
| 123 | + "what_changed": [], |
| 124 | + "why_better": [], |
| 125 | + "principles_applied": [], |
| 126 | + "trade_offs": [], |
| 127 | + "closing_summary": "" |
| 128 | + } |
| 129 | + |
| 130 | + # Prepare the JSON strings that will be inserted via placeholders |
| 131 | + json_input = json.dumps( |
| 132 | + {k: v for k, v in kwargs.items() if k != "msgs"}, |
| 133 | + ensure_ascii=False |
| 134 | + ) |
| 135 | + json_schema = json.dumps(schema, ensure_ascii=False) |
| 136 | + |
| 137 | + # Create the ChatPromptTemplate directly with string templates |
| 138 | + fallback = ChatPromptTemplate.from_messages([ |
| 139 | + ("system", "Return STRICT JSON only. No commentary."), |
| 140 | + ("user", "Given inputs (JSON):\n{json_input}\nRespond with STRICT JSON using exactly this schema:\n{json_schema}"), |
| 141 | + MessagesPlaceholder("msgs"), |
| 142 | + ]) |
| 143 | + |
| 144 | + # Format the messages with the prepared JSON strings |
| 145 | + return fallback.format_messages( |
| 146 | + json_input=json_input, |
| 147 | + json_schema=json_schema, |
| 148 | + msgs=kwargs["msgs"] |
| 149 | + ) |
| 150 | + |
| 151 | + @staticmethod |
| 152 | + def _fallback_payload(state: Dict[str, Any]) -> Dict[str, Any]: |
| 153 | + return { |
| 154 | + "items": [{ |
| 155 | + "antipattern_name": state.get("antipattern_name", "Unknown antipattern"), |
| 156 | + "antipattern_description": state.get("antipattern_description", ""), |
| 157 | + "impact": "", |
| 158 | + "why_it_is_bad": "", |
| 159 | + "how_we_fixed_it": state.get("refactor_rationale", ""), |
| 160 | + "refactored_code": state.get("refactored_code", ""), |
| 161 | + "summary": "Auto-generated minimal explanation (parser fallback)." |
| 162 | + }], |
| 163 | + "what_changed": [], |
| 164 | + "why_better": [], |
| 165 | + "principles_applied": [], |
| 166 | + "trade_offs": [], |
| 167 | + "closing_summary": "" |
| 168 | + } |
0 commit comments