镜像与构建 - 六阶段 Dockerfile(base/wheels/deps/manifest/core|guard),core 不含 torch - 构建期自证:gen_manifest --strict 拦未登记模块,core 阶段重算 sha256 - compose 四服务 host 网络(llm.url 强制回环),config.core/local 可挂载覆盖 无 docker 环境的四段链路 - pull_oci_image.py 直拉 OCI 镜像 rootfs(纯标准库,走加速器) - replay_image_build.sh 按 stage chroot 重放 Dockerfile - run_image_chroot.sh 等价 docker run(uid 10001 + 入口 + host 网络) - pack_image.py 封成 docker save 格式包,自带 diff_id 校验 交付 - make_package.sh 生成自包含目录:镜像包 + 溯源清单 + 构建输入 + 脚本 + 源码快照 - 文档:从零复现指南、docker 打包方案、镜像构建限制与替代方案、交付包 README 命名 - Qwen 品牌名统一替换为 large_model / small_model / large_model_guard, 覆盖 vLLM 服务名、模型目录、配置、脚本、测试与文档 - 模型架构字段(architectures / model_type / tokenizer_class)属上游定义, 改名会导致加载失败,保留原值;check_local_model.py 的架构判断同理 验证:smoke 6/6;test.py 20 通过 0 失败 1 警告;gen --strict 67 文件 / 22 进镜像
1148 lines
39 KiB
Lua
1148 lines
39 KiB
Lua
-- response_guard.lua —— OpenAI 兼容内容安全插件(Lua 插件接口 v1)
|
||
--
|
||
-- 判定走宿主本地守卫模型(host.llm.call),数据不出机器。
|
||
-- 宿主只接受 {task, prompt} 或 {task, prompt, response},多一个键即
|
||
-- InvalidModelRequest;返回 {safety, categories, refusal},safety 只有
|
||
-- Safe / Unsafe / Controversial,categories 必须命中宿主固定枚举。
|
||
-- 所以本地判定不能套 OpenAI 的 messages 结构,对外接口才是 OpenAI 格式。
|
||
--
|
||
-- 多轮对话:相邻同角色消息先合并成一"轮"(连续多条 user 之间没有 assistant
|
||
-- 回复,语义上仍属同一轮),当前轮 = 最后一轮 user,之前的历史按
|
||
-- multiturn_context_bytes 压成字节有界的上下文附在当前轮前面。
|
||
-- 历史不重复送检,避免轮次越多越慢、越长越容易超 token;上下文只按字节限量,
|
||
-- 防止用几句短消息把真正危险的那一轮挤出窗口。
|
||
--
|
||
-- 宿主对 {action="block"} 只返回它自己固定的 403 正文,插件改不了;所以请求侧判定
|
||
-- 不通过时不 block,而是把请求体换成 stub(原文不出网关),再在响应侧 replace 成
|
||
-- OpenAI 错误体:400 content_policy_violation / 503 safety_review_unavailable。
|
||
|
||
local plugin = {}
|
||
local config = {}
|
||
local requests = {}
|
||
|
||
local MAX_TAIL_BYTES = 512
|
||
local MAX_JUDGE_CHUNKS = 8
|
||
-- 分段字节上限要配合宿主的 max_input_tokens:英文约 4 字节/token,
|
||
-- 24576 字节约 6k token,加指令仍在 8192 以内。
|
||
local MAX_JUDGE_CHUNK_BYTES = 24576
|
||
-- 带上下文时单段要留出上下文的 token 预算,否则中文容易撞 max_input_tokens
|
||
local CONTEXT_CHUNK_BYTES = 8192
|
||
-- 多轮上下文字节硬顶,防止历史把单次判定撑爆
|
||
local MAX_CONTEXT_BYTES = 8192
|
||
local CONTEXT_LABELS = { user = "User: ", assistant = "Assistant: " }
|
||
|
||
local DEFAULT_STREAM_PATH = "choices.*.delta.content"
|
||
local DEFAULT_FULL_PATH = "choices.*.message.content"
|
||
|
||
-- 守卫模型的输出就是 Safety / Categories / Refusal 三行,宿主 parse_guard_output
|
||
-- 按这个格式解析,类别必须落在它的枚举内,否则整条判定按 InvalidModelOutput 失败。
|
||
-- 该模型训练时直接收原文,不要再加自定义指令;prompt_prefix 只在确有需要时使用。
|
||
-- 输出侧 prompt = 上下文 + 本轮提问,留 4096 让两者都有位置(中文约 1.3k token)
|
||
local MAX_INPUT_CONTEXT = 4096
|
||
|
||
local function key_for(ctx)
|
||
if type(ctx) == "table" and type(ctx.request_id) == "string" and ctx.request_id ~= "" then
|
||
return ctx.request_id
|
||
end
|
||
return nil
|
||
end
|
||
|
||
local function clear(key)
|
||
if key then requests[key] = nil end
|
||
end
|
||
|
||
local function shallow_copy(value)
|
||
local out = {}
|
||
for k, v in pairs(value or {}) do out[k] = v end
|
||
return out
|
||
end
|
||
|
||
local function is_continuation(byte)
|
||
return byte ~= nil and byte >= 0x80 and byte <= 0xBF
|
||
end
|
||
|
||
-- 按字节上限截断,回退到 UTF-8 字符边界
|
||
local function truncate_utf8(text, max_bytes)
|
||
if type(text) ~= "string" then return "" end
|
||
if #text <= max_bytes then return text end
|
||
local stop = max_bytes
|
||
while stop > 0 and is_continuation(string.byte(text, stop + 1)) do
|
||
stop = stop - 1
|
||
end
|
||
return string.sub(text, 1, stop)
|
||
end
|
||
|
||
-- 保留末尾 max_bytes 字节,起点对齐到 UTF-8 字符边界
|
||
local function utf8_tail(text, max_bytes)
|
||
if #text <= max_bytes then return text end
|
||
local start = #text - max_bytes + 1
|
||
while start <= #text and is_continuation(string.byte(text, start)) do
|
||
start = start + 1
|
||
end
|
||
return string.sub(text, start)
|
||
end
|
||
|
||
-- 按字节上限切分,切点回退到 UTF-8 字符边界
|
||
local function split_utf8(text, size)
|
||
local chunks = {}
|
||
local pos, length = 1, #text
|
||
while pos <= length do
|
||
local stop = pos + size - 1
|
||
if stop >= length then
|
||
chunks[#chunks + 1] = string.sub(text, pos)
|
||
break
|
||
end
|
||
while stop > pos and is_continuation(string.byte(text, stop + 1)) do
|
||
stop = stop - 1
|
||
end
|
||
chunks[#chunks + 1] = string.sub(text, pos, stop)
|
||
pos = stop + 1
|
||
end
|
||
return chunks
|
||
end
|
||
|
||
local function dense_length(value)
|
||
if type(value) ~= "table" then return nil end
|
||
local count, max_index = 0, 0
|
||
for k in pairs(value) do
|
||
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
|
||
count = count + 1
|
||
if k > max_index then max_index = k end
|
||
end
|
||
if count ~= max_index then return nil end
|
||
return count
|
||
end
|
||
|
||
local function parse_path(value)
|
||
if value == nil then return nil end
|
||
if type(value) == "string" then
|
||
local parts = {}
|
||
for part in string.gmatch(value, "[^%.]+") do
|
||
if part == "" then return nil end
|
||
parts[#parts + 1] = part
|
||
end
|
||
if #parts == 0 then return nil end
|
||
return parts
|
||
end
|
||
if type(value) == "table" then
|
||
local parts, count = {}, 0
|
||
for k in pairs(value) do
|
||
if type(k) ~= "number" or k < 1 or k % 1 ~= 0 then return nil end
|
||
count = count + 1
|
||
end
|
||
for i = 1, count do
|
||
local part = value[i]
|
||
if type(part) ~= "string" or part == "" then return nil end
|
||
parts[i] = part
|
||
end
|
||
if count == 0 then return nil end
|
||
return parts
|
||
end
|
||
return nil
|
||
end
|
||
|
||
local function parse_paths(value, default_text)
|
||
if value == nil then value = default_text end
|
||
if type(value) == "string" then
|
||
local single = parse_path(value)
|
||
if not single then return nil end
|
||
return { single }
|
||
end
|
||
if type(value) ~= "table" then return nil end
|
||
local count = dense_length(value)
|
||
if not count or count == 0 then return nil end
|
||
local list = {}
|
||
for i = 1, count do
|
||
local single = parse_path(value[i])
|
||
if not single then return nil end
|
||
list[i] = single
|
||
end
|
||
return list
|
||
end
|
||
|
||
-- 字段缺失 = 本帧没文本(role/finish 帧);存在但不是字符串 = malformed,必须 fail-closed
|
||
local function collect_locations(root, parts)
|
||
local found = {}
|
||
local malformed = false
|
||
|
||
local function walk(node, depth)
|
||
local segment = parts[depth]
|
||
if segment == "*" then
|
||
local length = dense_length(node)
|
||
if not length or length == 0 then
|
||
malformed = true
|
||
return false
|
||
end
|
||
for i = 1, length do
|
||
local child = node[i]
|
||
if depth == #parts then
|
||
if child == host.json.null or child == nil then
|
||
-- 无文本
|
||
elseif type(child) ~= "string" then
|
||
malformed = true
|
||
return false
|
||
else
|
||
found[#found + 1] = { parent = node, key = i }
|
||
end
|
||
else
|
||
if type(child) ~= "table" then
|
||
malformed = true
|
||
return false
|
||
end
|
||
if not walk(child, depth + 1) then return false end
|
||
end
|
||
end
|
||
return true
|
||
end
|
||
|
||
if type(node) ~= "table" then
|
||
malformed = true
|
||
return false
|
||
end
|
||
local child = node[segment]
|
||
if depth == #parts then
|
||
if child == nil or child == host.json.null then
|
||
return true
|
||
end
|
||
if type(child) ~= "string" then
|
||
malformed = true
|
||
return false
|
||
end
|
||
found[#found + 1] = { parent = node, key = segment }
|
||
return true
|
||
end
|
||
if child == nil or child == host.json.null then return true end
|
||
if type(child) ~= "table" then
|
||
malformed = true
|
||
return false
|
||
end
|
||
return walk(child, depth + 1)
|
||
end
|
||
|
||
walk(root, 1)
|
||
return found, malformed
|
||
end
|
||
|
||
local function join_locations(locations)
|
||
if #locations == 0 then return "" end
|
||
local parts = {}
|
||
for i, location in ipairs(locations) do
|
||
parts[i] = location.parent[location.key]
|
||
end
|
||
return table.concat(parts)
|
||
end
|
||
|
||
-- 顺序必须稳定:放行时按同样的顺序把脱敏结果切回各字段
|
||
local function collect_all(root, path_list)
|
||
local locations = {}
|
||
local malformed = false
|
||
for _, parts in ipairs(path_list) do
|
||
local found, bad = collect_locations(root, parts)
|
||
if bad then malformed = true end
|
||
for _, location in ipairs(found) do
|
||
locations[#locations + 1] = location
|
||
end
|
||
end
|
||
return locations, malformed
|
||
end
|
||
|
||
local redact_text
|
||
|
||
-- 就地脱敏;脱敏不改变字节长度,失败即 fail-closed
|
||
local function redact_locations(locations)
|
||
if #locations == 0 then return false, nil end
|
||
local original = join_locations(locations)
|
||
if original == "" then return false, nil end
|
||
local masked = redact_text(original)
|
||
if #masked ~= #original then
|
||
return false, "redaction_length_changed"
|
||
end
|
||
if masked == original then return false, nil end
|
||
local offset = 1
|
||
for _, location in ipairs(locations) do
|
||
local length = #location.parent[location.key]
|
||
location.parent[location.key] = string.sub(masked, offset, offset + length - 1)
|
||
offset = offset + length
|
||
end
|
||
return true, nil
|
||
end
|
||
|
||
redact_text = function(text)
|
||
local out = text
|
||
|
||
-- Bearer 凭证与常见 API Key
|
||
out = out:gsub("([Bb]earer%s+)([%w%._~%+/%-]+=*)", function(prefix, token)
|
||
return prefix .. string.rep("*", #token)
|
||
end)
|
||
out = out:gsub("sk%-[%w_%-]+", function(token)
|
||
return "sk-" .. string.rep("*", #token - 3)
|
||
end)
|
||
out = out:gsub("AKIA[A-Z0-9]+", function(token)
|
||
if #token >= 12 then return "AKIA" .. string.rep("*", #token - 4) end
|
||
return token
|
||
end)
|
||
|
||
-- 邮箱:保留域名与首字符
|
||
out = out:gsub("[%w%._%+%-]+@[%w%-%.]+%.[%a]+", function(email)
|
||
local at = email:find("@", 1, true)
|
||
if not at then return email end
|
||
local local_part, domain = email:sub(1, at - 1), email:sub(at + 1)
|
||
if #local_part <= 1 then return "*@" .. domain end
|
||
return local_part:sub(1, 1) .. string.rep("*", #local_part - 1) .. "@" .. domain
|
||
end)
|
||
|
||
-- 18 位身份证
|
||
out = out:gsub("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d[%dXx]", function(id)
|
||
return id:sub(1, 6) .. "********" .. id:sub(-4)
|
||
end)
|
||
|
||
-- 银行卡号(16~19 位,允许空格/连字符分隔),保持分隔符与长度
|
||
out = out:gsub("%d[%d %-]*%d", function(number_run)
|
||
local digits = number_run:gsub("%D", "")
|
||
if #digits < 16 or #digits > 19 then return number_run end
|
||
local total, index = #digits, 0
|
||
return (number_run:gsub("%d", function(digit)
|
||
index = index + 1
|
||
if index <= 4 or index > total - 4 then return digit end
|
||
return "*"
|
||
end))
|
||
end)
|
||
|
||
-- 中国大陆手机号
|
||
out = out:gsub("1[3-9]%d%d%d%d%d%d%d%d%d", function(phone)
|
||
return phone:sub(1, 3) .. "****" .. phone:sub(-4)
|
||
end)
|
||
|
||
-- 10 位固话:保留分隔符,长度必须不变
|
||
out = out:gsub("(%d%d%d)([%s%.%-]?)(%d%d%d)([%s%.%-]?)(%d%d%d%d)",
|
||
function(a, sep1, b, sep2, c)
|
||
return a .. sep1 .. "***" .. sep2 .. c
|
||
end)
|
||
|
||
return out
|
||
end
|
||
|
||
local closers = {
|
||
['"'] = true, ["'"] = true, [')'] = true, [']'] = true, ['}'] = true,
|
||
}
|
||
|
||
local function skip_utf8_closer(s, i)
|
||
for _, token in ipairs({ "”", "’", ")", "】", "》", "」", "』", "〉", "〕" }) do
|
||
if s:sub(i, i + #token - 1) == token then
|
||
return i + #token
|
||
end
|
||
end
|
||
return nil
|
||
end
|
||
|
||
local abbreviations = {
|
||
["mr"] = true, ["mrs"] = true, ["ms"] = true, ["dr"] = true,
|
||
["prof"] = true, ["sr"] = true, ["jr"] = true, ["st"] = true,
|
||
["vs"] = true, ["etc"] = true, ["e.g"] = true, ["i.e"] = true,
|
||
["fig"] = true, ["no"] = true, ["approx"] = true,
|
||
}
|
||
|
||
local function is_abbreviation_dot(s, i)
|
||
local prefix_start = math.max(1, i - 64)
|
||
local prefix = s:sub(prefix_start, i - 1):lower()
|
||
local token = prefix:match("([%a%.]+)$")
|
||
if token and abbreviations[token] then return true end
|
||
local before = s:sub(i - 1, i - 1)
|
||
local after = s:sub(i + 1, i + 1)
|
||
if before:match("%d") and after:match("%d") then return true end
|
||
return false
|
||
end
|
||
|
||
local function has_sentence_boundary(s)
|
||
local i = 1
|
||
while i <= #s do
|
||
local ch = s:sub(i, i)
|
||
local punct_len = 1
|
||
local punct = (ch == "." or ch == "!" or ch == "?")
|
||
if not punct then
|
||
local utf = s:sub(i, i + 2)
|
||
if utf == "。" or utf == "!" or utf == "?" then
|
||
punct, punct_len = true, 3
|
||
end
|
||
end
|
||
|
||
if punct then
|
||
if ch == "." and is_abbreviation_dot(s, i) then
|
||
i = i + punct_len
|
||
else
|
||
local j = i + punct_len
|
||
while j <= #s do
|
||
local c = s:sub(j, j)
|
||
if closers[c] then
|
||
j = j + 1
|
||
else
|
||
local next_j = skip_utf8_closer(s, j)
|
||
if next_j then j = next_j else break end
|
||
end
|
||
end
|
||
if (punct_len == 3) or (j <= #s and s:sub(j, j):match("%s")) then
|
||
return true
|
||
end
|
||
i = i + punct_len
|
||
end
|
||
else
|
||
i = i + 1
|
||
end
|
||
end
|
||
return false
|
||
end
|
||
|
||
local function policy_denied(verdict, kind)
|
||
return {
|
||
status = config.block_status,
|
||
type = "invalid_request_error",
|
||
code = "content_policy_violation",
|
||
message = (kind == "output") and config.block_message_output or config.block_message_input,
|
||
category = (verdict and verdict.category) or "other",
|
||
}
|
||
end
|
||
|
||
local function policy_unavailable(reason)
|
||
return {
|
||
status = 503,
|
||
type = "server_error",
|
||
code = "safety_review_unavailable",
|
||
message = "The content safety review could not complete. Please retry.",
|
||
category = reason or "unavailable",
|
||
}
|
||
end
|
||
|
||
local function error_body(policy)
|
||
return host.json.encode({
|
||
error = {
|
||
message = policy.message,
|
||
type = policy.type,
|
||
param = host.json.null,
|
||
code = policy.code,
|
||
},
|
||
})
|
||
end
|
||
|
||
-- 非流式:整包替换成一个标准 OpenAI 错误响应
|
||
local function error_response(policy)
|
||
return {
|
||
status = policy.status,
|
||
headers = { ["content-type"] = "application/json; charset=utf-8" },
|
||
body = error_body(policy),
|
||
streaming = false,
|
||
}
|
||
end
|
||
|
||
-- 流式:单帧 data: {"error":{...}}
|
||
local function error_frame(policy)
|
||
return { has_data = true, data = error_body(policy) }
|
||
end
|
||
|
||
-- prompt_moderation 只有 prompt 一个字段承载内容,所以原文直接放进去;
|
||
-- response_moderation 用 prompt 放用户原问题、response 放模型输出——不能把正文
|
||
-- 塞进 prompt,也不能只发输出而丢掉提问上下文。
|
||
local function input_prompt(part, index, total)
|
||
if total <= 1 then return part end
|
||
return string.format("(part %d of %d)\n%s", index, total, part)
|
||
end
|
||
|
||
-- 二级复核:0.6B 判危险后,用更大的模型对同一段原文再判一次。
|
||
-- 传的是「同一份原文 + 同一份上下文」,不是 0.6B 的判决对象;0.6B 的类别最多
|
||
-- 拼进 prompt 当弱提示。返回 nil 表示"复核不可用",调用方必须回落首判(fail-closed)。
|
||
local function review_call(kind, part, index, total, context, first)
|
||
local model = config.review_model
|
||
if not model then return nil end
|
||
local prefix = config.review_prefix or ""
|
||
|
||
local request
|
||
if kind == "output" then
|
||
local prompt = (type(context) == "string" and context ~= "") and context
|
||
or "Evaluate the safety of the assistant reply."
|
||
request = { task = "response_moderation",
|
||
prompt = prefix ~= "" and (prefix .. "\n\n" .. prompt) or prompt,
|
||
response = part }
|
||
else
|
||
local text = input_prompt(part, index, total)
|
||
if type(context) == "string" and context ~= "" then
|
||
text = context .. "\n\n" .. text
|
||
end
|
||
request = { task = "prompt_moderation",
|
||
prompt = prefix ~= "" and (prefix .. "\n\n" .. text) or text }
|
||
end
|
||
|
||
local ok, result = pcall(host.llm.call, model, request)
|
||
if not ok or type(result) ~= "table" then return nil end
|
||
|
||
if result.safety == "Safe" then return { allow = true } end
|
||
if result.safety == "Controversial" and not config.block_controversial then
|
||
return { allow = true }
|
||
end
|
||
if result.safety == "Unsafe" or result.safety == "Controversial" then
|
||
local categories = type(result.categories) == "table" and result.categories or {}
|
||
local first_cat = categories[1]
|
||
local category = type(first_cat) == "string" and first_cat
|
||
or (type(first) == "table" and first.category) or "other"
|
||
return { allow = false, category = category }
|
||
end
|
||
return nil -- safety 落在枚举外,视为复核不可用
|
||
end
|
||
|
||
local function judge_call(kind, part, index, total, context)
|
||
local request
|
||
if kind == "output" then
|
||
local prompt = context
|
||
if type(prompt) ~= "string" or prompt == "" then
|
||
prompt = "Evaluate the safety of the assistant reply."
|
||
end
|
||
if config.prompt_prefix then
|
||
prompt = config.prompt_prefix .. "\n\n" .. prompt
|
||
end
|
||
request = { task = "response_moderation", prompt = prompt, response = part }
|
||
else
|
||
local text = input_prompt(part, index, total)
|
||
if type(context) == "string" and context ~= "" then
|
||
text = context .. "\n\n" .. text
|
||
end
|
||
if config.prompt_prefix then
|
||
text = config.prompt_prefix .. "\n\n" .. text
|
||
end
|
||
request = { task = "prompt_moderation", prompt = text }
|
||
end
|
||
|
||
local ok, result = pcall(host.llm.call, config.model, request)
|
||
if not ok or type(result) ~= "table" then return nil, "judge_call_failed" end
|
||
|
||
local safety = result.safety
|
||
if safety == "Safe" then return { allow = true } end
|
||
if safety == "Controversial" and not config.block_controversial then
|
||
return { allow = true }
|
||
end
|
||
if safety == "Unsafe" or safety == "Controversial" then
|
||
local categories = type(result.categories) == "table" and result.categories or {}
|
||
local first = categories[1]
|
||
local verdict = { allow = false, category = type(first) == "string" and first or "other" }
|
||
|
||
-- 二级复核:默认只放松(8B 说 Safe 就放行),override 则让 8B 终裁
|
||
local want = (safety == "Unsafe") or config.review_scope_controversial
|
||
if want and config.review_model then
|
||
local second = review_call(kind, part, index, total, context, verdict)
|
||
if second then
|
||
if config.review_mode == "override" or second.allow == true then
|
||
return second
|
||
end
|
||
end
|
||
end
|
||
-- 复核不可用 / 复核也判危险:保持首判(fail-closed)
|
||
return verdict
|
||
end
|
||
-- safety 落在枚举外说明模型输出不可信,按 fail-closed 处理
|
||
return nil, "judge_invalid_safety"
|
||
end
|
||
|
||
-- context:输入侧是历史对话,输出侧是用户提问(两者都只做上下文,不参与分段)
|
||
local function judge(kind, target, model_text, context)
|
||
local body = model_text or target or ""
|
||
if body == "" then return { allow = true } end
|
||
|
||
local budget = config.judge_chunk_bytes
|
||
if type(context) == "string" and context ~= "" and budget > CONTEXT_CHUNK_BYTES then
|
||
budget = CONTEXT_CHUNK_BYTES
|
||
end
|
||
|
||
local chunks = split_utf8(body, budget)
|
||
if #chunks == 0 then return { allow = true } end
|
||
if #chunks > MAX_JUDGE_CHUNKS then return nil, "judge_input_too_large" end
|
||
|
||
for index = 1, #chunks do
|
||
local verdict, err = judge_call(kind, chunks[index], index, #chunks, context)
|
||
if not verdict then return nil, err end
|
||
if verdict.allow ~= true then return verdict end
|
||
end
|
||
return { allow = true }
|
||
end
|
||
|
||
-- chat 的 {type="text"} 和 Responses 的 {type="input_text"} 都要认,否则换个写法就能绕过审核
|
||
local function message_text(content)
|
||
if type(content) == "string" then return content end
|
||
if type(content) ~= "table" then return nil end
|
||
local parts = {}
|
||
for _, part in ipairs(content) do
|
||
if type(part) == "table" and type(part.text) == "string"
|
||
and (part.type == "text" or part.type == "input_text") then
|
||
parts[#parts + 1] = part.text
|
||
end
|
||
end
|
||
if #parts == 0 then return nil end
|
||
return table.concat(parts, "\n")
|
||
end
|
||
|
||
-- 按 messages 顺序收集可读轮次,保留角色边界;空内容帧(纯工具调用)跳过但不报错
|
||
local function collect_turns(decoded)
|
||
local messages = decoded.messages
|
||
if type(messages) ~= "table" then
|
||
if type(decoded.prompt) == "string" and decoded.prompt ~= "" then
|
||
return { { role = "user", text = decoded.prompt } }
|
||
end
|
||
return nil
|
||
end
|
||
local count = dense_length(messages)
|
||
if not count then return nil end
|
||
local turns = {}
|
||
for i = 1, count do
|
||
local message = messages[i]
|
||
if type(message) ~= "table" or type(message.role) ~= "string" then return nil end
|
||
local text = message_text(message.content)
|
||
if text and text ~= "" then
|
||
local last = turns[#turns]
|
||
if last and last.role == message.role then
|
||
-- 相邻同角色合并:客户端把一轮内容拆成多条消息时,不能只看最后一条
|
||
last.text = last.text .. "\n" .. text
|
||
else
|
||
turns[#turns + 1] = { role = message.role, text = text }
|
||
end
|
||
end
|
||
end
|
||
if #turns == 0 then return nil end
|
||
return turns
|
||
end
|
||
|
||
-- 当前轮 = 最后一轮 user(相邻 user 已合并);它之前的所有轮次都是上下文
|
||
local function split_turns(turns)
|
||
local index = nil
|
||
for i = #turns, 1, -1 do
|
||
if turns[i].role == "user" then
|
||
index = i
|
||
break
|
||
end
|
||
end
|
||
if index == nil then return nil, nil, nil end
|
||
return turns[index], turns, index
|
||
end
|
||
|
||
-- 历史压成 "User: ... / Assistant: ..." 的纯文本,按字节从最近往前取,
|
||
-- 保证预算优先留给离当前轮最近的历史,不会被早期短消息占满。
|
||
local function render_context(turns, stop, max_bytes)
|
||
if max_bytes <= 0 or stop <= 1 then return "" end
|
||
local lines = {}
|
||
local used = 0
|
||
for i = stop - 1, 1, -1 do
|
||
local label = CONTEXT_LABELS[turns[i].role]
|
||
if label then
|
||
local line = label .. turns[i].text
|
||
local size = #line + 1 -- 含与前一行之间的换行
|
||
if used + size > max_bytes then
|
||
if #lines == 0 then
|
||
-- 最近一条就超预算:只留它的尾部,上下文仍是"最近的"
|
||
local room = max_bytes - 1
|
||
if room > 0 then lines[1] = utf8_tail(line, room) end
|
||
end
|
||
break
|
||
end
|
||
lines[#lines + 1] = line
|
||
used = used + size
|
||
end
|
||
end
|
||
if #lines == 0 then return "" end
|
||
-- 上面是倒序收集,这里恢复时间顺序
|
||
local ordered = {}
|
||
for i = #lines, 1, -1 do ordered[#ordered + 1] = lines[i] end
|
||
return table.concat(ordered, "\n")
|
||
end
|
||
|
||
-- 当前轮必须完整保留(截断只能发生在上下文一侧),否则回答侧会拿错问题
|
||
local function context_prompt(context, current, limit)
|
||
if context == "" then return truncate_utf8(current, limit) end
|
||
local room = limit - #current
|
||
if room <= 0 then return truncate_utf8(current, limit) end
|
||
return utf8_tail(context, room) .. "\n\n" .. current
|
||
end
|
||
|
||
-- 拦截后发往上游的占位请求:只带 OpenAI 规范字段,否则上游会先用自己的 400 拒掉它
|
||
local function encode_stub(state)
|
||
local body = {
|
||
messages = { { role = "user", content = "ping" } },
|
||
stream = state.stream == true,
|
||
}
|
||
local model = state.model
|
||
if model == nil or model == "" then model = config.stub_model end
|
||
if type(model) == "string" and model ~= "" then body.model = model end
|
||
if config.stub_max_tokens then
|
||
body.max_tokens = config.stub_max_tokens
|
||
end
|
||
return host.json.encode(body)
|
||
end
|
||
|
||
local function should_flush(state)
|
||
if state.text_bytes < config.flush_chars then return false end
|
||
if has_sentence_boundary(state.tail) then return true end
|
||
return state.text_bytes >= config.force_flush_bytes
|
||
end
|
||
|
||
-- 审核 + 脱敏 + 按原顺序还原事件;失败返回 nil, policy
|
||
local function release(state)
|
||
local pending = state.pending
|
||
if #pending == 0 then return host.json.array(), nil end
|
||
|
||
local text = table.concat(state.texts)
|
||
local masked = text
|
||
|
||
if text ~= "" then
|
||
if config.check_output then
|
||
local verdict, err = judge("output", nil, text, state.input_text)
|
||
if not verdict then return nil, policy_unavailable(err) end
|
||
if verdict.allow ~= true then return nil, policy_denied(verdict, "output") end
|
||
end
|
||
|
||
local ok_redact, redacted = pcall(redact_text, text)
|
||
if not ok_redact or type(redacted) ~= "string" or #redacted ~= #text then
|
||
return nil, policy_unavailable("redaction_failed")
|
||
end
|
||
masked = redacted
|
||
end
|
||
|
||
local events = {}
|
||
local offset = 1
|
||
for _, entry in ipairs(pending) do
|
||
if #entry.lengths == 0 then
|
||
events[#events + 1] = entry.event
|
||
else
|
||
local ok_decode, decoded = pcall(host.json.decode, entry.event.data)
|
||
if not ok_decode or type(decoded) ~= "table" then
|
||
return nil, policy_unavailable("release_decode_failed")
|
||
end
|
||
local locations, malformed = collect_all(decoded, config.content_paths_stream)
|
||
if malformed or #locations ~= #entry.lengths then
|
||
return nil, policy_unavailable("release_shape_changed")
|
||
end
|
||
for i, location in ipairs(locations) do
|
||
local length = entry.lengths[i]
|
||
local replacement = ""
|
||
if length > 0 then
|
||
replacement = string.sub(masked, offset, offset + length - 1)
|
||
end
|
||
offset = offset + length
|
||
location.parent[location.key] = replacement
|
||
end
|
||
local ok_encode, encoded = pcall(host.json.encode, decoded)
|
||
if not ok_encode or type(encoded) ~= "string" then
|
||
return nil, policy_unavailable("release_encode_failed")
|
||
end
|
||
local copy = shallow_copy(entry.event)
|
||
copy.data = encoded
|
||
events[#events + 1] = copy
|
||
end
|
||
end
|
||
|
||
state.pending = {}
|
||
state.texts = {}
|
||
state.text_bytes = 0
|
||
state.tail = ""
|
||
return host.json.array(events), nil
|
||
end
|
||
|
||
local function positive_int(value, default, label)
|
||
if value == nil then return default end
|
||
local number = tonumber(value)
|
||
if not number or number < 1 or number % 1 ~= 0 then
|
||
error("response_guard: config." .. label .. " must be a positive integer")
|
||
end
|
||
return number
|
||
end
|
||
|
||
local function boolean(value, default)
|
||
if value == nil then return default end
|
||
if value == true or value == false then return value end
|
||
error("response_guard: boolean config value must be true or false")
|
||
end
|
||
|
||
-- 0 表示关闭多轮上下文(只判当前轮),所以允许 0
|
||
local function non_negative_int(value, default, label)
|
||
if value == nil then return default end
|
||
local number = tonumber(value)
|
||
if not number or number < 0 or number % 1 ~= 0 then
|
||
error("response_guard: config." .. label .. " must be a non-negative integer")
|
||
end
|
||
return number
|
||
end
|
||
|
||
-- 模型由宿主的 llm 段加载;这里只写 id,插件必须在 config.yaml 里用
|
||
-- llm.allow 声明同一个 id,否则 host.llm.call 必然失败。
|
||
function plugin.init(ctx, options)
|
||
if type(options) ~= "table" then
|
||
error("response_guard config must be a table")
|
||
end
|
||
local o = options
|
||
|
||
if type(o.model) ~= "string" or o.model == "" then
|
||
error("response_guard requires config.model (id of a host llm entry)")
|
||
end
|
||
|
||
local prompt_prefix = o.prompt_prefix
|
||
if prompt_prefix ~= nil and (type(prompt_prefix) ~= "string" or prompt_prefix == "") then
|
||
error("response_guard: config.prompt_prefix must be a non-empty string or absent")
|
||
end
|
||
|
||
-- 单个路径字符串或多路径数组都接受;多路径用于同时覆盖正文与工具调用参数
|
||
local stream_paths = parse_paths(o.content_path_stream, DEFAULT_STREAM_PATH)
|
||
if not stream_paths then
|
||
error("response_guard: invalid config.content_path_stream")
|
||
end
|
||
local full_paths = parse_paths(o.content_path_full, DEFAULT_FULL_PATH)
|
||
if not full_paths then
|
||
error("response_guard: invalid config.content_path_full")
|
||
end
|
||
|
||
local block_status = positive_int(o.block_status, 400, "block_status")
|
||
if block_status < 400 or block_status > 599 then
|
||
error("response_guard: config.block_status must be within 400..599")
|
||
end
|
||
|
||
local judge_chunk_bytes = positive_int(o.judge_chunk_bytes, 8192, "judge_chunk_bytes")
|
||
if judge_chunk_bytes > MAX_JUDGE_CHUNK_BYTES then
|
||
error("response_guard: config.judge_chunk_bytes must not exceed " .. MAX_JUDGE_CHUNK_BYTES)
|
||
end
|
||
local stream_mode = o.stream_mode or "incremental"
|
||
if stream_mode ~= "incremental" and stream_mode ~= "buffered" then
|
||
error("response_guard: config.stream_mode must be 'incremental' or 'buffered'")
|
||
end
|
||
|
||
-- 占位请求兜底模型:客户端请求里没有 model 时用(规范要求 model 必填)
|
||
local stub_model = o.stub_model
|
||
if stub_model ~= nil and (type(stub_model) ~= "string" or stub_model == "") then
|
||
error("response_guard: config.stub_model must be a non-empty string or absent")
|
||
end
|
||
|
||
-- 占位请求生成长度上限:默认 16;false 表示不发(上游只认 max_completion_tokens 时用)
|
||
local stub_max_tokens
|
||
if o.stub_max_tokens == false then
|
||
stub_max_tokens = nil
|
||
else
|
||
stub_max_tokens = positive_int(o.stub_max_tokens, 16, "stub_max_tokens")
|
||
end
|
||
|
||
-- 多轮上下文:只按字节限量(默认 2048);0 表示只判当前轮,历史不进判定
|
||
-- 旧的 multiturn_context_messages 已移除:按条数会被几句短填充把那轮关键内容挤出窗口
|
||
if o.multiturn_context_messages ~= nil then
|
||
error("response_guard: config.multiturn_context_messages has been removed, "
|
||
.. "use multiturn_context_bytes instead")
|
||
end
|
||
local multiturn_bytes = non_negative_int(o.multiturn_context_bytes, 2048, "multiturn_context_bytes")
|
||
if multiturn_bytes > MAX_CONTEXT_BYTES then
|
||
error("response_guard: config.multiturn_context_bytes must not exceed " .. MAX_CONTEXT_BYTES)
|
||
end
|
||
|
||
-- 二级复核配置:review_model 必须在宿主的 llm.allow 里,否则调用直接失败
|
||
local review_model = o.review_model
|
||
if review_model ~= nil and (type(review_model) ~= "string" or review_model == "") then
|
||
error("response_guard: config.review_model must be a non-empty string or absent")
|
||
end
|
||
local review_mode = o.review_mode or "relax"
|
||
if review_mode ~= "relax" and review_mode ~= "override" then
|
||
error("response_guard: config.review_mode must be 'relax' or 'override'")
|
||
end
|
||
local review_scope_controversial = false
|
||
if o.review_scope ~= nil then
|
||
if type(o.review_scope) ~= "table" then
|
||
error("response_guard: config.review_scope must be a list like [Unsafe]")
|
||
end
|
||
for _, name in ipairs(o.review_scope) do
|
||
if name == "Controversial" then review_scope_controversial = true end
|
||
end
|
||
end
|
||
local review_prefix = o.review_prefix
|
||
if review_prefix ~= nil and (type(review_prefix) ~= "string" or review_prefix == "") then
|
||
error("response_guard: config.review_prefix must be a non-empty string or absent")
|
||
end
|
||
|
||
config = {
|
||
model = o.model,
|
||
review_model = review_model,
|
||
review_mode = review_mode,
|
||
review_scope_controversial = review_scope_controversial,
|
||
review_prefix = review_prefix,
|
||
prompt_prefix = prompt_prefix,
|
||
stub_model = stub_model,
|
||
stub_max_tokens = stub_max_tokens,
|
||
judge_chunk_bytes = judge_chunk_bytes,
|
||
content_paths_stream = stream_paths,
|
||
content_paths_full = full_paths,
|
||
block_status = block_status,
|
||
block_message_input = type(o.block_message_input) == "string" and o.block_message_input
|
||
or "Your request was rejected by the content safety policy.",
|
||
block_message_output = type(o.block_message_output) == "string" and o.block_message_output
|
||
or "The model response was withheld by the content safety policy.",
|
||
flush_chars = positive_int(o.flush_chars, 512, "flush_chars"),
|
||
force_flush_bytes = positive_int(o.force_flush_bytes, 4096, "force_flush_bytes"),
|
||
max_buffer_bytes = positive_int(o.max_buffer_bytes, 131072, "max_buffer_bytes"),
|
||
stream_mode = stream_mode,
|
||
check_input = boolean(o.check_input, true),
|
||
check_output = boolean(o.check_output, true),
|
||
block_controversial = boolean(o.block_controversial, true),
|
||
multiturn_context_bytes = multiturn_bytes,
|
||
}
|
||
|
||
-- 不重置 requests:host 可能在请求初始化阶段调用 init
|
||
return nil
|
||
end
|
||
|
||
function plugin.on_request(ctx, request)
|
||
local key = key_for(ctx)
|
||
if not key then
|
||
-- 没有 request_id 就无法保存判定结果,只能 fail-closed
|
||
return { action = "block", reason = "missing request_id" }
|
||
end
|
||
|
||
local state = {
|
||
input_text = "",
|
||
verdict = "allow",
|
||
policy = nil,
|
||
stream = false,
|
||
model = nil,
|
||
pending = {},
|
||
texts = {},
|
||
text_bytes = 0,
|
||
tail = "",
|
||
terminal = false,
|
||
opaque = false,
|
||
}
|
||
requests[key] = state
|
||
|
||
if type(request) ~= "table" or type(request.body) ~= "string" then
|
||
state.opaque = true
|
||
return { action = "pass" }
|
||
end
|
||
|
||
local ok_decode, decoded = pcall(host.json.decode, request.body)
|
||
if not ok_decode or type(decoded) ~= "table" then
|
||
-- 非法 JSON 交给上游按 OpenAI 规范自己拒绝,这里不额外加工
|
||
state.opaque = true
|
||
return { action = "pass" }
|
||
end
|
||
|
||
if type(decoded.model) == "string" then state.model = decoded.model end
|
||
state.stream = decoded.stream == true
|
||
|
||
-- 多轮:当前轮单独判,历史只作为有界上下文;历史本身不重复送检
|
||
local turns = collect_turns(decoded)
|
||
if turns == nil then return { action = "pass" } end
|
||
local current, _, index = split_turns(turns)
|
||
if current == nil then return { action = "pass" } end
|
||
|
||
local context = render_context(turns, index, config.multiturn_context_bytes)
|
||
|
||
-- 输出判定要带上本轮提问(含上文):守卫模型的 response_moderation 用 user 轮做上下文
|
||
state.input_text = context_prompt(context, current.text, MAX_INPUT_CONTEXT)
|
||
|
||
if not config.check_input then return { action = "pass" } end
|
||
|
||
local verdict, err = judge("input", current.text, nil, context)
|
||
if not verdict then
|
||
state.verdict = "error"
|
||
state.policy = policy_unavailable(err)
|
||
elseif verdict.allow ~= true then
|
||
state.verdict = "deny"
|
||
state.policy = policy_denied(verdict, "input")
|
||
end
|
||
|
||
if state.verdict == "allow" then return { action = "pass" } end
|
||
|
||
local replacement = shallow_copy(request)
|
||
replacement.body = encode_stub(state)
|
||
return { action = "replace", value = replacement }
|
||
end
|
||
|
||
function plugin.on_response(ctx, response)
|
||
if type(response) ~= "table" then
|
||
return { action = "block", reason = "invalid response" }
|
||
end
|
||
-- SSE 响应只在 on_event 处理,body 是 JSON null,不能整体替换
|
||
if response.streaming == true then return nil end
|
||
|
||
local key = key_for(ctx)
|
||
if not key then return { action = "block", reason = "missing request_id" } end
|
||
local state = requests[key]
|
||
if not state then return { action = "block", reason = "request state missing" } end
|
||
|
||
if state.verdict ~= "allow" then
|
||
clear(key)
|
||
return { action = "replace", value = error_response(state.policy) }
|
||
end
|
||
|
||
if state.opaque then
|
||
clear(key)
|
||
return { action = "pass" }
|
||
end
|
||
|
||
if response.status ~= 200 then
|
||
-- 上游自己返回的 OpenAI 错误,原样透传
|
||
clear(key)
|
||
return { action = "pass" }
|
||
end
|
||
|
||
if type(response.body) ~= "string" then
|
||
clear(key)
|
||
return { action = "replace", value = error_response(policy_unavailable("invalid_response_body")) }
|
||
end
|
||
|
||
local ok_decode, decoded = pcall(host.json.decode, response.body)
|
||
if not ok_decode or type(decoded) ~= "table" then
|
||
clear(key)
|
||
return { action = "replace", value = error_response(policy_unavailable("response_not_json")) }
|
||
end
|
||
|
||
local locations, malformed = collect_all(decoded, config.content_paths_full)
|
||
if malformed then
|
||
clear(key)
|
||
return { action = "replace", value = error_response(policy_unavailable("unexpected_response_shape")) }
|
||
end
|
||
|
||
local text = join_locations(locations)
|
||
if text ~= "" and config.check_output then
|
||
local verdict, err = judge("output", nil, text, state.input_text)
|
||
if not verdict then
|
||
clear(key)
|
||
return { action = "replace", value = error_response(policy_unavailable(err)) }
|
||
end
|
||
if verdict.allow ~= true then
|
||
local policy = policy_denied(verdict, "output")
|
||
clear(key)
|
||
return { action = "replace", value = error_response(policy) }
|
||
end
|
||
end
|
||
|
||
local changed, redact_err = redact_locations(locations)
|
||
clear(key)
|
||
if redact_err then
|
||
return { action = "replace", value = error_response(policy_unavailable(redact_err)) }
|
||
end
|
||
if not changed then return { action = "pass" } end
|
||
|
||
local ok_encode, encoded = pcall(host.json.encode, decoded)
|
||
if not ok_encode or type(encoded) ~= "string" then
|
||
return { action = "replace", value = error_response(policy_unavailable("response_encode_failed")) }
|
||
end
|
||
local replacement = shallow_copy(response)
|
||
replacement.body = encoded
|
||
return { action = "replace", value = replacement }
|
||
end
|
||
|
||
function plugin.on_event(ctx, event)
|
||
if type(event) ~= "table" then
|
||
return { action = "block", reason = "invalid event" }
|
||
end
|
||
|
||
local key = key_for(ctx)
|
||
if not key then return { action = "block", reason = "missing request_id" } end
|
||
local state = requests[key]
|
||
if not state then return { action = "block", reason = "request state missing" } end
|
||
|
||
-- 已经给出错误帧:后续一切事件全部吞掉,连接由宿主正常关闭
|
||
if state.terminal then
|
||
return { action = "replace", events = host.json.array() }
|
||
end
|
||
|
||
-- 请求侧已判定不通过或审核不可用:第一帧就换成 OpenAI 错误
|
||
if state.verdict ~= "allow" then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({ error_frame(state.policy) }) }
|
||
end
|
||
|
||
local entry = { event = event, lengths = {} }
|
||
local added = 0
|
||
|
||
if event.has_data ~= false and type(event.data) == "string" and event.data ~= "" then
|
||
if event.data == "[DONE]" then
|
||
-- 终止帧本身没有正文,随缓冲内容一起按序放行
|
||
state.pending[#state.pending + 1] = entry
|
||
local events, policy = release(state)
|
||
if not events then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
|
||
end
|
||
return { action = "replace", events = events }
|
||
end
|
||
|
||
local ok_decode, decoded = pcall(host.json.decode, event.data)
|
||
if not ok_decode or type(decoded) ~= "table" then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({
|
||
error_frame(policy_unavailable("invalid_stream_frame")),
|
||
}) }
|
||
end
|
||
|
||
local locations, malformed = collect_all(decoded, config.content_paths_stream)
|
||
if malformed then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({
|
||
error_frame(policy_unavailable("unexpected_stream_shape")),
|
||
}) }
|
||
end
|
||
|
||
for i, location in ipairs(locations) do
|
||
local text = location.parent[location.key]
|
||
entry.lengths[i] = #text
|
||
state.texts[#state.texts + 1] = text
|
||
added = added + #text
|
||
-- 增量维护句边界扫描窗口(只保留尾部,避免持有整段文本副本)
|
||
state.tail = utf8_tail(state.tail .. text, MAX_TAIL_BYTES)
|
||
end
|
||
end
|
||
|
||
state.pending[#state.pending + 1] = entry
|
||
state.text_bytes = state.text_bytes + added
|
||
|
||
if state.text_bytes > config.max_buffer_bytes then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({
|
||
error_frame({
|
||
status = 413,
|
||
type = "invalid_request_error",
|
||
code = "response_too_large",
|
||
message = "The model response exceeded the safety review buffer limit.",
|
||
}),
|
||
}) }
|
||
end
|
||
|
||
if config.stream_mode == "incremental" and added > 0 and should_flush(state) then
|
||
local events, policy = release(state)
|
||
if not events then
|
||
state.terminal = true
|
||
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
|
||
end
|
||
return { action = "replace", events = events }
|
||
end
|
||
|
||
return { action = "hold" }
|
||
end
|
||
|
||
function plugin.on_end(ctx)
|
||
local key = key_for(ctx)
|
||
if not key then return { action = "block", reason = "missing request_id" } end
|
||
local state = requests[key]
|
||
if not state then return nil end
|
||
|
||
if state.terminal then
|
||
clear(key)
|
||
return nil
|
||
end
|
||
if #state.pending == 0 then
|
||
clear(key)
|
||
return nil
|
||
end
|
||
|
||
local events, policy = release(state)
|
||
clear(key)
|
||
if not events then
|
||
return { action = "replace", events = host.json.array({ error_frame(policy) }) }
|
||
end
|
||
return { action = "replace", events = events }
|
||
end
|
||
|
||
function plugin.close(ctx)
|
||
local key = key_for(ctx)
|
||
if key then clear(key) end
|
||
return nil
|
||
end
|
||
|
||
return plugin
|