feat(calllog): 详情不截断记录(捕获/清洗/入库三处上限全部放开)
- 请求体捕获 8000 → 128KiB(_CONTENT_MAX,可用 CALLLOG_BODY_MAX 调) - 回复文本改用新增的 _content():128KiB 且保留换行/制表(_logsafe 会把换行压成 ?) - 入库上限 CALLLOG_CONTENT_MAX 默认 8000 → 256KiB(实际等于不截断) - 详情新增 prompt_full(完整提取内容,保留换行),与原始 JSON 并列展示 - BODY_BY_RID 有界 128 条,防止宽上限下内存膨胀 - 版本 2.9.1 → 2.9.2
This commit is contained in:
1 parent
ee42754095
commit
4ef03aa8f0
4 files changed
+74
-19
No files matched your search
@@ -1,5 +1,31 @@
|
|||||||
# CHANGELOG
|
# CHANGELOG
|
||||||
|
|
||||||
|
## 2026-10-23 · 详情不再截断记录(2.9.1 → 2.9.2)
|
||||||
|
|
||||||
|
老板:「点击进去看详情内容的时候不要截断记录」。
|
||||||
|
|
||||||
|
截断原本发生在**三个环节**,逐个拆掉:
|
||||||
|
|
||||||
|
| 环节 | 原来 | 现在 |
|
||||||
|
|---|---|---|
|
||||||
|
| 请求体捕获 | `raw[:2000]`(后提到 8000)| `raw[:_CONTENT_MAX]`,默认 **128 KiB**(≈32k tokens)|
|
||||||
|
| 回复文本 | `_logsafe(..., 8000)` | 新增 `_content()`:上限 **128 KiB**,且**保留换行/制表** |
|
||||||
|
| 入库 | `CALLLOG_CONTENT_MAX=8000` | 默认 **262144(256 KiB)**,实际等于不截断 |
|
||||||
|
|
||||||
|
**为什么换掉 `_logsafe`**:它是给单行文本日志用的(把 `\n` 压成 `?` 防日志行伪造),
|
||||||
|
用在调用日志上会把多行提示词全压成一行 `?`,详情根本没法看。新加的 `_content()`
|
||||||
|
只剥 NUL 等不可见控制字符,**换行与制表原样保留**。
|
||||||
|
|
||||||
|
- 详情接口新增 `prompt_full`:**完整提取出的输入内容**(保留换行排版),前端详情页
|
||||||
|
分两块展示 ——「内容(完整,保留换行)」+「原始请求体 JSON」(两者都不截断)。
|
||||||
|
- 列表那列仍是单行预览(240 字),不因为详情放开而变重。
|
||||||
|
- `BODY_BY_RID` 有界保留 128 条(宽上限下防止内存膨胀)。
|
||||||
|
|
||||||
|
**实测**:1499 行 / 46860 字符的提示词 → 详情 `prompt_full` 46860 字符 1499 行、
|
||||||
|
原始 JSON 48454 字符,**均无截断标记**。
|
||||||
|
|
||||||
|
> 注意:本次改动只对**新产生**的记录生效;之前的记录在入库时就已被截断,无法回溯。
|
||||||
|
|
||||||
## 2026-10-23 · 调用日志列表加「内容」列(2.9.0 → 2.9.1)
|
## 2026-10-23 · 调用日志列表加「内容」列(2.9.0 → 2.9.1)
|
||||||
|
|
||||||
老板:「列表的模型后面加一个字段,显示请求体的 content 内容」。
|
老板:「列表的模型后面加一个字段,显示请求体的 content 内容」。
|
||||||
|
|||||||
+14
-6
@@ -10,7 +10,7 @@
|
|||||||
- **零新依赖**:`sqlite3` 是标准库,不引入 ORM / 数据库驱动(与本项目"依赖极简"的基调一致)。
|
- **零新依赖**:`sqlite3` 是标准库,不引入 ORM / 数据库驱动(与本项目"依赖极简"的基调一致)。
|
||||||
- **不阻塞请求**:`stage()` 只往内存队列 append;后台 task 每 1 秒或攒满 `BATCH` 条批量写库。
|
- **不阻塞请求**:`stage()` 只往内存队列 append;后台 task 每 1 秒或攒满 `BATCH` 条批量写库。
|
||||||
队列满(默认 10000 条)即丢弃并计数,**绝不反压请求**。
|
队列满(默认 10000 条)即丢弃并计数,**绝不反压请求**。
|
||||||
- **隐私**:API Key 只存前 8 位(`key_id`);提示词/回复按 `CALLLOG_CONTENT_MAX` 截断(默认 8000 字)。
|
- **隐私**:API Key 只存前 8 位(`key_id`);提示词/回复按 `CALLLOG_CONTENT_MAX` 截断(默认 256KiB,实际上"不截断")。
|
||||||
- **保留**:默认 90 天,启动时清理一次 + 每 6 小时清理一次(不依赖外部 cron)。
|
- **保留**:默认 90 天,启动时清理一次 + 每 6 小时清理一次(不依赖外部 cron)。
|
||||||
- **只增不改**:日志表不做 UPDATE;清理只按 `ts` 删。
|
- **只增不改**:日志表不做 UPDATE;清理只按 `ts` 删。
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
- `CALLLOG_DB` 默认 `data/calllog.db`
|
- `CALLLOG_DB` 默认 `data/calllog.db`
|
||||||
- `CALLLOG_RETENTION_DAYS` 默认 90
|
- `CALLLOG_RETENTION_DAYS` 默认 90
|
||||||
- `CALLLOG_QUEUE_MAX` 默认 10000
|
- `CALLLOG_QUEUE_MAX` 默认 10000
|
||||||
- `CALLLOG_CONTENT_MAX` 默认 8000(提示词/回复各自截断长度)
|
- `CALLLOG_CONTENT_MAX` 默认 262144(=256KiB,提示词/回复各自上限;详情页不截断)
|
||||||
- `CALLLOG_DISABLED=1` 整体关闭(不回退任何现有行为)
|
- `CALLLOG_DISABLED=1` 整体关闭(不回退任何现有行为)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ _ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|||||||
DB_PATH = os.environ.get("CALLLOG_DB") or os.path.join(_ROOT, "data", "calllog.db")
|
DB_PATH = os.environ.get("CALLLOG_DB") or os.path.join(_ROOT, "data", "calllog.db")
|
||||||
RETENTION_DAYS = int(os.environ.get("CALLLOG_RETENTION_DAYS") or 90)
|
RETENTION_DAYS = int(os.environ.get("CALLLOG_RETENTION_DAYS") or 90)
|
||||||
QUEUE_MAX = int(os.environ.get("CALLLOG_QUEUE_MAX") or 10000)
|
QUEUE_MAX = int(os.environ.get("CALLLOG_QUEUE_MAX") or 10000)
|
||||||
CONTENT_MAX = int(os.environ.get("CALLLOG_CONTENT_MAX") or 8000)
|
CONTENT_MAX = int(os.environ.get("CALLLOG_CONTENT_MAX") or 262144)
|
||||||
DISABLED = os.environ.get("CALLLOG_DISABLED", "") not in ("", "0", "false", "False")
|
DISABLED = os.environ.get("CALLLOG_DISABLED", "") not in ("", "0", "false", "False")
|
||||||
|
|
||||||
BATCH = 200 # 攒够多少条提交一次
|
BATCH = 200 # 攒够多少条提交一次
|
||||||
@@ -101,7 +101,7 @@ def _clip(v: Any, n: int = CONTENT_MAX) -> str:
|
|||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
def prompt_preview(body: str | None, limit: int = 240) -> str:
|
def prompt_preview(body: str | None, limit: int = 240, collapse: bool = True) -> str:
|
||||||
"""从请求体 JSON 里抽出「用户实际说的话」,给列表做一行预览。
|
"""从请求体 JSON 里抽出「用户实际说的话」,给列表做一行预览。
|
||||||
|
|
||||||
兼容三种入站格式:
|
兼容三种入站格式:
|
||||||
@@ -111,11 +111,17 @@ def prompt_preview(body: str | None, limit: int = 240) -> str:
|
|||||||
"""
|
"""
|
||||||
if not body:
|
if not body:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
def _norm(t: str) -> str:
|
||||||
|
# collapse=True:列表预览(单行、压空白);False:详情(保留换行排版)
|
||||||
|
t = " ".join(str(t).split()) if collapse else str(t)
|
||||||
|
return t[:limit]
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import json as _json
|
import json as _json
|
||||||
d = _json.loads(body)
|
d = _json.loads(body)
|
||||||
except Exception: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
return " ".join(str(body).split())[:limit]
|
return _norm(body)
|
||||||
text = ""
|
text = ""
|
||||||
msgs = d.get("messages") if isinstance(d, dict) else None
|
msgs = d.get("messages") if isinstance(d, dict) else None
|
||||||
if not isinstance(msgs, list) or not msgs:
|
if not isinstance(msgs, list) or not msgs:
|
||||||
@@ -152,7 +158,7 @@ def prompt_preview(body: str | None, limit: int = 240) -> str:
|
|||||||
break
|
break
|
||||||
if not text:
|
if not text:
|
||||||
text = body
|
text = body
|
||||||
return " ".join(str(text).split())[:limit]
|
return _norm(text)
|
||||||
|
|
||||||
|
|
||||||
class CallLogStore:
|
class CallLogStore:
|
||||||
@@ -382,6 +388,8 @@ class CallLogStore:
|
|||||||
d["ts_iso"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(d["ts"]))
|
d["ts_iso"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(d["ts"]))
|
||||||
# 详情也带一份「提取出的 content」,弹窗里第一屏就能看到用户说了什么
|
# 详情也带一份「提取出的 content」,弹窗里第一屏就能看到用户说了什么
|
||||||
d["prompt_text"] = prompt_preview(d.get("prompt"))
|
d["prompt_text"] = prompt_preview(d.get("prompt"))
|
||||||
|
# 详情页要看「完整且可读」的输入:保留换行、不压空白(列表那列是单行预览)
|
||||||
|
d["prompt_full"] = prompt_preview(d.get("prompt"), limit=10 ** 9, collapse=False)
|
||||||
return d
|
return d
|
||||||
|
|
||||||
def stats(self, days: int = 7) -> dict[str, Any]:
|
def stats(self, days: int = 7) -> dict[str, Any]:
|
||||||
|
|||||||
+30
-9
@@ -162,6 +162,10 @@ def _setup_logging() -> None:
|
|||||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(levelname)s: %(message)s")
|
||||||
log = logging.getLogger("api-gateway")
|
log = logging.getLogger("api-gateway")
|
||||||
|
|
||||||
|
# 调用日志的内容上限(2026-10-23):提示词/回复按此长度截断,默认 128KiB(≈32k tokens)。
|
||||||
|
# 详情页要求「不截断」,实际上 128KiB 已覆盖绝大多数对话;要真的无限就把这个值调大。
|
||||||
|
_CONTENT_MAX = int(__import__("os").environ.get("CALLLOG_BODY_MAX") or 131072)
|
||||||
|
|
||||||
|
|
||||||
def _config_mtime() -> float:
|
def _config_mtime() -> float:
|
||||||
try:
|
try:
|
||||||
@@ -351,7 +355,7 @@ _docs_on = config.server.docs_enabled # 安全默认关(report: /docs、/ope
|
|||||||
# 2026-09-30: 2.6.1 → 2.7.0(按老板要求整个删除「火山方舟 Coding Plan」供应商:配置/模型/代码/文档/前端下拉/环境变量全清)。
|
# 2026-09-30: 2.6.1 → 2.7.0(按老板要求整个删除「火山方舟 Coding Plan」供应商:配置/模型/代码/文档/前端下拉/环境变量全清)。
|
||||||
# 2026-09-30: 2.7.0 → 2.7.1(界面提示白话化:熔断器→供应商自动保护、引擎→运行环境、slug→标识;删 120 个未引用死键)。
|
# 2026-09-30: 2.7.0 → 2.7.1(界面提示白话化:熔断器→供应商自动保护、引擎→运行环境、slug→标识;删 120 个未引用死键)。
|
||||||
# ★ 版本号纪律:每次改动都要往上加,小改动加小版本号、大改动加大版本号(README 有专章)。
|
# ★ 版本号纪律:每次改动都要往上加,小改动加小版本号、大改动加大版本号(README 有专章)。
|
||||||
VERSION = "2.9.1"
|
VERSION = "2.9.2"
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="API Gateway",
|
title="API Gateway",
|
||||||
@@ -498,8 +502,9 @@ async def in_flight_tracker(request: Request, call_next):
|
|||||||
if rid:
|
if rid:
|
||||||
try:
|
try:
|
||||||
raw = await request.body()
|
raw = await request.body()
|
||||||
BODY_BY_RID[rid] = raw[:8000].decode("utf-8", "replace")
|
# 调用日志要看完整提示词:放宽到 128KiB(≈32k tokens),并只保留最近 N 条
|
||||||
if len(BODY_BY_RID) > 2 * _BODY_MAX:
|
BODY_BY_RID[rid] = raw[:_CONTENT_MAX].decode("utf-8", "replace")
|
||||||
|
if len(BODY_BY_RID) > 128:
|
||||||
BODY_BY_RID.clear()
|
BODY_BY_RID.clear()
|
||||||
except Exception:
|
except Exception:
|
||||||
BODY_BY_RID.pop(rid, None)
|
BODY_BY_RID.pop(rid, None)
|
||||||
@@ -998,6 +1003,22 @@ def _identity_from_credentials(key: str) -> tuple[str, str, str] | None:
|
|||||||
return ident[0], ident[1], "apikey"
|
return ident[0], ident[1], "apikey"
|
||||||
|
|
||||||
|
|
||||||
|
def _content(v, maxlen: int = _CONTENT_MAX) -> str:
|
||||||
|
"""调用日志用的「内容」清洗:**保留换行与制表**(详情页要看原文排版)。
|
||||||
|
|
||||||
|
与 `_logsafe` 的区别:后者是给**单行文本日志**用的(会把 \n 压成 `?`,
|
||||||
|
防 `%0a` 伪造日志行)。调用日志要展示提示词/回复原文,压掉换行就没法看了,
|
||||||
|
所以这里只去 NUL 等不可见控制字符,换行/制表原样保留。
|
||||||
|
"""
|
||||||
|
if v is None:
|
||||||
|
return ""
|
||||||
|
t = v if isinstance(v, str) else str(v)
|
||||||
|
t = "".join(ch for ch in t if ch in "\n\t\r" or ch.isprintable())
|
||||||
|
if maxlen and len(t) > maxlen:
|
||||||
|
return t[:maxlen] + f"\n…(已截断,共 {len(t)} 字)"
|
||||||
|
return t
|
||||||
|
|
||||||
|
|
||||||
def _upstream_detail(text: str) -> str:
|
def _upstream_detail(text: str) -> str:
|
||||||
"""从上游 4xx/5xx 响应体里抽出原文(可能是 {message} 或 {error:{message}})。"""
|
"""从上游 4xx/5xx 响应体里抽出原文(可能是 {message} 或 {error:{message}})。"""
|
||||||
try:
|
try:
|
||||||
@@ -1644,8 +1665,8 @@ async def _passthrough(request: Request, protocol: str):
|
|||||||
_access.add({"method": "POST", "kind": "chat", "path": f"/v1/{protocol}", "rid": rid,
|
_access.add({"method": "POST", "kind": "chat", "path": f"/v1/{protocol}", "rid": rid,
|
||||||
"model": model_in, "served": model_in, "provider": pkey,
|
"model": model_in, "served": model_in, "provider": pkey,
|
||||||
"caller": caller, "ok": ok, "stream": False,
|
"caller": caller, "ok": ok, "stream": False,
|
||||||
"response": _logsafe(_resp_text(data) if ok else _upstream_detail(
|
"response": _content(_resp_text(data) if ok else _upstream_detail(
|
||||||
json.dumps(data, ensure_ascii=False) if isinstance(data, dict) else str(data)), 8000)})
|
json.dumps(data, ensure_ascii=False) if isinstance(data, dict) else str(data)))})
|
||||||
|
|
||||||
if not ok:
|
if not ok:
|
||||||
# 直传口径:上游的错误体**原样**回给客户端(错误文案也不翻译),只加一个
|
# 直传口径:上游的错误体**原样**回给客户端(错误文案也不翻译),只加一个
|
||||||
@@ -1690,7 +1711,7 @@ async def _passthrough_stream(request, rid, caller, protocol, adapter, cb,
|
|||||||
_access.add({"method": "POST", "kind": "chat", "path": f"/v1/{protocol}", "rid": rid,
|
_access.add({"method": "POST", "kind": "chat", "path": f"/v1/{protocol}", "rid": rid,
|
||||||
"model": model_in, "served": model_in, "provider": pkey, "caller": caller,
|
"model": model_in, "served": model_in, "provider": pkey, "caller": caller,
|
||||||
"ok": False, "stream": True,
|
"ok": False, "stream": True,
|
||||||
"response": _logsafe(_upstream_detail(raw.decode("utf-8", "replace")), 8000)})
|
"response": _content(_upstream_detail(raw.decode("utf-8", "replace")))})
|
||||||
return Response(content=raw, status_code=resp.status_code, media_type=ctype, headers=headers)
|
return Response(content=raw, status_code=resp.status_code, media_type=ctype, headers=headers)
|
||||||
|
|
||||||
scanner = _UsageScanner(protocol)
|
scanner = _UsageScanner(protocol)
|
||||||
@@ -2051,7 +2072,7 @@ async def _chat_once(cfg, rid, caller, request, req, model_id, messages, tools):
|
|||||||
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
||||||
"model": req.model, "served": model_id, "provider": pkey,
|
"model": req.model, "served": model_id, "provider": pkey,
|
||||||
"caller": caller, "ok": True, "stream": False,
|
"caller": caller, "ok": True, "stream": False,
|
||||||
"response": _logsafe(_resp_text(result), 8000)})
|
"response": _content(_resp_text(result))})
|
||||||
resp = {
|
resp = {
|
||||||
"id": result.get("id", "") or f"chatcmpl-{rid}", "object": "chat.completion",
|
"id": result.get("id", "") or f"chatcmpl-{rid}", "object": "chat.completion",
|
||||||
"created": int(time.time()), "model": req.model,
|
"created": int(time.time()), "model": req.model,
|
||||||
@@ -2179,7 +2200,7 @@ def _stream_response(request, req, model_id, messages, tools):
|
|||||||
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
||||||
"model": req.model, "served": model_id, "provider": pkey,
|
"model": req.model, "served": model_id, "provider": pkey,
|
||||||
"caller": caller, "ok": True, "stream": True,
|
"caller": caller, "ok": True, "stream": True,
|
||||||
"response": _logsafe(_stream_log_text(resp_parts, reason_parts), 8000)})
|
"response": _content(_stream_log_text(resp_parts, reason_parts))})
|
||||||
# 功能 8: 流式末尾发一个 usage 块(累计自上游 chunks 的 usage,若有)
|
# 功能 8: 流式末尾发一个 usage 块(累计自上游 chunks 的 usage,若有)
|
||||||
if stream_usage:
|
if stream_usage:
|
||||||
uf = {'id': f'chatcmpl-{rid}', 'object': 'chat.completion.chunk', 'created': int(time.time()),
|
uf = {'id': f'chatcmpl-{rid}', 'object': 'chat.completion.chunk', 'created': int(time.time()),
|
||||||
@@ -2197,7 +2218,7 @@ def _stream_response(request, req, model_id, messages, tools):
|
|||||||
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
_access.add({"method": "POST", "kind": "chat", "path": "/v1/chat/completions", "rid": rid,
|
||||||
"model": req.model, "served": model_id, "provider": pkey,
|
"model": req.model, "served": model_id, "provider": pkey,
|
||||||
"caller": caller, "ok": False, "stream": True, "error": str(e)[:200],
|
"caller": caller, "ok": False, "stream": True, "error": str(e)[:200],
|
||||||
"response": _logsafe(_stream_log_text(resp_parts, reason_parts), 8000)})
|
"response": _content(_stream_log_text(resp_parts, reason_parts))})
|
||||||
# 第六轮: 已向客户端输出过 content 时本来就无法回退(第二十七轮起更没有下一个
|
# 第六轮: 已向客户端输出过 content 时本来就无法回退(第二十七轮起更没有下一个
|
||||||
# 模型可退),统一发错误帧 + [DONE] 收尾,避免破坏已输出的 SSE 流。
|
# 模型可退),统一发错误帧 + [DONE] 收尾,避免破坏已输出的 SSE 流。
|
||||||
yield f"data: {json.dumps({'error': str(e), 'served_model': model_id}, ensure_ascii=False)}\n\n"
|
yield f"data: {json.dumps({'error': str(e), 'served_model': model_id}, ensure_ascii=False)}\n\n"
|
||||||
|
|||||||
@@ -124,11 +124,11 @@
|
|||||||
<span><i>ver</i>{{ detail.ver || '—' }}</span>
|
<span><i>ver</i>{{ detail.ver || '—' }}</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="sec">
|
<div class="sec">
|
||||||
<label>{{ t('calllogs.colContent') }}</label>
|
<label>{{ t('calllogs.colContent') }}(完整,保留换行)</label>
|
||||||
<pre>{{ detail.prompt_text || '—' }}</pre>
|
<pre>{{ detail.prompt_full || detail.prompt_text || '—' }}</pre>
|
||||||
</div>
|
</div>
|
||||||
<div class="sec">
|
<div class="sec">
|
||||||
<label>{{ t('calllogs.prompt') }}</label>
|
<label>{{ t('calllogs.prompt') }}(原始请求体 JSON)</label>
|
||||||
<pre>{{ detail.prompt || '—' }}</pre>
|
<pre>{{ detail.prompt || '—' }}</pre>
|
||||||
</div>
|
</div>
|
||||||
<div class="sec">
|
<div class="sec">
|
||||||
@@ -300,7 +300,7 @@ onMounted(loadPage)
|
|||||||
.sec { margin-top: 12px; }
|
.sec { margin-top: 12px; }
|
||||||
.sec label { font-size: 12px; color: var(--muted-2); }
|
.sec label { font-size: 12px; color: var(--muted-2); }
|
||||||
.sec pre {
|
.sec pre {
|
||||||
margin: 4px 0 0; padding: 10px 12px; max-height: 260px; overflow: auto;
|
margin: 4px 0 0; padding: 10px 12px; max-height: 460px; overflow: auto;
|
||||||
background: var(--surface-2, #f7f8fa); border: 1px solid var(--line); border-radius: 8px;
|
background: var(--surface-2, #f7f8fa); border: 1px solid var(--line); border-radius: 8px;
|
||||||
font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
|
font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user