a779a26ebb
- 灵感服务:读取本人会话、角色背景和已触发世界书,生成三条短回复,不写聊天记录 - 请求约束:账号隔离、并发与频率限制、超时取消,以及上下文过期检测 - 回归与文档:校验异常模型格式和上下文预算,新增匿名鉴权测试并纳入统一脚本
82 lines
2.9 KiB
TypeScript
82 lines
2.9 KiB
TypeScript
/** 回复灵感的格式、上下文预算与匿名鉴权回归,不调用真实模型。 */
|
|
import "./digital-env";
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import {
|
|
parseReplyIdeas,
|
|
replyIdeasMessages,
|
|
} from "../src/modules/digital/digital.suggestions";
|
|
import { HttpError } from "../src/shared/http-error";
|
|
import { createApp } from "../src/app";
|
|
|
|
test("灵感只接受三个非空、互不重复的短回复,允许模型返回JSON围栏", () => {
|
|
const replies = [
|
|
"我想听听你的故事。",
|
|
"我们一起去看看吧。",
|
|
"你刚才说的那个地方在哪里?",
|
|
];
|
|
assert.deepEqual(
|
|
parseReplyIdeas(
|
|
"```json\n" + JSON.stringify({ suggestions: replies }) + "\n```",
|
|
),
|
|
replies,
|
|
);
|
|
for (const value of [
|
|
undefined,
|
|
"invalid-secret-do-not-echo",
|
|
JSON.stringify({ suggestions: [] }),
|
|
JSON.stringify({ suggestions: ["相同", "相同 ", "另一个"] }),
|
|
JSON.stringify({ suggestions: ["x".repeat(241), "二", "三"] }),
|
|
JSON.stringify({ suggestions: ["one", null, "three"] }),
|
|
])
|
|
assert.throws(
|
|
() => parseReplyIdeas(value),
|
|
(e) =>
|
|
e instanceof HttpError &&
|
|
e.statusCode === 502 &&
|
|
!e.message.includes("secret-do-not-echo"),
|
|
);
|
|
});
|
|
test("灵感上下文保留最新对话、用户身份与草稿,并限制历史和资料预算", () => {
|
|
const history = Array.from({ length: 40 }, (_, i) => ({
|
|
role: (i % 2 ? "assistant" : "user") as "user" | "assistant",
|
|
content: ("旧消息" + i).repeat(1000),
|
|
}));
|
|
history.push({ role: "user", content: "最后一句:蓝色灯笼该叫什么名字?" });
|
|
const messages = replyIdeasMessages({
|
|
name: "陆沉舟",
|
|
description: "设定".repeat(10000),
|
|
scenario: "场景".repeat(10000),
|
|
userName: "小雨",
|
|
persona: "旅人",
|
|
memory: "我们约好看灯塔",
|
|
draft: "我想叫它",
|
|
lore: ["已触发的世界书"],
|
|
history,
|
|
});
|
|
assert.ok(messages[0].content.includes("用户视角"));
|
|
assert.equal(messages[0].role, "system");
|
|
const context = JSON.parse(messages[1].content);
|
|
assert.equal(context.history.length, 12);
|
|
assert.equal(context.history.at(-1).speaker, "用户");
|
|
assert.ok(context.history.at(-1).content.includes("蓝色灯笼"));
|
|
assert.equal(context.draft, "我想叫它");
|
|
assert.equal(context.userName, "小雨");
|
|
assert.ok(context.description.length <= 1200);
|
|
assert.ok(context.scenario.length <= 800);
|
|
assert.ok(messages[1].content.length < 20000);
|
|
});
|
|
test("灵感接口不接受匿名用户,即使请求体伪造账号也会先拒绝", async () => {
|
|
const app = createApp();
|
|
try {
|
|
const result = await app.inject({
|
|
method: "POST",
|
|
url: "/api/digital/conversations/unit-conversation/suggestions",
|
|
payload: { account: "super_admin:1", draft: "测试" },
|
|
});
|
|
assert.equal(result.statusCode, 401);
|
|
} finally {
|
|
await app.close();
|
|
}
|
|
});
|