query.py 31.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735
import asyncio
import json
import logging
import os
import re
import time
from dataclasses import dataclass
from datetime import datetime
from typing import Any

from fastapi import APIRouter, Body, HTTPException
from fastapi.responses import StreamingResponse

from agentscope.agent import ReActAgent
from agentscope.message import Msg
from agentscope.tool import Toolkit

from config import QUERY_MODEL_NAME, WIKI_DIR
from src.database.models import WikiQueryLog
from src.database.session import AsyncSessionLocal
from src.tools.wiki_tools import glob_wiki_files, grep_wiki_files, read_local_file
from src.utils.llm_models import extract_text_content, extract_thinking_content
from src.utils.llm_tracker import get_llm_formatter, get_llm_model, load_skill_prompt, print_thinking, token_counter_context

logger = logging.getLogger(__name__)
router = APIRouter()

# 环境变量读取配置项
QUERY_TIMEOUT_SECONDS = int(os.environ.get("WIKI_QUERY_TIMEOUT_SECONDS", "180"))  # 查询超时时间,默认 180 秒
HEARTBEAT_SECONDS = int(os.environ.get("WIKI_QUERY_HEARTBEAT_SECONDS", "15"))  # SSE 流式输出的心跳间隔时间,默认 15 秒
EMPTY_ANSWER_FALLBACK = "知识库查询没有生成有效回答,请稍后重试,或补充更明确的问题信息。"  # 兜底回答文本
ANSWER_EVENT_ID = "final-answer"  # 无 text part 时(如兜底/异常路径)收尾使用的事件 id


@dataclass
class WikiQueryResult:
    """用于封装 Wiki 查询返回的结果数据结构"""
    answer: str  # 最终返回的答案
    tokens: int  # 本次请求消耗的 token 数量
    duration_ms: int  # 查询总耗时(毫秒)
    status: str = "Success"  # 执行状态(Success, Error, Timeout, EmptyAnswer)
    error: str | None = None  # 错误信息(如果有)


async def save_query_log_to_db(
        query: str,
        history: list,
        answer: str | None,
        model: str,
        tokens: int,
        duration_ms: int,
        status: str = "Success",
        error: str | None = None,
        session_id: str | None = None,
) -> None:
    """
    异步将查询记录保存至数据库中。
    内部使用异常捕获以确保失败仅记录日志,不会阻塞或影响用户的正常接口响应。
    """
    try:
        async with AsyncSessionLocal() as session:
            # 构造数据库日志对象
            log = WikiQueryLog(
                session_id=session_id,
                query_text=query,
                history=json.dumps(history, ensure_ascii=False) if history else None,
                answer_text=answer,
                model_name=model,
                total_tokens=tokens,
                duration_ms=duration_ms,
                status=status,
                error_message=error,
            )
            session.add(log)
            await session.commit()
            logger.info("查询日志已入库: id=%s, status=%s", getattr(log, "id", None), status)
            if answer:
                logger.info("[Query Result] query=%r, answer_chars=%s", query, len(answer))
    except Exception as exc:
        logger.exception("写入查询日志到数据库失败: %s", exc)


@router.post("/wiki/query")
async def wiki_query(data: dict = Body(...)):
    """
    Wiki 查询接口(SSE 流式响应)。
    用于前端实时接收模型打字机效果及推理过程心跳。
    """
    user_query = str(data.get("query", "")).strip()
    history = data.get("history") or []
    session_id = data.get("sessionId")

    logger.info(
        "收到 Wiki 查询请求: query=%r, session_id=%r, history_len=%s",
        user_query,
        session_id,
        len(history),
    )
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    # 返回 StreamingResponse,启用流式事件输出
    return StreamingResponse(
        run_wiki_query_stream(user_query, history, session_id),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",  # 禁用缓存
            "X-Accel-Buffering": "no",  # 禁用 Nginx 等反向代理的缓存以保证实时性
        },
    )


