query.py 19.8 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
import asyncio
import json
import re
import time
from datetime import datetime
from fastapi import APIRouter, Body, BackgroundTasks, HTTPException
from fastapi.responses import StreamingResponse
import logging

logger = logging.getLogger(__name__)

from src.database.models import WikiOperationLog, WikiQueryLog
from src.database.session import AsyncSessionLocal
from src.utils.llm_tracker import get_llm_model, load_skill_prompt, token_counter_context
from config import QUERY_MODEL_NAME
from src.tools.wiki_tools import grep_wiki_files, glob_wiki_files, read_local_file

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


router = APIRouter()


async def save_query_log_to_db(query: str, history: list, answer: str, model: str, tokens: int, duration_ms: int, status: str = "Success", error: str = None, session_id: str = 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(f"查询日志已入库: id={log.id}, status={status}")
            if answer:
                logger.info(f"[Query Result] Query: {query} | Full Answer: {answer}")
    except Exception as e:
        logger.error(f"写入查询日志到数据库失败: {e}", exc_info=True)


@router.post("/wiki/query")
async def wiki_query(data: dict = Body(...), background_tasks: BackgroundTasks = None):
    """
    Wiki 查询接口:基于 AgentScope 的 ReAct 智能体实现。
    支持流式输出 (Server-Sent Events),让用户能实时看到思考过程。
    """
    user_query = data.get("query", "")
    history = data.get("history", [])
    session_id = data.get("sessionId")
    logger.info(f"收到 Wiki 查询请求: query='{user_query}', session_id='{session_id}', 历史消息长度={len(history)}")
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    event_generator = run_wiki_query_stream(user_query, history, session_id)
    return StreamingResponse(event_generator, media_type="text/event-stream")


@router.post("/wiki/query/json")
async def wiki_query_json_endpoint(data: dict = Body(...), background_tasks: BackgroundTasks = None):
    """
    非流式版本的 Wiki 查询接口。
    直接返回包含推导过程和最终结果的完整 JSON。
    """
    user_query = data.get("query", "")
    history = data.get("history", [])
    session_id = data.get("sessionId")
    logger.info(f"收到 Wiki JSON查询请求: query='{user_query}', session_id='{session_id}', 历史消息长度={len(history)}")
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    start_time = time.time()
    try:
        result = await run_wiki_query_json(user_query, history)
        duration_ms = int((time.time() - start_time) * 1000)
        
        # 异步落表
        if background_tasks:
            background_tasks.add_task(
                save_query_log_to_db,
                user_query,
                history,
                result.get("answer"),
                QUERY_MODEL_NAME,
                result.get("tokens", 0),
                duration_ms,
                "Success",
                None,  # error
                session_id
            )
        
        return result
    except Exception as e:
        duration_ms = int((time.time() - start_time) * 1000)
        logger.exception(f"JSON 查询执行失败: {e}")
        
        if background_tasks:
            background_tasks.add_task(
                save_query_log_to_db,
                user_query,
                history,
                None,
                QUERY_MODEL_NAME,
                0,
                duration_ms,
                "Error",
                str(e),
                session_id
            )
            
        raise HTTPException(status_code=500, detail=str(e))


def build_query_agent(history: list) -> ReActAgent:
    """内部方法:构建基于 ReAct 的 Wiki 查询智能体。"""
    toolkit = Toolkit()
    toolkit.register_tool_function(grep_wiki_files)
    toolkit.register_tool_function(glob_wiki_files)
    toolkit.register_tool_function(read_local_file)

    skill_prompt = load_skill_prompt("llm-query")

    history_injection = ""
    if history:
        history_lines = []
        for m in history[-16:]:  # 最多8轮对话
            role_label = "用户" if m.get("role") == "user" else "助手"
            content = m.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}

【工作流程】
1. 先分析用户问题的意图(产品/话术/政策/流程/排障等)
2. 使用 grep_wiki_files / glob_wiki_files / read_local_file 工具在 ware/wiki 中检索
3. 完成检索后,直接基于找到的内容生成专业、准确的最终回答

