query.py 15.9 KB
import asyncio
import json
import re
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
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()


@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", [])
    logger.info(f"收到 Wiki 查询请求: query='{user_query}', 历史消息长度={len(history)}")
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    # 缺陷5:改用 background_tasks.add_task 替代 asyncio.create_task(fire-and-forget 修复)
    async def log_query_db():
        try:
            async with AsyncSessionLocal() as session:
                log = WikiOperationLog(
                    operation="WIKI_QUERY",
                    details=json.dumps({"query": user_query, "model": QUERY_MODEL_NAME}, ensure_ascii=False)
                )
                session.add(log)
                await session.commit()
        except Exception as e:
            logger.error(f"查询日志写入数据库失败: {e}", exc_info=True)

    if background_tasks:
        background_tasks.add_task(log_query_db)

    event_generator = run_wiki_query_stream(user_query, history)
    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", [])
    logger.info(f"收到 Wiki JSON查询请求: query='{user_query}', 历史消息长度={len(history)}")
    if not user_query:
        raise HTTPException(status_code=400, detail="Query is empty")

    # 缺陷5:改用 background_tasks.add_task 替代 asyncio.create_task
    async def log_query_db():
        try:
            async with AsyncSessionLocal() as session:
                log = WikiOperationLog(
                    operation="WIKI_QUERY_JSON",
                    details=json.dumps({"query": user_query, "model": QUERY_MODEL_NAME}, ensure_ascii=False)
                )
                session.add(log)
                await session.commit()
        except Exception as e:
            logger.error(f"查询日志写入数据库失败: {e}", exc_info=True)

    if background_tasks:
        background_tasks.add_task(log_query_db)

    try:
        result = await run_wiki_query_json(user_query, history)
        return result
    except Exception as e:
        logger.exception(f"JSON 查询执行失败: {e}")
        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):
    """
    流式执行 Wiki 查询。返回一个异步生成器,产出 Server-Sent Events (SSE) 字符串。
    问题9:使用 token_counter_context 追踪 Token 消耗。
    """
    # 问题9:Token 追踪
    async with token_counter_context() as get_tokens:
        agent = build_query_agent(history)
        queue = asyncio.Queue()
        pending_thought = None

        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 message_handler(msg: Msg):
            nonlocal pending_thought
            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:
                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
            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 ""

                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:
                            logger.info(f"[Agent WikiAssistant Final Answer] {final_text[:200]}...")
                            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

                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()
                    if fc:
                        logger.info(f"[Agent WikiAssistant Final Answer] {fc[:200]}...")
                        m_id = f"msg-{datetime.now().timestamp()}"
                        for i in range(0, len(fc), 4):
                            queue.put_nowait({"id": m_id, "type": "stream", "content": fc[i:i+4]})
                            await asyncio.sleep(0.01)

            except Exception as 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()
                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}