修复用量总计与渠道账本统计

This commit is contained in:
JianFeeeee
2026-10-15 12:43:11 +08:00
parent 8f73f77ec2
commit ea8a9ac4c6
3 changed files with 54 additions and 27 deletions

View File

@ -7110,27 +7110,24 @@ function plugin.usage_token_ledger(req)
if key ~= "" then
url = url .. "&key=" .. (key:len() <= 6 and key or ("***" .. key:sub(-6)))
end
local resp, err = __llmsproxy_http({ url = url, method = "GET", timeout_ms = 4000 })
local headers = {}
if key ~= "" then
headers["Authorization"] = "Bearer " .. key
end
local resp, err = __llmsproxy_http({ url = url, method = "GET", timeout_ms = 4000, headers = headers })
if err or not resp or resp.status ~= 200 then
return { status = 200, json = { ok = true, snapshot = { available = false,
error = err or (resp and tostring(resp.status) or "no response") } } }
return { status = 503, json = { ok = false, error = "usage snapshot unavailable: " .. tostring(err or (resp and resp.status or "no response")) } }
end
local ok, rec = pcall(json.decode, resp.body or "")
if not ok or type(rec) ~= "table" then
return { status = 200, json = { ok = true, snapshot = { available = false, error = "stats 无法解析" } } }
end
-- 汇总 token 总量(兼容 stats 的不同形状)
local prompt, completion, requests = 0, 0, 0
local rows = rec.requests or rec.rows or rec.data or {}
if type(rows) == "table" then
for _, r in ipairs(rows) do
if type(r) == "table" then
prompt = prompt + (tonumber(r.prompt_tokens) or 0)
completion = completion + (tonumber(r.completion_tokens) or 0)
requests = requests + 1
end
end
return { status = 502, json = { ok = false, error = "usage snapshot 无法解析" } }
end
-- 汇总 token 总量。/api/stats 的聚合在 `total` 下,不在顶层数组中。
-- 之前错误地遍历 rec.requests/rows/data,导致该端点永远返回 0。
local total = type(rec.total) == "table" and rec.total or {}
local prompt = tonumber(total.prompt_tokens) or 0
local completion = tonumber(total.completion_tokens) or 0
local requests = tonumber(total.reqs) or 0
return { status = 200, json = { ok = true, snapshot = { available = true,
tokens = { prompt = prompt, completion = completion, total = prompt + completion },
requests = requests, raw = rec } } }