@router.post("/wiki/query/json")
async def wiki_query_json_endpoint(data: dict = Body(...)):
    """
    Wiki 查询接口(JSON 同步响应)。
    供不需要流式输出的客户端调用,直接等待查询结束后返回完整结果。
    """
    user_query = str(data.get("query", "")).strip()
    history = data.get("history") or []
    session_id = data.get("sessionId")

    logger.info(
        "收到 Wiki JSON 查询请求: query=%r, session_id=%r, history_len=%s",
        user_query,
        session_id,
        len(history),
    )
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    try:
        # 同步等待查询执行结束
        result = await run_wiki_query_json(user_query, history, session_id)
    except Exception as exc:
        logger.exception("JSON 查询执行失败: %s", exc)
        raise HTTPException(status_code=500, detail=str(exc)) from exc

    return {
        "answer": result.answer,
        "tokens": result.tokens,
        "duration_ms": result.duration_ms,
        "status": result.status,
    }


def load_index_map() -> str:
    """读取 ware/wiki/index.md 作为「知识库地图」注入系统提示词。
    index.md 由摄入/维护流程按 type 分组确定性重建(`- [[slug]] — title`),
    提前注入可让 Agent 直接据图定位 slug,省去「读 index / 先盲 grep」的往返。
    """
    index_path = os.path.join(WIKI_DIR, "index.md")
    if not os.path.exists(index_path):
        return "(知识库地图为空:index.md 不存在)"
    try:
        with open(index_path, "r", encoding="utf-8", errors="replace") as f:
            return f.read().strip()
    except Exception as exc:
        logger.warning("读取 index.md 失败: %s", exc)
        return "(知识库地图读取失败)"


def build_query_agent(history: list) -> ReActAgent:
    """
    构建并配置用于检索 Wiki 的 AgentScope ReAct 智能体。
    为智能体装载本地文件读取和搜索工具,注入「知识库地图」与业务 System Prompt。
    """
    toolkit = Toolkit()
    # 注册智能体可使用的工具
    toolkit.register_tool_function(read_local_file)   # 读取页面内容(主用)
    toolkit.register_tool_function(glob_wiki_files)   # 文件名匹配(定位路径)
    toolkit.register_tool_function(grep_wiki_files)   # 全文正则搜索(兜底)

    # 加载针对 llm-query 定制的提示词片段 + 知识库地图
    skill_prompt = load_skill_prompt("llm-query")
    index_map = load_index_map()

    # 注入前置历史会话上下文
    history_injection = ""
    if history:
        history_lines = []
        # 只保留最近 16 条对话记录
        for item in history[-16:]:
            role_label = "用户" if item.get("role") == "user" else "助手"
            # 限制历史文本长度,避免 Token 消耗过大
            content = str(item.get("content", ""))[:500]
            history_lines.append(f"{role_label}: {content}")
        history_injection = (
                "\n\n【对话历史】用于理解用户当前上下文:\n"
                + "\n".join(history_lines)
                + "\n"
        )

    # 定义完整的系统提示词
    sys_prompt = f"""你是一名专业的汽车后市场服务知识顾问。你的任务是基于知识库精确回答用户问题。
{history_injection}

【知识库地图(index.md,已为你注入,禁止再用工具读取 index.md)】
下面是全库页面目录,按页面类型分组。普通行格式为 `- [[slug]] — 标题`;sources 行会额外带 `| path: ware/wiki/sources/<品牌系列>/<slug>.md`。请直接据此地图定位目标页面。
{index_map}

【页面物理路径规则】(据 slug 直接拼出路径去读,避免无谓搜索)
- 一般类型:`ware/wiki/<type>/<slug>.md`(type 取地图中所属分组,如 products/policies/scripts/procedures/concepts/comparisons/troubleshooting/entities/synthesis)。
- 来源摘要:优先使用 index.md 中该 sources 条目携带的 `path:` 完整路径读取;如果旧索引没有 path,先调用 `glob_wiki_files(pattern="ware/wiki/sources/**/<slug>.md")` 定位唯一文件,再用 `read_local_file` 读取,禁止直接猜 `ware/wiki/sources/<slug>.md`。

【工作流程(务必收敛,尽量少调用工具)】
1. 判断意图并路由(优先级):系统报错/操作受阻→troubleshooting;"能不能说/违规吗"→policies(合规红线);"怎么回/话术"→scripts;产品参数/价格→products;条款/政策→policies;流程/步骤→procedures;对比→comparisons/synthesis;概念→concepts。
2. 据地图选出最相关的目标 slug,用 read_local_file 直接读 **≤3 个**目标页:普通类型按上方规则拼路径;sources 必须优先使用地图中的 `path:`,没有 path 时先 glob 定位。
3. 仅当页面 frontmatter 的 `related` 中有**确有必要**的关联页时,再二跳读取(如产品页→关联 policy 看免责、话术页→关联 concept 看方法论)。
4. 基于读到的内容生成最终回答。
- 仅当据图无法定位、或需在正文中查具体数值/罕见词时,才用 grep_wiki_files(兜底)。

【上下文与防串味(使用结构化字段,不要用 tags 判品牌)】
- 页面 frontmatter 含结构化字段:`brand`(列表)、`series`、`business_category`、`sub_business`、`role`。
- 读页后用 `brand`/`series` 核对是否与用户所属品牌一致,**严禁跨品牌混淆信息**。
- 若问题涉及产品/价格/政策但无法确定品牌,**先反问确认品牌再检索**,不要臆测。

【严格约束】
- 只使用知识库中的信息回答,禁止编造或臆测;价格、年限、里程等数字必须与原文完全一致,禁止四舍五入。
- 知识库信息不足以回答时,明确告知并建议补充哪类文档(走兜底话术)。
- 引用页面使用 slug 简写 `[[slug]]`。
- 调用工具前如需说明,**控制在一句话以内**(正文会原样展示给用户),不要复述工具返回的原始内容。
- 推理过程与工具调用细节不要写进正文。

{skill_prompt}
"""
    return ReActAgent(
        name="WikiAssistant",
        model=get_llm_model(QUERY_MODEL_NAME, purpose="QUERY"),
        formatter=get_llm_formatter(QUERY_MODEL_NAME),
        sys_prompt=sys_prompt,
        toolkit=toolkit,
    )


