JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix: 重试时增加日志打印
renquanjia5362b2282f1e
diff --git a/jiuwenswarm/llm_sse_patch.py b/jiuwenswarm/llm_sse_patch.pyindex 5f15a49204..ec374b3d0c 100644--- a/jiuwenswarm/llm_sse_patch.py+++ b/jiuwenswarm/llm_sse_patch.py@@ -39,6 +39,7 @@ import reimport timeimport uuidfrom typing import Any, Optional+from urllib.parse import urlsplitlogger = logging.getLogger("jiuwenswarm.llm_sse_patch")@@ -705,34 +706,59 @@ def apply_huawei_maas_span_id_patch() -> None:async def _stream_with_maas_span(self: Any, *args, **kwargs):_maybe_inject_maas_span_id(self, kwargs)+ _mcc = getattr(self, "model_client_config", None)+ _mc = getattr(self, "model_config", None)+ _span = (+ _span_id_value(kwargs.get("custom_headers"))+ or _span_id_value(getattr(_mcc, "custom_headers", None))+ or "-"+ )+ logger.info(+ "[MODEL_HTTP] begin span=%s model=%s host=%s idle_timeout=%s",+ _span,+ kwargs.get("model") or getattr(_mc, "model_name", "") or "-",+ urlsplit(str(getattr(_mcc, "api_base", "") or "")).netloc or "-",+ getattr(_mcc, "stream_idle_timeout", None),+ )# [PERF] 打点:LLM 流调用 TTFT 与总时长import time as _perf_time_t0 = _perf_time.perf_counter()- _ttft_logged = False+ _ttft_ms = None_producer_s = 0.0_n_chunks = 0+ _status = "ok"+ _exc_name = "-"_it = _orig_stream(self, *args, **kwargs)- while True:- _t_next = _perf_time.perf_counter()- try:- chunk = await _it.__anext__()- except StopAsyncIteration:- break- _producer_s += _perf_time.perf_counter() - _t_next- _n_chunks += 1- if not _ttft_logged:- _ttft_logged = True- logger.info(- "[PERF] llm_stream ttft_ms=%.1f",- (_perf_time.perf_counter() - _t0) * 1000,- )- yield chunk- logger.info(- "[PERF] llm_stream total_ms=%.1f producer_ms=%.1f chunks=%d",- (_perf_time.perf_counter() - _t0) * 1000,- _producer_s * 1000,- _n_chunks,- )+ try:+ while True:+ _t_next = _perf_time.perf_counter()+ try:+ chunk = await _it.__anext__()+ except StopAsyncIteration:+ break+ _producer_s += _perf_time.perf_counter() - _t_next+ _n_chunks += 1+ if _ttft_ms is None:+ _ttft_ms = (_perf_time.perf_counter() - _t0) * 1000+ logger.info("[PERF] llm_stream ttft_ms=%.1f", _ttft_ms)+ yield chunk+ except BaseException as exc:+ _status = "error"+ _exc_name = type(exc).__name__+ raise+ finally:+ # 正常结束、超时、取消都打:失败时也要留下本次尝试的汇总+ logger.info(+ "[MODEL_HTTP] end span=%s status=%s chunks=%d ttft_ms=%s producer_ms=%.1f "+ "total_ms=%.1f exc=%s",+ _span,+ _status,+ _n_chunks,+ f"{_ttft_ms:.1f}" if _ttft_ms is not None else "-",+ _producer_s * 1000,+ (_perf_time.perf_counter() - _t0) * 1000,+ _exc_name,+ )client_cls.invoke = _invoke_with_maas_spanclient_cls.stream = _stream_with_maas_spandiff --git a/tests/unit_tests/test_llm_sse_patch_granularity.py b/tests/unit_tests/test_llm_sse_patch_granularity.pyindex b929406fcd..3a1ae5cb54 100644--- a/tests/unit_tests/test_llm_sse_patch_granularity.py+++ b/tests/unit_tests/test_llm_sse_patch_granularity.py@@ -15,6 +15,7 @@from __future__ import annotationsimport asyncio+import loggingfrom types import SimpleNamespacefrom typing import Any@@ -240,6 +241,58 @@ def test_maas_span_id_replaces_blank_value(assert len(headers["x-span-id"]) == 32+# ── 流式请求发送前日志 ───────────────────────────────────────────────+++def test_stream_logs_request_before_send(+ monkeypatch: pytest.MonkeyPatch, fresh_patch_state: None, caplog: pytest.LogCaptureFixture+) -> None:+ """无论后续是否超时,发请求前都必须先落一行(带 span/模型/超时参数)。"""++ async def _fake_stream(self: Any, *args: Any, **kwargs: Any):+ yield "chunk-1"+ raise asyncio.CancelledError()++ monkeypatch.setattr(oai_mod.OpenAIModelClient, "stream", _fake_stream)+ patch_mod.apply_huawei_maas_span_id_patch()++ client = SimpleNamespace(+ model_client_config=SimpleNamespace(+ api_base="https://modelarts-maas.cn/v1",+ stream_idle_timeout=60,+ ),+ model_config=SimpleNamespace(model_name="glm-5.3"),+ )+ caplog.set_level(logging.INFO, logger="jiuwenswarm.llm_sse_patch")++ async def _run() -> None:+ async for _chunk in oai_mod.OpenAIModelClient.stream(+ client, messages=[{"role": "user", "content": "hi"}], model="glm-5.3"+ ):+ pass++ with pytest.raises(asyncio.CancelledError):+ asyncio.run(_run())++ line = next(+ r.getMessage() for r in caplog.records if "[MODEL_HTTP] begin" in r.getMessage()+ )+ assert "span=" in line+ assert "model=glm-5.3" in line+ assert "host=modelarts-maas.cn" in line+ assert "idle_timeout=60" in line++ # 失败也必须留下 end 汇总,不能只在正常结束时打+ end = next(+ r.getMessage() for r in caplog.records if "[MODEL_HTTP] end" in r.getMessage()+ )+ assert "status=error" in end+ assert "chunks=1" in end+ assert "exc=CancelledError" in end+ # end 必须带上本次尝试的 span,失败行才能直接拿去 MaaS 侧对账+ assert f"span={line.split('span=', 1)[1].split(' ', 1)[0]}" in end++# ── P1:渠道门控读取路径 ──────────────────────────────────────────────