llm.py 7.93 KB
"""
大语言模型(LLM)与词向量(Embedding)调用模块。
对大语言模型进行统一封装,提供了流式与非流式对话接口,
以及支持批量处理与内存缓存的 Embedding 向量化功能。
"""
import logging
import threading
import time
from collections import OrderedDict
from typing import Iterable

from agentscope.message import Msg

from config import API_KEY
from src.rag.core.config import RAG_EMBED_BATCH_SIZE  # noqa: F401  (下方 import 合并)
from src.rag.core.config import (
    RAG_EMBEDDING_MODEL,
    RAG_QUERY_CACHE_SIZE,
    RAG_QUERY_CACHE_TTL_SECONDS,
)
from src.utils.llm_models import extract_text_content, extract_thinking_content
from src.utils.llm_tracker import get_llm_model, stream_delta

logger = logging.getLogger(__name__)

# 用于缓存 Query 文本对应的 Embedding 向量结果,以降低 API 成本和加速重复检索
_embedding_cache: OrderedDict[str, tuple[float, list[float]]] = OrderedDict()
# 读写缓存时的线程锁,保证并发安全
_cache_lock = threading.RLock()


async def chat_once(model_name: str, prompt: str, *, purpose: str | None = None) -> str:
    """
    进行单次(非流式)的大语言模型对话请求。
    
    :param model_name: 调用的模型名称
    :param prompt: 构建好的完整提示词
    :return: 模型生成的纯文本字符串结果
    """
    model = get_llm_model(model_name, purpose=purpose)
    res = await model([{"role": "user", "content": prompt}])
    
    # 兼容处理某些模型可能返回异步迭代器(流)的情况
    if hasattr(res, "__aiter__"):
        final_chunk = None
        async for chunk in res:
            final_chunk = chunk
        res = final_chunk

    return extract_text_content(getattr(res, "content", ""))


async def chat_stream(model_name: str, prompt: str, *, include_thinking: bool = False, purpose: str | None = None):
    """
    进行流式大语言模型对话请求,按块(Chunk)不断产出生成结果。
    
    :param model_name: 调用的模型名称
    :param prompt: 构建好的完整提示词
    :param include_thinking: 是否需要返回模型“思考”过程的文本(如某些带有深度思考机制的模型)
    :yield: 不断吐出格式如 {"type": "answer_delta", "content": "..."} 的字典
    """
    model = get_llm_model(model_name, purpose=purpose)
    res = await model([{"role": "user", "content": prompt}])

    # 若模型返回的是异步生成器(正常流式表现)
    if hasattr(res, "__aiter__"):
        full_text = ""
        full_thinking = ""
        async for chunk in res:
            content = getattr(chunk, "content", "")
            text = extract_text_content(content)
            thinking = extract_thinking_content(content)

            # 用 stream_delta 兼容「累计式/增量式」两类模型,避免切片错位导致重复或金字塔
            text_delta, full_text = stream_delta(full_text, text)
            thinking_delta, full_thinking = stream_delta(full_thinking, thinking)

            if include_thinking and thinking_delta:
                yield {"type": "thinking_delta", "content": thinking_delta}
            if text_delta:
                yield {"type": "answer_delta", "content": text_delta}
    else:
        # 兼容处理未开启流式时,直接一次性返回了结果的情况
        content = getattr(res, "content", "")
        text = extract_text_content(content)
        thinking = extract_thinking_content(content)
            
        if include_thinking and thinking:
            yield {"type": "thinking_delta", "content": thinking}
        if text:
            yield {"type": "answer_delta", "content": text}