class WikiQueryRunner:
    """
    执行核心查询逻辑的运行器类,负责调度 Agent,处理各类过程事件并记录。
    支持可选将事件抛出到异步队列以供流式接口使用。
    """

    def __init__(
            self,
            user_query: str,
            history: list,
            session_id: str | None = None,
            event_queue: asyncio.Queue | None = None,
    ) -> None:
        self.user_query = user_query
        self.history = history
        self.session_id = session_id
        self.event_queue = event_queue

        self.reasoning: list[dict[str, Any]] = []  # 收集的所有推理事件
        self._reasoning_latest: dict[str, dict[str, Any]] = {}  # 最新状态的推理事件(按 ID 索引)
        self._reasoning_logged = False  # 标记是否已经记录过最终的推理总结日志
        self._logged_call_events: set[str] = set()  # 记录已打印日志的工具调用事件,用于防重

        self._start_ts: float = time.time()  # 本次查询起点,用于给事件打 elapsed_ms
        self._last_text_id: str | None = None  # 最后一个答案 part 的事件 id(收尾时用它做权威覆盖)

    async def execute(self) -> WikiQueryResult:
        """主执行入口,启动 Agent 进行问题解答,捕获状态并保存数据库日志。"""
        start_time = time.time()
        self._start_ts = start_time
        answer = ""
        status = "Success"
        error_msg: str | None = None
        total_tokens = 0

        # 进入 Token 统计上下文,方便在结束时获取请求消耗
        async with token_counter_context() as get_tokens:
            try:
                agent = build_query_agent(self.history)
                self._configure_agent(agent)
                user_msg = Msg("user", self.user_query, role="user")

                # 设置上下文标识,记录内部 thinking 打印状态
                thinking_token = print_thinking.set(False)
                try:
                    # 调用 Agent 进行查询,设定超时控制
                    final_res = await asyncio.wait_for(agent(user_msg), timeout=QUERY_TIMEOUT_SECONDS)
                finally:
                    # 恢复上下文标识
                    print_thinking.reset(thinking_token)

                # 提取并清理最终答案
                answer = clean_final_answer(
                    extract_text(final_res.content if hasattr(final_res, "content") else final_res))

                # 如果没有生成实质答案,则进行兜底处理
                if not answer:
                    status = "EmptyAnswer"
                    answer = EMPTY_ANSWER_FALLBACK
                    logger.warning("[Query] Agent 返回空答案,已使用兜底回答: query=%r", self.user_query)

                # 打印整个过程的推理摘要日志
                self._log_reasoning_summary(answer)
                # 以流的形式发送答案
                await self._emit_answer(answer)
                logger.info("[Agent WikiAssistant Final Answer]\n%s", answer)
            except asyncio.TimeoutError as exc:
                status = "Timeout"
                error_msg = f"查询超时({QUERY_TIMEOUT_SECONDS} 秒),请稍后重试或缩小问题范围。"
                self._log_reasoning_summary(answer)
                logger.exception("[Query] 查询超时: query=%r", self.user_query)
                raise RuntimeError(error_msg) from exc
            except Exception as exc:
                status = "Error"
                error_msg = str(exc)
                self._log_reasoning_summary(answer)
                logger.exception("[Query] 查询执行异常: %s", exc)
                raise
            finally:
                # 无论成功失败,记录 token 用量、耗时并执行入库
                total_tokens = get_tokens()
                duration_ms = int((time.time() - start_time) * 1000)
                save_log_coro = save_query_log_to_db(
                    self.user_query,
                    self.history,
                    answer or None,
                    QUERY_MODEL_NAME,
                    total_tokens,
                    duration_ms,
                    status,
                    error_msg,
                    self.session_id,
                )
                # 如果有队列说明是流式请求,以非阻塞 Task 异步执行入库
                if self.event_queue:
                    asyncio.create_task(save_log_coro)
                else:
                    await save_log_coro
                logger.info(
                    "[Query] 查询结束: status=%s, tokens=%s, duration_ms=%s",
                    status,
                    total_tokens,
                    duration_ms,
                )

        return WikiQueryResult(
            answer=answer,
            tokens=total_tokens,
            duration_ms=int((time.time() - start_time) * 1000),
            status=status,
            error=error_msg,
        )

    def _configure_agent(self, agent: ReActAgent) -> None:
        """配置 Agent:接管自带的打印功能,将其转换为我们的流式事件用于前端展示和日志。

        路由是**确定性的、按内容 block 类型分流**,且**只追加、不回撤、不重新归类**
        (即主流 chat UI 的 append-only 时间线模型):
        - thinking → 思考框(thought),实时。协议明确标了类型,故单独折叠。
        - tool_use → 思考框(call),实时
        - tool_result → 思考框(response),实时
        - text → 答案区的一个 part(bot),按该轮 msg id 独立成块,实时逐字增长

        text 一律进答案区,**不再区分「前导文字」与「最终回答」**:不传 structured_model 时,
        AgentScope ReActAgent 判定终局靠的是「本轮无 tool_use」这一**只有轮末才成立的事后条件**
        (_react_agent.py:513),流式当下无从判断。旧实现用时间去抖猜测,实测模型前导领先
        tool_use 0.3~0.5s 而窗口仅 0.15s,必然猜错并触发「已推进气泡再清空」的闪烁。
        改为每个 text block 各占一个 part 后,前端按 id 覆盖同 part、按插入顺序拼接多 part,
        无覆盖即无回撤,该类 bug 从定义上消失。
        """
        if hasattr(agent, "set_console_output_enabled"):
            agent.set_console_output_enabled(False)

        async def hooked_print(content: Any, *args: Any, **kwargs: Any) -> None:
            if not isinstance(content, Msg):
                return
            role = getattr(content, "role", None)
            # 忽略注入给模型的 hint 等用户消息
            if role == "user":
                return
            # 注:AgentScope 会额外传 last(该轮流式是否结束)。时间线模型下每个 part 都是
            # 「按 id 覆盖」的累计全文,中途与轮末的处理完全一致,故无需再区分。
            msg_id = str(getattr(content, "id", None) or f"msg-{datetime.now().timestamp()}")

            try:
                tool_use_blocks = content.get_content_blocks("tool_use")
                tool_result_blocks = content.get_content_blocks("tool_result")
                thinking_blocks = content.get_content_blocks("thinking")
                text_blocks = content.get_content_blocks("text")
            except Exception:
                return

            # 1) thinking → 思考框(实时)
            thinking_text = extract_thinking_content(thinking_blocks).strip()
            if thinking_text:
                self._emit_reasoning({"id": f"{msg_id}-think", "type": "thought", "content": thinking_text})

            # 2) tool_use → 思考框(实时)
            for blk in tool_use_blocks:
                block_id = str(blk.get("id") or f"{msg_id}-{blk.get('name')}")
                self._emit_reasoning({
                    "id": f"call-{block_id}",
                    "type": "call",
                    "content": json.dumps(blk, ensure_ascii=False),
                    "name": blk.get("name"),
                })

            # 3) tool_result → 思考框(实时)
            for blk in tool_result_blocks:
                block_id = str(blk.get("id") or f"{msg_id}-{blk.get('name')}")
                self._emit_reasoning({
                    "id": f"resp-{block_id}",
                    "type": "response",
                    "content": json.dumps(blk, ensure_ascii=False),
                    "name": blk.get("name"),
                })

            # 4) text → 答案时间线的一个 part(text_value 为该轮到目前为止的累计文本)
            text_value = "".join(str(b.get("text", "")) for b in text_blocks)
            if not text_value and not (tool_use_blocks or tool_result_blocks or thinking_blocks):
                # 兜底:极少数情况下 content 为纯字符串
                raw = content.content if isinstance(getattr(content, "content", None), str) else ""
                text_value = str(raw)
            if not text_value or role != "assistant":
                return

            # 按本轮 msg id 独立成 part:前端 messageMap[id] 覆盖同 part(逐字增长)、
            # 跨 part 按插入顺序拼接(多段有序)。只追加,绝不回撤。
            text_id = f"{msg_id}-answer"
            self._last_text_id = text_id
            self._put_event({"id": text_id, "type": "bot", "content": text_value})

        # 拦截替换
        agent.print = hooked_print

    def _emit_reasoning(self, event: dict[str, Any]) -> None:
        """记录一条思考过程事件:入 reasoning 列表(用于汇总日志)、推送 SSE、并对工具调用打印面包屑日志。"""
        event_id = str(event.get("id") or "")
        existing_idx = next(
            (i for i, e in enumerate(self.reasoning) if str(e.get("id") or "") == event_id), None
        ) if event_id else None
        if existing_idx is not None:
            self.reasoning[existing_idx] = event
        else:
            self.reasoning.append(event)

        self._remember_reasoning_event(event)
        self._put_event(event)  # 推送至 SSE 队列

        event_type = event.get("type")
        if event_type in {"call", "response"}:
            # 日志去重,防止连续打印同样的工具调用
            if event_id and event_id in self._logged_call_events:
                return
            if event_id:
                self._logged_call_events.add(event_id)
            detail = ""
            if event_type == "call":
                parsed = parse_json_object(event.get("content"))
                tool_input = parsed.get("input") if parsed else None
                if tool_input is not None:
                    detail = " input=" + preview_text(json.dumps(tool_input, ensure_ascii=False), 200)
            logger.info("[Agent WikiAssistant %s] name=%s%s", event_type, event.get("name"), detail)

    def _remember_reasoning_event(self, event: dict[str, Any]) -> None:
        """在本地记录一份最新的推理事件快照,用于生成最终的汇总日志"""
        event_id = str(event.get("id") or f"event-{len(self._reasoning_latest)}")
        self._reasoning_latest[event_id] = event

    def _log_reasoning_summary(self, answer: str = "") -> None:
        """打印完整的推理过程汇总日志,避免过程中日志零散不直观"""
        if self._reasoning_logged or not self._reasoning_latest:
            return

        blocks = []
        for event in self._reasoning_latest.values():
            # 去除与最终答案重复的 thinking 输出
            if event.get("type") == "thought" and is_same_text(event.get("content", ""), answer):
                continue
            blocks.append(render_full_reasoning_log_event(event))

        if blocks:
            logger.info("[Agent WikiAssistant Reasoning]\n%s", "\n\n".join(blocks))
        self._reasoning_logged = True

    async def _emit_answer(self, answer: str) -> None:
        """权威收尾:用清洗后的入库答案覆盖**最后一个**答案 part。

        始终执行(非失败兜底),保证末段恒等于入库答案——绝不空白、绝不截断、绝不串入思考内容。
        更早的 part(调工具前的说明文字)原样保留,与末段共同构成完整时间线。
        若本次没产生任何 text part(异常/兜底路径),回落到 ANSWER_EVENT_ID 新起一个 part。
        """
        if not self.event_queue:
            return
        self._put_event({"id": self._last_text_id or ANSWER_EVENT_ID, "type": "bot", "content": answer})
        await asyncio.sleep(0)  # 让出执行权,确保事件被及时转发

    def _put_event(self, event: dict[str, Any]) -> None:
        """将事件放入异步队列(如果有的话),并补上服务器侧时间戳,供前端计算各步骤耗时。"""
        if self.event_queue:
            if isinstance(event, dict) and "ts" not in event:
                now = time.time()
                event["ts"] = int(now * 1000)
                event["elapsed_ms"] = int((now - self._start_ts) * 1000)
            self.event_queue.put_nowait(event)


