""" glm_parser.py - ChatGLM SSE response parser. Observed stream traits: - content-type: text/event-stream - each SSE block is carried in a data: line with a JSON payload - think/tool_calls/text/system_error are all emitted through parts[*].content[*] - text payloads are full rendered text snapshots, not pure deltas - stream ends when a text part status becomes finish or top-level status becomes finish """ from __future__ import annotations import json import re from typing import Any, Dict, List from app.core.config import logger from .base import ResponseParser class GLMParser(ResponseParser): """Parse ChatGLM SSE streams while ignoring think/tool-call noise.""" _TERMINAL_STATUSES = {"finish", "finished", "intervene", "intervened"} _PPT_FOLLOWUP_COMMANDS = {"change_mode_to_engine_ppt"} _PPT_TEMPLATE_MARKERS = ('"theme"', '"background"', '"palette"') _HIDDEN_REPAIR_TEXT_PATTERNS = ( "xml-style tool call", "could not be parsed into a valid declared tool", "could not be parsed into valid tool_calls", "validation errors", "the rejected assistant reply was", ) _THINK_REASONING_PREFIX_RE = re.compile( r"^\s*(let me\b|looking at\b|the user has\b|让我|我来|先分析|仔细分析)", re.IGNORECASE, ) _EMBEDDED_REPLY_LABEL_RE = re.compile( r"(?:the rejected assistant reply was|the rejected response was|被拒绝的响应是|被拒绝的助手回复是)\s*[::]?\s*```", re.IGNORECASE, ) _VISIBLE_MARKERS = ("", "", "", "