llm_tracker.py 6.71 KB
import asyncio
import os
import functools
import contextlib
import contextvars
import agentscope
from agentscope.model import DashScopeChatModel
from config import SKILLS_DIR, API_KEY, is_multimodal, is_thinking
from src.utils.logger import StreamTranscript

# ==================================================================================
# 核心组件:Token 消耗跟踪器 (Token Tracker)
# ==================================================================================
# 引入 ContextVar (上下文变量) 机制。
# 在高并发的 FastAPI 异步处理环境下,多个文件的 Ingest (摄入) 任务会同时运行。
# 使用传统的全局变量会导致 Token 统计互相干扰串数据。
# ContextVar 能够保证在同一个协程上下文中,Token 统计是完全隔离且线程/协程安全的。
current_task_tokens = contextvars.ContextVar("current_task_tokens")
print_thinking = contextvars.ContextVar("print_thinking", default=True)


def stream_delta(prev_full: str, chunk_text: str) -> tuple[str, str]:
    """模型无关地求「新增增量」与「新的累计全文」,兼容两类流式语义:

    - 累计式:每个 chunk 返回到目前为止的全文(chunk_text 以 prev_full 为前缀)→ 取尾部增量;
    - 增量式:每个 chunk 只返回新片段(不以 prev_full 为前缀)→ 直接作为增量拼接。

    避免对增量式模型误用切片导致重复/越来越长的「金字塔」式输出与日志。
    返回 (delta, new_full)。
    """
    if not chunk_text or chunk_text == prev_full:
        return "", prev_full
    if chunk_text.startswith(prev_full):
        # 累计式:新增的尾部即增量
        return chunk_text[len(prev_full):], chunk_text
    # 增量式(或前后不一致):把本次 chunk 当作新片段直接拼接
    return chunk_text, prev_full + chunk_text


class TrackingDashScopeChatModel(DashScopeChatModel):
    """
    模型监控包装类 (Wrapper):继承自 AgentScope 的原生 DashScopeChatModel,
    并重写了底层的大模型调用 __call__ 方法。

    目的:
    在不依赖全局 Monitor (监控器) 的情况下,实现细粒度、按任务隔离的 Token 消耗精准捕获。
    支持阻塞调用和流式输出(Generator)两种情况的统计。
    """

    async def __call__(self, *args, **kwargs):
        # 首先调用父类的原始 __call__ 获取大模型响应
        res = super().__call__(*args, **kwargs)
        # 如果返回的是一个协程对象,则等待其执行完成
        if asyncio.iscoroutine(res):
            res = await res

        # 判断响应是否是流式(Stream)输出迭代器
        if hasattr(res, "__aiter__"):
            # 针对流式输出,必须拦截并代理底层的异步生成器 async_generator
            async def wrapped_generator():
                last_input = 0
                last_output = 0
                full_thinking = ""
                transcript = StreamTranscript(f"{getattr(self, 'model_name', 'model')} thinking")
                # 逐块(Chunk)读取大模型流式响应
                async for chunk in res:
                    # 并非所有的 Chunk 都会携带 usage 字段,通常只有最后一个 Chunk 包含总计 Token
                    if hasattr(chunk, "usage") and chunk.usage:
                        # 实时更新获取到的最新输入输出 Token
                        last_input = getattr(chunk.usage, "input_tokens", last_input)
                        last_output = getattr(chunk.usage, "output_tokens", last_output)

                    # 实时打印思维链:用 stream_delta 兼容「累计/增量」两类模型,避免阶梯式重复
                    if hasattr(chunk, "content") and isinstance(chunk.content, list):
                        chunk_thinking = "".join(
                            str(block.get("thinking", ""))
                            for block in chunk.content
                            if isinstance(block, dict) and block.get("type") == "thinking"
                        )
                        delta, full_thinking = stream_delta(full_thinking, chunk_thinking)
                        if delta and print_thinking.get():
                            transcript.write(delta)

                    # 将当前 Chunk 原封不动 yield 给上层业务
                    yield chunk

                if full_thinking and print_thinking.get():
                    transcript.write("\n")
                    transcript.close()

                # 流式输出全部结束后,计算总 Token 并累加到当前任务的 ContextVar 计数器中
                counter = current_task_tokens.get(None)
                if counter is not None:
                    counter[0] += last_input + last_output

            # 替换原生生成器为代理生成器
            return wrapped_generator()
        else:
            # 针对非流式输出的普通请求,直接从响应对象中获取 usage 消耗
            if hasattr(res, "usage") and res.usage:
                i_tok = getattr(res.usage, "input_tokens", 0)
                o_tok = getattr(res.usage, "output_tokens", 0)
                counter = current_task_tokens.get(None)
                if counter is not None:
                    # 累加 Token 消耗
                    counter[0] += i_tok + o_tok

        return res


# 初始化 AgentScope 框架
agentscope.init()


def get_llm_model(model_name: str) -> TrackingDashScopeChatModel:
    """根据传入的模型名称动态实例化 TrackingDashScopeChatModel。"""
    return TrackingDashScopeChatModel(
        model_name=model_name,
        api_key=API_KEY,
        multimodality=is_multimodal(model_name),
        enable_thinking=is_thinking(model_name),
        generate_kwargs={"temperature": 0.5} if "deepseek" not in model_name.lower() else {}
    )


@functools.lru_cache(maxsize=None)
def load_skill_prompt(skill_name: str) -> str:
    """根据技能名称从 skills 目录加载对应的 SKILL.md 提示词内容。"""
    skill_path = os.path.join(SKILLS_DIR, skill_name, "SKILL.md")
    if os.path.exists(skill_path):
        with open(skill_path, "r", encoding="utf-8") as f:
            return f.read()
    return ""


@contextlib.asynccontextmanager
async def token_counter_context():
    """
    异步上下文管理器:在任意模块(Query、Lint 等)中追踪 Token 消耗。

    用法示例:
        async with token_counter_context() as get_tokens:
            # 执行 LLM 调用 ...
            total = get_tokens()  # 获取本次上下文内的 Token 消耗总量
    """
    counter = [0]
    token = current_task_tokens.set(counter)
    try:
        yield lambda: counter[0]
    finally:
        try:
            current_task_tokens.reset(token)
        except ValueError:
            pass