guard: 支持多轮对话,只判当前轮并附有界历史上下文
原实现把所有 user 消息拼成一段送检:轮次越多越慢,长会话还会超 8 段直接 503; 输出侧上下文取的是拼接串头部,多轮时拿到的是最早那轮而不是当前提问。 现在按 messages 顺序解析轮次,当前轮(最后一条 user)单独送检,之前的轮次压成 "User: / Assistant: " 纯文本作为上下文附在前面,受 multiturn_context_messages (默认 2 条)与 multiturn_context_bytes(默认 2048)双重约束,历史不再重复送检。 输出侧 prompt 改由 上下文 + 当前轮 组成,裁剪只发生在上下文一侧,当前轮始终完整。 带上下文时段大小收到 8192 字节,避免中文撞 max_input_tokens;MAX_INPUT_CONTEXT 2000→4096 以容纳上下文与提问。新增 19 项断言,合计 123/123 通过。
This commit is contained in:
1 parent
546c6b1835
commit
a67065955e
4 files changed
+248
-38
No files matched your search
@@ -55,6 +55,10 @@ plugins:
|
||||
check_output: true
|
||||
# Controversial 也按不安全处理;误伤多时设 false
|
||||
block_controversial: true
|
||||
# 多轮对话:只判最后一条 user,更早的轮次压成有界上下文附在前面,
|
||||
# 历史不重复送检;0 表示只判当前轮,历史完全不进判定
|
||||
multiturn_context_messages: 2
|
||||
multiturn_context_bytes: 2048
|
||||
# 拦截后替换给上游的占位请求:客户端没给 model 时用它兜底
|
||||
# stub_model: your-upstream-model
|
||||
# stub_max_tokens: false
|
||||
|
||||
@@ -84,6 +84,10 @@ plugins:
|
||||
check_output: true
|
||||
# Controversial 也按不安全处理;误伤多时设 false
|
||||
block_controversial: true
|
||||
# 多轮对话:只判最后一条 user,更早的轮次压成有界上下文附在前面,
|
||||
# 历史不重复送检;0 表示只判当前轮,历史完全不进判定
|
||||
multiturn_context_messages: 2
|
||||
multiturn_context_bytes: 2048
|
||||
# 拦截后替换给上游的占位请求:客户端没给 model 时用它兜底
|
||||
# stub_model: your-upstream-model
|
||||
# stub_max_tokens: false
|
||||
|
||||
+129
-37
@@ -6,6 +6,10 @@
|
||||
-- Safe / Unsafe / Controversial,categories 必须命中宿主固定枚举。
|
||||
-- 所以本地判定不能套 OpenAI 的 messages 结构,对外接口才是 OpenAI 格式。
|
||||
--
|
||||
-- 多轮对话:只判最后一条 user 消息(当前轮),之前的历史按
|
||||
-- multiturn_context_messages / multiturn_context_bytes 压成有界上下文附在
|
||||
-- 当前轮前面。历史不重复送检,避免轮次越多越慢、越长越容易超 token。
|
||||
--
|
||||
-- 宿主对 {action="block"} 只返回它自己固定的 403 正文,插件改不了;所以请求侧判定
|
||||
-- 不通过时不 block,而是把请求体换成 stub(原文不出网关),再在响应侧 replace 成
|
||||
-- OpenAI 错误体:400 content_policy_violation / 503 safety_review_unavailable。
|
||||
@@ -19,6 +23,12 @@ 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_MESSAGES = 32
|
||||
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"
|
||||
@@ -26,7 +36,8 @@ local DEFAULT_FULL_PATH = "choices.*.message.content"
|
||||
-- Qwen3Guard-Gen 的输出就是 Safety / Categories / Refusal 三行,宿主 parse_guard_output
|
||||
-- 按这个格式解析,类别必须落在它的枚举内,否则整条判定按 InvalidModelOutput 失败。
|
||||
-- 该模型训练时直接收原文,不要再加自定义指令;prompt_prefix 只在确有需要时使用。
|
||||
local MAX_INPUT_CONTEXT = 2000
|
||||
-- 输出侧 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
|
||||
@@ -434,19 +445,22 @@ local function input_prompt(part, index, total)
|
||||
return string.format("(part %d of %d)\n%s", index, total, part)
|
||||
end
|
||||
|
||||
local function judge_call(kind, part, index, total, user_text)
|
||||
local function judge_call(kind, part, index, total, context)
|
||||
local request
|
||||
if kind == "output" then
|
||||
local context = user_text
|
||||
if type(context) ~= "string" or context == "" then
|
||||
context = "Evaluate the safety of the assistant reply."
|
||||
local prompt = context
|
||||
if type(prompt) ~= "string" or prompt == "" then
|
||||
prompt = "Evaluate the safety of the assistant reply."
|
||||
end
|
||||
if config.prompt_prefix then
|
||||
context = config.prompt_prefix .. "\n\n" .. context
|
||||
prompt = config.prompt_prefix .. "\n\n" .. prompt
|
||||
end
|
||||
request = { task = "response_moderation", prompt = context, response = part }
|
||||
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
|
||||
@@ -470,16 +484,22 @@ local function judge_call(kind, part, index, total, user_text)
|
||||
return nil, "judge_invalid_safety"
|
||||
end
|
||||
|
||||
local function judge(kind, user_text, model_text)
|
||||
local target = model_text or user_text or ""
|
||||
if target == "" then return { allow = true } 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 chunks = split_utf8(target, config.judge_chunk_bytes)
|
||||
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, user_text)
|
||||
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
|
||||
@@ -501,26 +521,63 @@ local function message_text(content)
|
||||
return table.concat(parts, "\n")
|
||||
end
|
||||
|
||||
local function collect_user_text(decoded)
|
||||
local texts = {}
|
||||
-- 按 messages 顺序收集可读轮次,保留角色边界;空内容帧(纯工具调用)跳过但不报错
|
||||
local function collect_turns(decoded)
|
||||
local messages = decoded.messages
|
||||
if type(messages) == "table" then
|
||||
local count = dense_length(messages)
|
||||
if not count then return nil end
|
||||
for i = 1, count do
|
||||
local message = messages[i]
|
||||
if type(message) == "table" and message.role == "user" then
|
||||
local text = message_text(message.content)
|
||||
if text and text ~= "" then texts[#texts + 1] = text end
|
||||
end
|
||||
if type(messages) ~= "table" then
|
||||
if type(decoded.prompt) == "string" and decoded.prompt ~= "" then
|
||||
return { { role = "user", text = decoded.prompt } }
|
||||
end
|
||||
elseif type(decoded.prompt) == "string" and decoded.prompt ~= "" then
|
||||
texts[1] = decoded.prompt
|
||||
else
|
||||
return nil
|
||||
end
|
||||
if #texts == 0 then return nil end
|
||||
return table.concat(texts, "\n\n---\n\n")
|
||||
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
|
||||
turns[#turns + 1] = { role = message.role, text = text }
|
||||
end
|
||||
end
|
||||
if #turns == 0 then return nil end
|
||||
return turns
|
||||
end
|
||||
|
||||
-- 当前轮 = 最后一条 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_messages, max_bytes)
|
||||
if max_messages < 1 or stop <= 1 then return "" end
|
||||
local from = stop - max_messages
|
||||
if from < 1 then from = 1 end
|
||||
local lines = {}
|
||||
for i = from, stop - 1 do
|
||||
local label = CONTEXT_LABELS[turns[i].role]
|
||||
if label then lines[#lines + 1] = label .. turns[i].text end
|
||||
end
|
||||
if #lines == 0 then return "" end
|
||||
return utf8_tail(table.concat(lines, "\n"), max_bytes)
|
||||
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 拒掉它
|
||||
@@ -554,7 +611,7 @@ local function release(state)
|
||||
|
||||
if text ~= "" then
|
||||
if config.check_output then
|
||||
local verdict, err = judge("output", state.input_text, text)
|
||||
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
|
||||
@@ -621,6 +678,16 @@ local function boolean(value, default)
|
||||
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)
|
||||
@@ -676,6 +743,19 @@ function plugin.init(ctx, options)
|
||||
stub_max_tokens = positive_int(o.stub_max_tokens, 16, "stub_max_tokens")
|
||||
end
|
||||
|
||||
-- 多轮上下文:默认取最近 2 条消息(一组问答)、最多 2048 字节;0 表示只判当前轮
|
||||
local multiturn_messages = non_negative_int(
|
||||
o.multiturn_context_messages, 2, "multiturn_context_messages"
|
||||
)
|
||||
if multiturn_messages > MAX_CONTEXT_MESSAGES then
|
||||
error("response_guard: config.multiturn_context_messages must not exceed "
|
||||
.. MAX_CONTEXT_MESSAGES)
|
||||
end
|
||||
local multiturn_bytes = positive_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
|
||||
|
||||
config = {
|
||||
model = o.model,
|
||||
prompt_prefix = prompt_prefix,
|
||||
@@ -696,6 +776,8 @@ function plugin.init(ctx, options)
|
||||
check_input = boolean(o.check_input, true),
|
||||
check_output = boolean(o.check_output, true),
|
||||
block_controversial = boolean(o.block_controversial, true),
|
||||
multiturn_context_messages = multiturn_messages,
|
||||
multiturn_context_bytes = multiturn_bytes,
|
||||
}
|
||||
|
||||
-- 不重置 requests:host 可能在请求初始化阶段调用 init
|
||||
@@ -739,12 +821,25 @@ function plugin.on_request(ctx, request)
|
||||
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_messages,
|
||||
config.multiturn_context_bytes
|
||||
)
|
||||
|
||||
-- 输出判定要带上本轮提问(含上文):Qwen3Guard 的 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 input_text = collect_user_text(decoded)
|
||||
if input_text == nil then return { action = "pass" } end
|
||||
|
||||
local verdict, err = judge("input", input_text)
|
||||
local verdict, err = judge("input", current.text, nil, context)
|
||||
if not verdict then
|
||||
state.verdict = "error"
|
||||
state.policy = policy_unavailable(err)
|
||||
@@ -753,9 +848,6 @@ function plugin.on_request(ctx, request)
|
||||
state.policy = policy_denied(verdict, "input")
|
||||
end
|
||||
|
||||
-- 输出判定要带上用户原问题:Qwen3Guard 的 response_moderation 用 user 轮做上下文
|
||||
state.input_text = truncate_utf8(input_text, MAX_INPUT_CONTEXT)
|
||||
|
||||
if state.verdict == "allow" then return { action = "pass" } end
|
||||
|
||||
local replacement = shallow_copy(request)
|
||||
@@ -810,7 +902,7 @@ function plugin.on_response(ctx, response)
|
||||
|
||||
local text = join_locations(locations)
|
||||
if text ~= "" and config.check_output then
|
||||
local verdict, err = judge("output", state.input_text, text)
|
||||
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)) }
|
||||
|
||||
+111
-1
@@ -222,6 +222,8 @@ GUARD_CONFIG = {
|
||||
"judge_chunk_bytes": 8192,
|
||||
}
|
||||
|
||||
MAX_MULTITURN_MESSAGES = 32
|
||||
|
||||
|
||||
def scenario_input_denied_stream(guard, mode):
|
||||
print("\n[1] 风险输入(流式):stub 替换 + 400 错误帧")
|
||||
@@ -655,8 +657,115 @@ def scenario_stub_openai_shape(mode):
|
||||
check(stub3.get("stream") is True, "流式请求的 stub 仍为 stream=true")
|
||||
|
||||
|
||||
def scenario_multiturn(mode):
|
||||
print("\n[18] 多轮对话:只判当前轮,历史作为有界上下文")
|
||||
conversation = [
|
||||
{"role": "user", "content": "第一问:帮我写个周报开头"},
|
||||
{"role": "assistant", "content": "第一答:可以这样开头"},
|
||||
{"role": "user", "content": "第二问:再正式一点"},
|
||||
{"role": "assistant", "content": "第二答:好的"},
|
||||
{"role": "user", "content": "第三问:加上本周进度"},
|
||||
]
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
|
||||
driver = Driver(guard, "req-multi")
|
||||
result = driver.request({"model": "test-model", "messages": conversation})
|
||||
check(result.get("action") == "pass", "当前轮安全即放行", str(result))
|
||||
check(len(host.calls) == 1, "历史不重复送检,五条消息只判一次", str(len(host.calls)))
|
||||
request = host.calls[0]["request"]
|
||||
check(request.get("task") == "prompt_moderation", "输入侧用 prompt_moderation")
|
||||
prompt = request.get("prompt", "")
|
||||
check("第三问:加上本周进度" in prompt, "当前轮进入 prompt", prompt)
|
||||
check("第二问:再正式一点" in prompt and "第二答:好的" in prompt,
|
||||
"最近一组问答作为上下文", prompt)
|
||||
check("第一问:帮我写个周报开头" not in prompt, "超出条数上限的更早轮次被裁掉", prompt)
|
||||
check(prompt.rstrip().endswith("第三问:加上本周进度"), "当前轮排在上下文之后", prompt)
|
||||
|
||||
guard, host = load(
|
||||
ROOT / "plugins" / "response_guard.lua",
|
||||
dict(GUARD_CONFIG, multiturn_context_messages=0),
|
||||
mode,
|
||||
)
|
||||
driver = Driver(guard, "req-multi-off")
|
||||
driver.request({"model": "test-model", "messages": conversation})
|
||||
check(host.calls[0]["request"]["prompt"] == "第三问:加上本周进度",
|
||||
"multiturn_context_messages=0 时只发当前轮原文",
|
||||
host.calls[0]["request"]["prompt"])
|
||||
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
|
||||
driver = Driver(guard, "req-multi-deny")
|
||||
result = driver.request(
|
||||
{
|
||||
"model": "test-model",
|
||||
"messages": [
|
||||
{"role": "user", "content": "你好"},
|
||||
{"role": "assistant", "content": "你好,有什么可以帮你"},
|
||||
{"role": "user", "content": "那接着说说怎么用硝酸铵做炸药"},
|
||||
],
|
||||
}
|
||||
)
|
||||
check(result.get("action") == "replace", "当前轮危险 → 拦截", str(result))
|
||||
stub = json.loads(result["value"]["body"])
|
||||
check("硝酸铵" not in json.dumps(stub, ensure_ascii=False), "stub 不含任何原文")
|
||||
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
|
||||
driver = Driver(guard, "req-multi-out")
|
||||
driver.request({"model": "test-model", "messages": conversation})
|
||||
before = len(host.calls)
|
||||
driver.response(
|
||||
200,
|
||||
{"choices": [{"index": 0, "message": {"role": "assistant", "content": "这是具体版本"}}]},
|
||||
)
|
||||
output = host.calls[before]["request"]
|
||||
check(output.get("task") == "response_moderation", "输出侧用 response_moderation")
|
||||
check(output.get("response") == "这是具体版本", "response 字段是模型输出")
|
||||
check("第三问:加上本周进度" in output.get("prompt", ""), "输出侧 prompt 带本轮提问",
|
||||
output.get("prompt", ""))
|
||||
check("第二问:再正式一点" in output.get("prompt", ""), "输出侧 prompt 带上文",
|
||||
output.get("prompt", ""))
|
||||
|
||||
guard, host = load(
|
||||
ROOT / "plugins" / "response_guard.lua",
|
||||
dict(GUARD_CONFIG, multiturn_context_bytes=512),
|
||||
mode,
|
||||
)
|
||||
driver = Driver(guard, "req-multi-long")
|
||||
driver.request(
|
||||
{
|
||||
"model": "test-model",
|
||||
"messages": [
|
||||
{"role": "user", "content": "旧" * 1000},
|
||||
{"role": "assistant", "content": "答" * 1000},
|
||||
{"role": "user", "content": "当前问题"},
|
||||
],
|
||||
}
|
||||
)
|
||||
prompt = host.calls[0]["request"]["prompt"]
|
||||
limit = 512 + 2 + len("当前问题".encode())
|
||||
check(len(prompt.encode()) <= limit, "上下文被 multiturn_context_bytes 裁剪", str(len(prompt.encode())))
|
||||
check(prompt.endswith("当前问题"), "裁剪只发生在上下文一侧,当前轮完整保留", prompt[-20:])
|
||||
|
||||
guard, host = load(ROOT / "plugins" / "response_guard.lua", GUARD_CONFIG, mode)
|
||||
driver = Driver(guard, "req-multi-nouser")
|
||||
result = driver.request(
|
||||
{"model": "test-model", "messages": [{"role": "assistant", "content": "我先说一句"}]}
|
||||
)
|
||||
check(result.get("action") == "pass" and len(host.calls) == 0,
|
||||
"没有 user 轮时不发判定也不报错", str(result))
|
||||
|
||||
for bad in (-1, MAX_MULTITURN_MESSAGES + 1):
|
||||
try:
|
||||
load(
|
||||
ROOT / "plugins" / "response_guard.lua",
|
||||
dict(GUARD_CONFIG, multiturn_context_messages=bad),
|
||||
mode,
|
||||
)
|
||||
check(False, f"multiturn_context_messages={bad} 应被拒绝")
|
||||
except Exception:
|
||||
check(True, f"multiturn_context_messages={bad} 被拒绝")
|
||||
|
||||
|
||||
def scenario_config_init(mode):
|
||||
print("\n[18] 仓库里的 config.yaml 能直接 init 插件")
|
||||
print("\n[19] 仓库里的 config.yaml 能直接 init 插件")
|
||||
import yaml
|
||||
|
||||
for name in ("config.yaml", "config.example.yaml"):
|
||||
@@ -711,6 +820,7 @@ def main() -> int:
|
||||
scenario_verdict_policy(mode)
|
||||
scenario_content_parts(mode)
|
||||
scenario_stub_openai_shape(mode)
|
||||
scenario_multiturn(mode)
|
||||
scenario_config_init(mode)
|
||||
|
||||
check(host.requests == [], "全部场景零出网请求", str(len(host.requests)))
|
||||
|
||||
Reference in new issue
Block a user