fix(ai_auto_response): sanitize dify wrapped think output
This commit is contained in:
@@ -10,7 +10,8 @@ class LLMResultParser:
|
||||
def sanitize_response(response: str, current_content: str = "") -> str:
|
||||
if not response:
|
||||
return ""
|
||||
response = response.strip()
|
||||
response = LLMResultParser._unwrap_result_payload(response)
|
||||
response = LLMResultParser._strip_think_blocks(response).strip()
|
||||
response = re.sub(r"\n{3,}", "\n\n", response)
|
||||
current_content = str(current_content or "").strip()
|
||||
if not response:
|
||||
@@ -26,6 +27,8 @@ class LLMResultParser:
|
||||
raw = str(text or "").strip()
|
||||
if not raw:
|
||||
return None
|
||||
raw = LLMResultParser._unwrap_result_payload(raw)
|
||||
raw = LLMResultParser._strip_think_blocks(raw).strip()
|
||||
if raw.startswith("```"):
|
||||
raw = re.sub(r"^```[a-zA-Z0-9_]*\s*", "", raw)
|
||||
raw = re.sub(r"\s*```$", "", raw)
|
||||
@@ -144,3 +147,26 @@ class LLMResultParser:
|
||||
if "category" in keys:
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _strip_think_blocks(text: str) -> str:
|
||||
value = str(text or "")
|
||||
value = re.sub(r"<think>.*?</think>", "", value, flags=re.IGNORECASE | re.DOTALL)
|
||||
return value
|
||||
|
||||
@staticmethod
|
||||
def _unwrap_result_payload(text: str) -> str:
|
||||
raw = str(text or "").strip()
|
||||
if not raw.startswith("{") or not raw.endswith("}"):
|
||||
return raw
|
||||
try:
|
||||
data = json.loads(raw)
|
||||
except Exception:
|
||||
return raw
|
||||
if not isinstance(data, dict):
|
||||
return raw
|
||||
for key in ("result_json", "text", "answer", "result"):
|
||||
value = data.get(key)
|
||||
if isinstance(value, str) and value.strip():
|
||||
return value.strip()
|
||||
return raw
|
||||
|
||||
Reference in New Issue
Block a user