fix(ai): 模型返回容错解析与失败自动重试,减少 AI 剪辑助手报错
- parseJson 支持思考标签、代码块、嵌套花括号与字符串内花括号的平衡扫描 - JSON 解析失败时自动重试一次:取消强制 format 并追加严格输出提示 - Anthropic 协议补齐 temperature=0.2,稳定输出 - 上下文超长等错误附带可操作的修复提示
This commit is contained in:
1 parent
de19ecc42c
commit
b865f2979d
2 files changed
+46
-5
No files matched your search
@@ -10,3 +10,23 @@ test('适配器协议合约(本机测试服务器,不代表云端联调)',
|
||||
await assert.rejects(complete({protocol:'openai',baseUrl:'https://example.com',model:'x',allowText:false},'private'),/未授权/);
|
||||
assert.deepEqual(parseJson('```json\n{"ok":true}\n```'),{ok:true});
|
||||
});
|
||||
test('JSON 容错解析:思考标签、前置文字、嵌套花括号与字符串中的花括号',()=>{
|
||||
assert.deepEqual(parseJson('<think>思考过程</think>{"ok":true}'),{ok:true});
|
||||
assert.deepEqual(parseJson('好的,以下是结果:\n```json\n{"a":{"b":[1,{"c":"带}和{括号"}]}}\n```\n希望有帮助'),{a:{b:[1,{c:'带}和{括号'}]}});
|
||||
assert.deepEqual(parseJson('{"results":[{"id":"x","text":"}]"}]}'),{results:[{id:'x',text:'}]'}]});
|
||||
assert.throws(()=>parseJson('完全没有 JSON 内容'),/JSON/);
|
||||
});
|
||||
test('JSON 解析失败自动重试:第二次不再强制 format 并追加严格提示',async()=>{
|
||||
const calls=[];
|
||||
const server=http.createServer(async(req,res)=>{let data='';for await(const part of req)data+=part;const body=JSON.parse(data);calls.push(body);res.setHeader('Content-Type','application/json');
|
||||
if(body.format==='json')res.end(JSON.stringify({message:{content:'这是一段没有 JSON 的回答'},eval_count:3}));
|
||||
else res.end(JSON.stringify({message:{content:'{"ok":true}'},eval_count:4}));});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));const baseUrl=`http://127.0.0.1:${server.address().port}`;
|
||||
try{
|
||||
const r=await complete({protocol:'ollama',baseUrl,model:'test-only'},'请输出 JSON');
|
||||
assert.equal(r.data.ok,true);
|
||||
assert.equal(calls.length,2);
|
||||
assert.equal(calls[1].format,undefined);
|
||||
assert.ok(calls[1].messages[0].content.includes('只输出一个 JSON 对象'));
|
||||
}finally{server.closeAllConnections();server.close();}
|
||||
});
|
||||
Reference in new issue
Block a user