async def run_wiki_query_stream(user_query: str, history: list, session_id: str | None = None):
    """
    流式执行 Wiki 查询的生成器函数。
    向 SSE 客户端依次 yield 初始化、心跳、中间推理、打字片段及结束状态。
    """
    # 发送初始化事件
    yield "data: [INIT]\n\n"

    queue: asyncio.Queue = asyncio.Queue()
    runner = WikiQueryRunner(user_query, history, session_id=session_id, event_queue=queue)

    # 异步启动查询任务
    task = asyncio.create_task(runner.execute())
    # 任务完成后向队列压入特殊标记,以便跳出接收循环
    task.add_done_callback(lambda _task: queue.put_nowait({"type": "_task_done"}))

    done_payload_sent = False
    while True:
        # 如果任务结束且队列已空,则退出
        if task.done() and queue.empty():
            break
        try:
            # 阻塞等待队列中的新事件,设定超时做心跳探测
            item = await asyncio.wait_for(queue.get(), timeout=HEARTBEAT_SECONDS)
        except asyncio.TimeoutError:
            # 捕获到超时说明长时间无消息,发送心跳维持连接
            if task.done() and queue.empty():
                break
            heartbeat = {
                "type": "heartbeat",
                "data": {"elapsed_ms": None, "ts": int(time.time() * 1000)},
            }
            yield sse_data(heartbeat)
            continue

        if isinstance(item, dict) and item.get("type") == "_task_done":
            break

        # 转发普通事件数据到前端
        yield sse_data(item)

        if task.done() and queue.empty():
            break

    try:
        # 等待任务最终返回以获取统计信息
        result = await task
        done_payload_sent = True
        yield sse_data(
            {
                "type": "done",
                "data": {
                    "duration_ms": result.duration_ms,
                    "tokens": result.tokens,
                    "status": result.status,
                },
            }
        )
    except Exception as exc:
        logger.exception("[Query] SSE 查询失败: %s", exc)
        yield sse_data({"type": "error", "content": str(exc)})
    finally:
        # 如果任务被异常取消,发送报错
        if not done_payload_sent and task.cancelled():
            yield sse_data({"type": "error", "content": "查询任务已取消。"})
        # 标准 SSE 结束标识
        yield "data: [DONE]\n\n"