def embed_texts(texts: list[str], *, allow_cache: bool = False) -> list[list[float]]:
    """
    调用阿里云 DashScope 的文本向量化(Embedding)接口,将字符串数组批量转换为高维浮点数向量。
    
    :param texts: 需要向量化的字符串列表
    :param allow_cache: 是否允许从本地内存缓存中直接返回(通常仅在查询阶段且单个输入时开启)
    :return: 对应的二维向量数组
    """
    if not texts:
        return []
        
    # 如果允许缓存且只有一个文本(通常是用户搜索的 Query),优先检查缓存
    if allow_cache and len(texts) == 1:
        cached = _get_cached_embedding(texts[0])
        if cached is not None:
            return [cached]
            
    try:
        import dashscope

        start = time.time()
        vectors = []
        # 按批量 10 个一组请求 Embedding 接口,避免请求超载
        for i in range(0, len(texts), RAG_EMBED_BATCH_SIZE):
            batch_texts = texts[i : i + 10]
            
            max_retries = 3
            resp = None
            # 添加重试机制
            for attempt in range(max_retries):
                try:
                    resp = dashscope.TextEmbedding.call(model=RAG_EMBEDDING_MODEL, input=batch_texts, api_key=API_KEY)
                    if getattr(resp, "status_code", 200) != 200:
                        raise RuntimeError(f"DashScope embedding failed: {resp}")
                    break  # Success
                except Exception as e:
                    if attempt < max_retries - 1:
                        logger.warning("[RAG] DashScope API 调用异常,正在重试 (%s/%s): %s", attempt + 1, max_retries - 1, e)
                        time.sleep(1.0 * (attempt + 1))
                    else:
                        raise

            # 解析接口返回的向量结果
            output = resp.get("output") if isinstance(resp, dict) else getattr(resp, "output", None)
            embeddings = output.get("embeddings", []) if isinstance(output, dict) else []
            batch_vectors = [item["embedding"] for item in embeddings]
            vectors.extend(batch_vectors)
            
        if len(vectors) != len(texts):
            raise RuntimeError(f"DashScope embedding count mismatch: expected={len(texts)} actual={len(vectors)}")
            
        logger.info(
            "[RAG] Embedding 完成: model=%s texts=%s dim=%s duration_ms=%s",
            RAG_EMBEDDING_MODEL,
            len(texts),
            len(vectors[0]),
            int((time.time() - start) * 1000),
        )
        
        # 将单个查询成功的结果写入缓存
        if allow_cache and len(texts) == 1:
            _set_cached_embedding(texts[0], vectors[0])
            
        return vectors
    except Exception as exc:
        logger.exception("[RAG] Embedding API 不可用")
        raise RuntimeError("Embedding API 不可用,已停止索引/检索") from exc


def embedding_model_name() -> str:
    """返回当前系统正在使用的 Embedding 模型名称。"""
    return RAG_EMBEDDING_MODEL


def _cache_key(text: str) -> str:
    """构建缓存主键,带上模型名以防模型切换导致向量维度或含义不匹配。"""
    return f"{RAG_EMBEDDING_MODEL}:{text}"


def _get_cached_embedding(text: str) -> list[float] | None:
    """尝试从内存 LRU 队列中读取有效的 Embedding 缓存向量。"""
    key = _cache_key(text)
    now = time.time()
    with _cache_lock:
        cached = _embedding_cache.get(key)
        if not cached:
            return None
        ts, vector = cached
        # 判断缓存是否过期
        if now - ts > RAG_QUERY_CACHE_TTL_SECONDS:
            _embedding_cache.pop(key, None)
            return None
        # 使用过后移动到有序字典末尾,维持 LRU 机制
        _embedding_cache.move_to_end(key)
        return vector


def _set_cached_embedding(text: str, vector: list[float]) -> None:
    """将刚刚计算的文本 Embedding 结果保存到 LRU 内存缓存中。"""
    key = _cache_key(text)
    with _cache_lock:
        _embedding_cache[key] = (time.time(), vector)
        _embedding_cache.move_to_end(key)
        # 容量控制,超出则剔除最早未被使用的缓存项
        while len(_embedding_cache) > RAG_QUERY_CACHE_SIZE:
            _embedding_cache.popitem(last=False)