205 lines
7.7 KiB
Python
205 lines
7.7 KiB
Python
"""Sanitizes LLM responses so reasoning/thinking traces never leak into business schemas or UI copy."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from typing import Any
|
||
|
||
from app.schemas.ai import SituationalAnalysisResponse
|
||
|
||
_THINK_TAG_RE = re.compile(
|
||
r"<(?:think|thinking|reasoning|thought)\b[^>]*>(.*?)</(?:think|thinking|reasoning|thought)>",
|
||
re.IGNORECASE | re.DOTALL,
|
||
)
|
||
_UNCLOSED_THINK_RE = re.compile(
|
||
r"<(?:think|thinking|reasoning|thought)\b[^>]*>(.*)$",
|
||
re.IGNORECASE | re.DOTALL,
|
||
)
|
||
_CODE_FENCE_RE = re.compile(r"^```(?:json)?\s*|\s*```$", re.IGNORECASE | re.MULTILINE)
|
||
_COT_PREAMBLE_RE = re.compile(
|
||
r"^\s*(?:thinking\s*process|chain\s*of\s*thought|reasoning_content|思考过程|推理过程)\s*[::].*?(?=(?:\n\s*[\{\[#])|\n\n)",
|
||
re.IGNORECASE | re.DOTALL,
|
||
)
|
||
|
||
|
||
def strip_thinking_text(raw_text: str | None) -> tuple[str, list[str]]:
|
||
"""Return `(clean_text, extracted_thinking_fragments)`."""
|
||
if not raw_text:
|
||
return "", []
|
||
extracted: list[str] = []
|
||
|
||
def _collect_closed(match: re.Match[str]) -> str:
|
||
inner = (match.group(1) or "").strip()
|
||
if inner:
|
||
extracted.append(inner)
|
||
return ""
|
||
|
||
text = _THINK_TAG_RE.sub(_collect_closed, raw_text)
|
||
|
||
unclosed = _UNCLOSED_THINK_RE.search(text)
|
||
if unclosed:
|
||
inner = (unclosed.group(1) or "").strip()
|
||
if inner:
|
||
extracted.append(inner)
|
||
text = text[: unclosed.start()]
|
||
|
||
preamble = _COT_PREAMBLE_RE.match(text)
|
||
if preamble:
|
||
extracted.append(preamble.group(0).strip())
|
||
text = text[preamble.end() :]
|
||
|
||
return text.strip(), extracted
|
||
|
||
|
||
def sanitize_analysis_response(response: SituationalAnalysisResponse) -> SituationalAnalysisResponse:
|
||
"""Strip reasoning traces from `content` and `text_blocks`, moving them into audit `thinking_blocks`."""
|
||
audit_thoughts = list(response.thinking_blocks or [])
|
||
clean_content, from_content = strip_thinking_text(response.content)
|
||
audit_thoughts.extend(from_content)
|
||
|
||
clean_text_blocks: list[str] = []
|
||
for block in response.text_blocks or []:
|
||
cleaned, extra = strip_thinking_text(block)
|
||
audit_thoughts.extend(extra)
|
||
if cleaned:
|
||
clean_text_blocks.append(cleaned)
|
||
|
||
raw = response.raw_response if isinstance(response.raw_response, dict) else {}
|
||
raw_reasoning = raw.get("reasoning_content")
|
||
if isinstance(raw_reasoning, str) and raw_reasoning.strip():
|
||
audit_thoughts.append(raw_reasoning.strip())
|
||
|
||
deduped_thoughts = list(dict.fromkeys(item for item in audit_thoughts if item))
|
||
return response.model_copy(
|
||
update={
|
||
"content": clean_content,
|
||
"text_blocks": clean_text_blocks,
|
||
"thinking_blocks": deduped_thoughts,
|
||
}
|
||
)
|
||
|
||
|
||
def extract_json_object(raw_text: str | None) -> dict[str, Any] | None:
|
||
"""Extract and parse a JSON object after stripping any thinking tags or markdown fences."""
|
||
cleaned, _ = strip_thinking_text(raw_text)
|
||
if not cleaned:
|
||
return None
|
||
unfenced = _CODE_FENCE_RE.sub("", cleaned).strip()
|
||
for candidate in (unfenced,):
|
||
try:
|
||
parsed = json.loads(candidate)
|
||
if isinstance(parsed, dict):
|
||
return parsed
|
||
except json.JSONDecodeError:
|
||
pass
|
||
first_brace = unfenced.find("{")
|
||
last_brace = unfenced.rfind("}")
|
||
if first_brace != -1 and last_brace > first_brace:
|
||
try:
|
||
parsed = json.loads(unfenced[first_brace : last_brace + 1])
|
||
if isinstance(parsed, dict):
|
||
return parsed
|
||
except json.JSONDecodeError:
|
||
return None
|
||
return None
|
||
|
||
|
||
def assert_no_thinking_leak(value: Any) -> None:
|
||
"""Raise ValueError if any nested string still contains raw reasoning markers."""
|
||
if isinstance(value, str):
|
||
lowered = value.lower()
|
||
if any(
|
||
marker in lowered
|
||
for marker in ("<think>", "</think>", "<thinking>", "reasoning_content:")
|
||
):
|
||
raise ValueError("Reasoning trace leaked into user-facing payload")
|
||
return
|
||
if isinstance(value, dict):
|
||
for item in value.values():
|
||
assert_no_thinking_leak(item)
|
||
return
|
||
if isinstance(value, list):
|
||
for item in value:
|
||
assert_no_thinking_leak(item)
|
||
|
||
|
||
def prepare_situational_ai_call(
|
||
ai_client: Any,
|
||
*,
|
||
min_max_tokens: int = 2800,
|
||
) -> tuple[Any, dict[str, Any] | None]:
|
||
"""Ensure situational JSON agents use sufficient token headroom and compatible thinking config."""
|
||
if ai_client is None or not getattr(ai_client, "service_url", ""):
|
||
return ai_client, None
|
||
llm_cfg = dict(getattr(ai_client, "llm_config", None) or {})
|
||
model = str(llm_cfg.get("model") or "").casefold()
|
||
thinking_arg = {"type": "adaptive", "effort": "low"} if model.startswith("minimax-m3") else None
|
||
|
||
effective_client = ai_client
|
||
current_max = int(llm_cfg.get("max_tokens") or 0)
|
||
if llm_cfg and current_max < min_max_tokens:
|
||
from app.services.ai_client import AIProviderClient
|
||
|
||
if isinstance(ai_client, AIProviderClient):
|
||
effective_client = AIProviderClient(
|
||
service_url=ai_client.service_url,
|
||
service_token=ai_client.service_token,
|
||
timeout=getattr(ai_client, "timeout", 60),
|
||
retry_attempts=getattr(ai_client, "retry_attempts", 2),
|
||
llm_config={**llm_cfg, "max_tokens": min_max_tokens},
|
||
)
|
||
return effective_client, thinking_arg
|
||
|
||
|
||
def extract_response_usage(response: Any) -> dict[str, Any]:
|
||
"""Normalize provider token usage counters from a `SituationalAnalysisResponse`."""
|
||
raw = getattr(response, "raw_response", None)
|
||
usage = raw.get("usage") if isinstance(raw, dict) and isinstance(raw.get("usage"), dict) else {}
|
||
details = (
|
||
usage.get("output_tokens_details")
|
||
if isinstance(usage.get("output_tokens_details"), dict)
|
||
else {}
|
||
)
|
||
input_tokens = int(usage.get("input_tokens") or usage.get("prompt_tokens") or 0)
|
||
output_tokens = int(usage.get("output_tokens") or usage.get("completion_tokens") or 0)
|
||
thinking_tokens = int(details.get("thinking_tokens") or usage.get("reasoning_tokens") or 0)
|
||
total_tokens = int(usage.get("total_tokens") or (input_tokens + output_tokens))
|
||
return {
|
||
"provider": str(getattr(response, "provider", "") or ""),
|
||
"model": str(getattr(response, "model", "") or ""),
|
||
"input_tokens": input_tokens,
|
||
"output_tokens": output_tokens,
|
||
"thinking_tokens": thinking_tokens,
|
||
"total_tokens": total_tokens,
|
||
}
|
||
|
||
|
||
def merge_usage_dicts(*usages: dict[str, Any] | None) -> dict[str, Any]:
|
||
"""Aggregate usage metrics across multiple LLM invocations within one workflow run."""
|
||
total_in = 0
|
||
total_out = 0
|
||
total_think = 0
|
||
total_all = 0
|
||
providers: list[str] = []
|
||
models: list[str] = []
|
||
for item in usages:
|
||
if not isinstance(item, dict) or not item:
|
||
continue
|
||
total_in += int(item.get("input_tokens") or 0)
|
||
total_out += int(item.get("output_tokens") or 0)
|
||
total_think += int(item.get("thinking_tokens") or 0)
|
||
total_all += int(item.get("total_tokens") or 0)
|
||
if item.get("provider") and item["provider"] not in providers:
|
||
providers.append(str(item["provider"]))
|
||
if item.get("model") and item["model"] not in models:
|
||
models.append(str(item["model"]))
|
||
return {
|
||
"provider": providers[-1] if providers else "",
|
||
"model": models[-1] if models else "",
|
||
"input_tokens": total_in,
|
||
"output_tokens": total_out,
|
||
"thinking_tokens": total_think,
|
||
"total_tokens": total_all or (total_in + total_out),
|
||
}
|