test_llm_compat.py 8.38 KB
"""OpenAI 兼容接口(LLM_BASE_URL 有值时):带思考参数、流式、接入调用追踪、能被终止。

不连网:requests.post 换成按行吐 SSE 的假响应。
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).parent))

from app.core import llm
from app.governance import llmlog
from test_platform import env  # noqa: F401

DS = "https://dashscope.aliyuncs.com/compatible-mode/v1"


def sse(*chunks: dict) -> list[bytes]:
    return [b"data: " + json.dumps(c, ensure_ascii=False).encode() for c in chunks] + [b"", b"data: [DONE]"]


def delta(think: str = "", text: str = "") -> dict:
    return {"choices": [{"delta": {"reasoning_content": think, "content": text}}]}


USAGE = {"choices": [], "usage": {"prompt_tokens": 30, "completion_tokens": 20,
                                  "completion_tokens_details": {"reasoning_tokens": 12}}}


class FakeResp:
    def __init__(self, lines: list[bytes], status: int = 200, text: str = ""):
        self.lines, self.status_code, self.text = lines, status, text

    def __enter__(self):
        return self

    def __exit__(self, *a):
        return False

    def iter_lines(self, decode_unicode=False):
        yield from self.lines


@pytest.fixture()
def post(monkeypatch):
    """记下每次请求体;每次返回 post.next 里排好的响应。"""
    sent: list[dict] = []
    queue: list[FakeResp] = []

    def fake(url, headers=None, json=None, timeout=None, stream=False):    # noqa: A002
        sent.append({"url": url, "body": json, "stream": stream, "timeout": timeout})
        return queue.pop(0)
    monkeypatch.setattr(llm.requests, "post", fake)
    monkeypatch.setattr(llm.time, "sleep", lambda s: None)
    fake.sent, fake.queue = sent, queue
    return fake


@pytest.fixture()
def cfg(monkeypatch):
    vals = {"QWEN_MODEL": "qwen3.7-plus", "LLM_BASE_URL": DS, "LLM_THINKING": "auto", "LLM_THINKING_BUDGET": "4096",
            "LLM_CACHE": "0"}
    monkeypatch.setattr(llm.db, "get_config", lambda k, d=None: vals.get(k, d if d is not None else ""))
    return vals


class Sink:
    def __init__(self, cancel_at: int = 0):
        self.updates, self.ended, self.began, self.cancel_at = [], [], [], cancel_at

    def begin(self, label, feature, model, prompt):
        self.began.append((label, feature, model))
        return len(self.began)

    def update(self, h, reasoning, output):
        self.updates.append((reasoning, output))
        if self.cancel_at and len(self.updates) >= self.cancel_at:
            raise llm.Cancelled()

    def end(self, h, **kw):
        self.ended.append(kw)


MSGS = [{"role": "user", "content": "你好"}]


def test_非追踪_累加输出_思考不进正文(post, cfg):
    post.queue.append(FakeResp(sse(delta("先想", ""), delta("再想", ""), delta("", "好"), delta("", "的"), USAGE)))
    assert llm.chat(MSGS, use_cache=False) == "好的"
    sent = post.sent[0]
    assert sent["url"] == DS + "/chat/completions" and sent["stream"] is True
    assert sent["timeout"] == (15, 180)                       # 只限两块之间的空档,思考再长不会撞整体超时


@pytest.mark.parametrize("feature,mode,want", [
    ("modeling_rules", "auto", {"thinking_budget": 4096}),       # 起草类:思考,但限预算
    ("modeling_check", "auto", {"enable_thinking": False}),      # 对账:不用长考
    ("ask", "auto", {}),                                        # 提问:思考不限
    ("modeling_metric_unknown", "auto", {"enable_thinking": False}),   # 不在白名单:不思考
    ("ask", "off", {"enable_thinking": False}),
])
def test_带上思考参数(post, cfg, feature, mode, want):
    cfg["LLM_THINKING"] = mode
    post.queue.append(FakeResp(sse(delta("", "x"))))
    with llmlog.feature(feature):
        llm.chat(MSGS, use_cache=False)
    body = post.sent[0]["body"]
    assert body["stream_options"] == {"include_usage": True}
    for k in ("enable_thinking", "thinking_budget"):
        assert body.get(k) == want.get(k)
    assert ("enable_thinking" in body) == ("enable_thinking" in want)
    assert ("thinking_budget" in body) == ("thinking_budget" in want)


def test_别家服务不发扩展参数(post, cfg):
    cfg["LLM_BASE_URL"] = "http://localhost:8000/v1"
    cfg["LLM_THINKING"] = "off"
    post.queue.append(FakeResp(sse(delta("", "x"))))
    llm.chat(MSGS, use_cache=False)
    body = post.sent[0]["body"]
    assert not {"enable_thinking", "thinking_budget", "stream_options"} & set(body)
    assert body["stream"] is True


def test_追踪_思考过程_用量_耗时(post, cfg, monkeypatch):
    t = iter([0.0, 0.0, 2.0, 4.0, 6.0, 6.0, 6.0, 6.0])         # 让「约每 1.5 秒报一次」每块都触发
    monkeypatch.setattr(llm.time, "time", lambda: next(t, 9.0))
    post.queue.append(FakeResp(sse(delta("想一", ""), delta("想二", ""), delta("", "答"), USAGE)))
    sink = Sink()
    with llm.tracing(sink, "读文档"), llmlog.feature("modeling_rules"):
        assert llm.chat(MSGS, use_cache=False) == "答"
    assert sink.began and sink.began[0][0] == "读文档" and sink.began[0][2] == "qwen3.7-plus"
    assert sink.updates and sink.updates[-1][0].startswith("想一")
    end = sink.ended[0]
    assert end["output"] == "答" and end["reasoning"] == "想一想二"
    assert end["usage"] == {"input_tokens": 30, "output_tokens": 20, "output_tokens_details": {"reasoning_tokens": 12}}


def test_追踪_建模记录里拆出思考token(env, post, cfg):
    """和 modeling._Calls 对接:usage 里 output_tokens 含思考,记录里要拆成输出 + 思考。"""
    from app.core.dbx import session
    from app.kernel import modeling
    from app.kernel.models import ModelCall
    doc = ("# 工单\n\n" + "内容。" * 50).encode("utf-8")
    run = modeling.create("工单", files=[("工单.md", doc)], ds_ids=[], stages=["convert", "draft"])
    post.queue.append(FakeResp(sse(delta("想", "答"), USAGE)))
    with llm.tracing(modeling._Calls(run["id"], "convert"), "读文档"):
        assert llm.chat(MSGS, use_cache=False) == "答"
    with session() as s:
        row = s.query(ModelCall).filter(ModelCall.run_id == run["id"]).one()
    assert row.status == "done" and row.reasoning == "想" and row.output == "答"
    assert (row.prompt_tokens, row.output_tokens, row.reasoning_tokens) == (30, 8, 12)


def test_追踪_终止不重试(post, cfg, monkeypatch):
    post.queue.append(FakeResp(sse(delta("想", ""))))
    post.queue.append(FakeResp(sse(delta("不该被请求", ""))))
    sink = Sink(cancel_at=1)
    seq = iter(range(0, 1000, 5))                           # 每次取时间都过了 5 秒:第一块就触发 update
    monkeypatch.setattr(llm.time, "time", lambda: next(seq))
    with llm.tracing(sink, "x"):
        with pytest.raises(llm.Cancelled):
            llm.chat(MSGS, use_cache=False)
    assert len(post.sent) == 1                              # 终止了就别再请求
    assert sink.ended and sink.ended[0]["error"] == "已终止"


def test_HTTP出错_重试后报错并带上返回内容(post, cfg):
    for _ in range(3):
        post.queue.append(FakeResp([], status=400, text='{"error":"url error"}'))
    with pytest.raises(RuntimeError, match="url error"):
        llm.chat(MSGS, use_cache=False)
    assert len(post.sent) == 3


def test_流式提问_也带思考参数(post, cfg):
    cfg["LLM_THINKING"] = "off"
    post.queue.append(FakeResp(sse(delta("想", ""), delta("", "你"), delta("", "好"))))
    assert "".join(llm._stream_openai(DS, "m", MSGS, 0.3)) == "你好"        # 思考不当作回答吐出去
    assert post.sent[0]["body"]["enable_thinking"] is False


def test_AI建模换模型_自动走兼容接口(post, cfg, monkeypatch):
    """全局走 SDK(没配兼容地址)、对话模型是别的:建模范围里换成 qwen3.7-plus,自动走 DashScope 兼容接口。"""
    cfg["LLM_BASE_URL"] = ""
    cfg["QWEN_MODEL"] = "deepseek-v4-flash-0731"
    monkeypatch.setattr(llm, "_chat_dashscope", lambda *a, **k: pytest.fail("换了模型就不该走 SDK"))
    post.queue.append(FakeResp(sse(delta("", "好"))))
    with llm.use_model("qwen3.7-plus"):
        assert llm.chat(MSGS, use_cache=False) == "好"
    assert post.sent[0]["url"] == DS + "/chat/completions" and post.sent[0]["body"]["model"] == "qwen3.7-plus"
    with llm.use_model(""):                                    # 没配建模模型:照旧用对话模型
        assert llm._route() == ("deepseek-v4-flash-0731", "")