async def run_wiki_query_json(
        user_query: str,
        history: list,
        session_id: str | None = None,
) -> WikiQueryResult:
    """内部执行直接获取 JSON 结果的包装函数"""
    runner = WikiQueryRunner(user_query, history, session_id=session_id)
    return await runner.execute()


def sse_data(payload: dict[str, Any]) -> str:
    """序列化格式化为 SSE (Server-Sent Events) 标准格式的字符串"""
    return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"


def msg_to_reasoning_events(msg: Msg) -> list[dict[str, Any]]:
    """将 AgentScope 的 Msg 对象解析并转换为规范化的推理事件结构列表"""
    # 忽略用户的原始提问消息
    if getattr(msg, "role", None) == "user":
        return []

    msg_id = getattr(msg, "id", None) or f"msg-{datetime.now().timestamp()}"
    content = getattr(msg, "content", "")
    return content_to_reasoning_events(content, msg_id)


def content_to_reasoning_events(content: Any, msg_id: str) -> list[dict[str, Any]]:
    """
    深度解析 Agent 的响应内容。
    区分出 tool_use, tool_result, thinking, text 等不同类型的节点。
    """
    events: list[dict[str, Any]] = []

    # 列表递归拆解
    if isinstance(content, list):
        for index, item in enumerate(content):
            events.extend(content_to_reasoning_events(item, f"{msg_id}-{index}"))
        return events

    # 字典格式解析:识别不同的行为 block
    if isinstance(content, dict):
        block_type = content.get("type")
        if block_type == "tool_use":
            # 工具调用事件
            events.append(
                {
                    "id": msg_id,
                    "type": "call",
                    "content": json.dumps(content, ensure_ascii=False),
                    "name": content.get("name"),
                }
            )
        elif block_type == "tool_result":
            # 工具返回结果事件
            events.append(
                {
                    "id": msg_id,
                    "type": "response",
                    "content": json.dumps(content, ensure_ascii=False),
                    "name": content.get("name"),
                }
            )
        elif block_type == "thinking" or "thinking" in content:
            # 模型内部的 thinking/推理过程
            thinking = extract_thinking_content(content)
            if thinking:
                events.append({"id": msg_id, "type": "thought", "content": thinking})
        elif block_type == "text" or "text" in content:
            # 普通输出文本
            text = str(content.get("text", ""))
            if text and not is_final_answer_text(text):
                events.append({"id": msg_id, "type": "thought", "content": text})
        elif content:
            # 兜底的字典项处理
            events.append(
                {
                    "id": msg_id,
                    "type": "thought",
                    "content": json.dumps(content, ensure_ascii=False),
                }
            )
        return events

    # 兜底纯文本处理
    text = str(content).strip()
    if text and not is_final_answer_text(text):
        events.append({"id": msg_id, "type": "thought", "content": text})
    return events