【严格约束】
- 只使用知识库中的信息回答,禁止编造或臆测
- 价格、年限、里程等数字必须与知识库原文完全一致,禁止四舍五入
- 如果知识库信息不足以回答,明确告知用户并建议补充哪类文档
- 区分不同品牌/车型,不得混淆信息
- 当用户问题模糊时(如不确定品牌/产品),先反问确认再检索

{skill_prompt}
"""
    agent = ReActAgent(
        name="WikiAssistant",
        model=get_llm_model(QUERY_MODEL_NAME),
        formatter=DashScopeChatFormatter(),
        sys_prompt=sys_prompt,
        toolkit=toolkit,
    )
    return agent


async def run_wiki_query_stream(user_query: str, history: list, session_id: str = None):
    """
    流式执行 Wiki 查询。返回一个异步生成器,产出 Server-Sent Events (SSE) 字符串。
    问题9:使用 token_counter_context 追踪 Token 消耗。
    """
    # 立即发送 INIT 事件,让前端确认连接已建立,避免因 Agent 初始化慢导致前端看起来无反应
    yield "data: [INIT]\n\n"

    # 问题9:Token 追踪
    async with token_counter_context() as get_tokens:
        agent = build_query_agent(history)
        queue = asyncio.Queue()
        pending_thought = None
        final_answer_sent = False  # 防止最终答案被重复发送

        def flush_pending_thought():
            nonlocal pending_thought
            if pending_thought:
                pt = pending_thought
                pending_thought = None
                m_id = getattr(pt, "id", None) or f"msg-{datetime.now().timestamp()}"
                content = pt.content
                if isinstance(content, str):
                    queue.put_nowait({"id": m_id, "type": "thought", "content": content})
                elif isinstance(content, list):
                    for i, item in enumerate(content):
                        item_id = f"{m_id}-{i}"
                        if isinstance(item, str):
                            queue.put_nowait({"id": item_id, "type": "thought", "content": item})
                        elif isinstance(item, dict) and "text" in item:
                            queue.put_nowait({"id": item_id, "type": "thought", "content": item["text"]})
                        else:
                            queue.put_nowait({"id": item_id, "type": "thought", "content": str(item)})

        def _extract_text_from_content(content) -> str:
            """从 msg.content 中提取纯文本字符串"""
            if isinstance(content, str):
                return content
            if isinstance(content, list):
                parts = []
                for item in content:
                    if isinstance(item, str):
                        parts.append(item)
                    elif isinstance(item, dict) and "text" in item:
                        parts.append(item["text"])
                return "".join(parts)
            return ""

        def message_handler(msg: Msg):
            nonlocal pending_thought, final_answer_sent
            if msg.role == "user":
                return

            content = msg.content
            is_tool = False
            is_pure_text = False

            if isinstance(content, str):
                is_pure_text = True
            elif isinstance(content, list):
                for item in content:
                    if isinstance(item, dict) and item.get("type") in ["tool_use", "tool_result"]:
                        is_tool = True
                        break
                if not is_tool and all(isinstance(i, str) or (isinstance(i, dict) and "text" in i) for i in content):
                    is_pure_text = True
            elif isinstance(content, dict) and content.get("type") in ["tool_use", "tool_result"]:
                is_tool = True

            if is_pure_text and not is_tool:
                # 检测是否是最终答案(以 Final Answer: 开头)
                # 如果是,则直接流式发送,不存入 pending_thought(避免先出现在思考折叠框后再重复输出)
                raw_text = _extract_text_from_content(content)
                cleaned = re.sub(r"^Final Answer:\s*", "", raw_text, flags=re.IGNORECASE).strip()
                if cleaned != raw_text.strip():  # 说明确实以 Final Answer: 开头
                    # 这是最终答案:先 flush 之前暂存的中间思考,再流式发送最终答案
                    flush_pending_thought()
                    if cleaned:
                        final_answer_sent = True
                        logger.info(f"[Agent WikiAssistant Final Answer via handler] {cleaned}")
                        m_id = f"msg-{datetime.now().timestamp()}"
                        chunk_size = 4
                        for i in range(0, len(cleaned), chunk_size):
                            queue.put_nowait({"id": m_id, "type": "stream", "content": cleaned[i:i+chunk_size]})
                    return
                # 普通中间思考文本:暂存到 pending_thought
                pending_thought = msg
                return

            flush_pending_thought()

            m_id = getattr(msg, "id", None) or f"msg-{datetime.now().timestamp()}"
            m_type = "thought"

            if isinstance(content, list):
                for i, item in enumerate(content):
                    item_id = f"{m_id}-{i}"
                    if isinstance(item, dict):
                        if item.get("type") == "tool_use":
                            queue.put_nowait({
                                "id": item_id,
                                "type": "call",
                                "content": json.dumps(item, ensure_ascii=False),
                                "name": item.get("name"),
                            })
                        elif item.get("type") == "tool_result":
                            queue.put_nowait({
                                "id": item_id,
                                "type": "response",
                                "content": json.dumps(item, ensure_ascii=False),
                                "name": item.get("name"),
                            })
                        elif "text" in item:
                            queue.put_nowait({"id": item_id, "type": m_type, "content": item["text"]})
                        elif "thinking" in item:
                            queue.put_nowait({"id": item_id, "type": m_type, "content": item["thinking"]})
                    else:
                        queue.put_nowait({"id": item_id, "type": m_type, "content": str(item)})
            elif isinstance(content, dict):
                if content.get("type") == "tool_use":
                    queue.put_nowait({
                        "id": m_id,
                        "type": "call",
                        "content": json.dumps(content, ensure_ascii=False),
                        "name": content.get("name"),
                    })
                elif content.get("type") == "tool_result":
                    queue.put_nowait({
                        "id": m_id,
                        "type": "response",
                        "content": json.dumps(content, ensure_ascii=False),
                        "name": content.get("name"),
                    })
                else:
                    queue.put_nowait({
                        "id": m_id,
                        "type": m_type,
                        "content": json.dumps(content, ensure_ascii=False),
                    })
            else:
                queue.put_nowait({"id": m_id, "type": m_type, "content": str(content)})

        async def hooked_print(content, *args, **kwargs):
            if isinstance(content, Msg):
                msg_content = content.content
                has_tool = False
                if isinstance(msg_content, list):
                    for item in msg_content:
                        if isinstance(item, dict) and item.get("type") in ["tool_use", "tool_result"]:
                            has_tool = True
                            break
                elif isinstance(msg_content, dict) and msg_content.get("type") in ["tool_use", "tool_result"]:
                    has_tool = True

                should_log = False
                if has_tool:
                    s = json.dumps(msg_content, ensure_ascii=False)
                    if "tool_result" in s:
                        should_log = True

                if should_log:
                    logger.info(f"[Agent {content.name} Tool Result] {json.dumps(msg_content, ensure_ascii=False)}")

                message_handler(content)

        agent.print = hooked_print

        async def run_task():
            nonlocal pending_thought
            start_time = time.time()
            full_answer = ""
            status = "Success"
            error_msg = None
            try:
                msg = Msg("user", user_query, role="user")
                final_res = await agent(msg)

                def _extract_text(content):
                    if isinstance(content, str):
                        return content
                    if isinstance(content, list):
                        parts = []
                        for item in content:
                            if isinstance(item, str):
                                parts.append(item)
                            elif isinstance(item, dict) and "text" in item:
                                parts.append(item["text"])
                        return "".join(parts)
                    return str(content) if content else ""

                # 提取最终答案用于日志记录
                full_answer = _extract_text(final_res.content if hasattr(final_res, "content") else str(final_res))
                if full_answer:
                    full_answer = re.sub(r"^Final Answer:\s*", "", full_answer, flags=re.IGNORECASE).strip()

                if pending_thought:
                    pt = pending_thought
                    pending_thought = None
                    final_text = _extract_text(pt.content)
                    if final_text:
                        final_text = re.sub(r"^Final Answer:\s*", "", final_text, flags=re.IGNORECASE).strip()
                        if final_text:
                            # 已经通过 full_answer 提取过了,这里只需要流式发送
                            logger.info(f"[Agent WikiAssistant Final Answer] {final_text}")
                            m_id = f"msg-{datetime.now().timestamp()}"
                            chunk_size = 4
                            for i in range(0, len(final_text), chunk_size):
                                queue.put_nowait({"id": m_id, "type": "stream", "content": final_text[i:i+chunk_size]})
                                await asyncio.sleep(0.01)
                            return

                # 兜底:message_handler 未能拦截到 Final Answer 时,从 full_answer 中提取并流式发送
                if not final_answer_sent:
                    if full_answer:
                        logger.info(f"[Agent WikiAssistant Final Answer] {full_answer}")
                        m_id = f"msg-{datetime.now().timestamp()}"
                        for i in range(0, len(full_answer), 4):
                            queue.put_nowait({"id": m_id, "type": "stream", "content": full_answer[i:i+4]})
                            await asyncio.sleep(0.01)

            except Exception as e:
                status = "Error"
                error_msg = str(e)
                queue.put_nowait({"type": "error", "content": str(e)})
                # 缺陷1:使用 logger 替代 traceback.print_exc()
                logger.exception(f"Query stream 执行异常: {e}")
            finally:
                total_tokens = get_tokens()
                duration_ms = int((time.time() - start_time) * 1000)
                
                # 异步落表
                await save_query_log_to_db(
                    user_query,
                    history,
                    full_answer,
                    QUERY_MODEL_NAME,
                    total_tokens,
                    duration_ms,
                    status,
                    error_msg,
                    session_id
                )
                
                if total_tokens > 0:
                    logger.info(f"[Query] 本次查询 Token 消耗: {total_tokens}")
                queue.put_nowait("[DONE]")

        # 缺陷5:run_task 也使用 create_task 但注册 done_callback 处理未检索的异常
        task = asyncio.create_task(run_task())
        task.add_done_callback(
            lambda t: logger.error(f"[Query] run_task 异常退出: {t.exception()}", exc_info=t.exception())
            if not t.cancelled() and t.exception() else None
        )

        while True:
            item = await queue.get()
            if item == "[DONE]":
                yield "data: [DONE]\n\n"
                break
            yield f"data: {json.dumps(item, ensure_ascii=False)}\n\n"


async def run_wiki_query_json(user_query: str, history: list) -> dict:
    """
    非流式执行 Wiki 查询。直接返回包含解答的字典。
    问题9:使用 token_counter_context 追踪 Token 消耗。
    """
    # 问题9:Token 追踪
    async with token_counter_context() as get_tokens:
        agent = build_query_agent(history)
        agent.set_console_output_enabled(True)

        logger.info(f"[JSON Query] 收到查询请求: {user_query}")

        msg = Msg("user", user_query, role="user")
        final_res = await agent(msg)

        def _extract_text(content):
            if isinstance(content, str):
                return content
            if isinstance(content, list):
                parts = []
                for item in content:
                    if isinstance(item, str):
                        parts.append(item)
                    elif isinstance(item, dict) and "text" in item:
                        parts.append(item["text"])
                return "".join(parts)
            return str(content) if content else ""

        fc = _extract_text(final_res.content if hasattr(final_res, "content") else str(final_res))
        if fc:
            fc = re.sub(r"^Final Answer:\s*", "", fc, flags=re.IGNORECASE).strip()

        total_tokens = get_tokens()
        if total_tokens > 0:
            logger.info(f"[JSON Query] Token 消耗: {total_tokens}")

        return {"answer": fc, "tokens": total_tokens}