def extract_text(content: Any) -> str:
    """提取混合结构数据中的所有纯文本部分并拼接"""
    return extract_text_content(content)


def clean_final_answer(text: str) -> str:
    """清理答案中的 thinking 标签和内部使用标记,输出整洁给用户的最终结果"""
    text = text or ""
    # 移除 <think>...</think> 相关内容
    text = re.sub(r"<(?:think|thinking)>.*?</(?:think|thinking)>", "", text, flags=re.DOTALL | re.IGNORECASE)
    # 移除头部的 Final Answer: 标识
    text = re.sub(r"^\s*Final Answer\s*:\s*", "", text, flags=re.IGNORECASE)
    return text.strip()


def is_final_answer_text(text: str) -> bool:
    """判断一段文本是否是以 Final Answer: 为前缀的标志性输出"""
    return bool(re.match(r"^\s*Final Answer\s*:", text or "", flags=re.IGNORECASE))


def render_full_reasoning_log_event(event: dict[str, Any]) -> str:
    """格式化单条推理事件字典为美观的纯文本形式以供日志打印"""
    event_type = event.get("type", "thought")
    name = event.get("name")
    event_id = event.get("id")
    content = event.get("content", "")
    parsed = parse_json_object(content)
    if parsed and not name:
        name = parsed.get("name")

    header = f"--- [{event_type}{':' + str(name) if name else ''}]"
    if event_id:
        header += f" id={event_id}"

    if parsed:
        body = json.dumps(parsed, ensure_ascii=False, indent=2)
    else:
        body = str(content)
    return f"{header}\n{body}"


def parse_json_object(value: Any) -> dict[str, Any]:
    """安全地解析 JSON 字符串为字典"""
    if isinstance(value, dict):
        return value
    if not isinstance(value, str):
        return {}
    try:
        parsed = json.loads(value)
    except Exception:
        return {}
    return parsed if isinstance(parsed, dict) else {}




def is_same_text(left: Any, right: Any) -> bool:
    """比对两段文本去格式化后的核心内容是否一致"""
    left_text = normalize_log_text(left)
    right_text = normalize_log_text(right)
    return bool(left_text and right_text and left_text == right_text)


def normalize_log_text(value: Any) -> str:
    """剔除空格和特殊标识,生成标准可比它的纯内容文本"""
    return re.sub(r"\s+", "", clean_final_answer(str(value or "")))


def preview_text(text: Any, limit: int = 500) -> str:
    """文本截断预览,超过限制的补全省略号并消除换行以单行展示"""
    value = str(text).replace("\r", "\\r").replace("\n", "\\n")
    if len(value) <= limit:
        return value
    return value[:limit] + "...[truncated]"