Files
AI-cut/tests/providers.test.mjs
T
xhgit b865f2979d fix(ai): 模型返回容错解析与失败自动重试,减少 AI 剪辑助手报错
- parseJson 支持思考标签、代码块、嵌套花括号与字符串内花括号的平衡扫描
- JSON 解析失败时自动重试一次:取消强制 format 并追加严格输出提示
- Anthropic 协议补齐 temperature=0.2,稳定输出
- 上下文超长等错误附带可操作的修复提示
2026-11-14 11:13:06 +08:00

33 lines
3.4 KiB
JavaScript

import {test} from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import {complete,listModels,parseJson} from '../desktop/core/providers.mjs';
test('适配器协议合约(本机测试服务器,不代表云端联调)',async()=>{
let body,url,headers;const server=http.createServer(async(req,res)=>{let data='';for await(const part of req)data+=part;body=data?JSON.parse(data):null;url=req.url;headers=req.headers;res.setHeader('Content-Type','application/json');if(req.url==='/api/chat')res.end(JSON.stringify({message:{content:'{"ok":true}'},eval_count:4}));else if(req.url==='/messages')res.end(JSON.stringify({content:[{type:'text',text:'{"ok":true}'}]}));else if(req.url.includes('generateContent'))res.end(JSON.stringify({candidates:[{content:{parts:[{text:'{"ok":true}'}]}}]}));else if(req.url==='/models')res.end(JSON.stringify({data:[{id:'test-only'}]}));else res.end(JSON.stringify({choices:[{message:{content:'{"ok":true}'}}]}));});
await new Promise(r=>server.listen(0,'127.0.0.1',r));const baseUrl=`http://127.0.0.1:${server.address().port}`;
try{for(const protocol of ['ollama','openai','anthropic','gemini']){const r=await complete({protocol,baseUrl,model:'test-only',key:'contract-secret'},'json');assert.equal(r.data.ok,true);if(protocol==='anthropic'){assert.equal(headers['x-api-key'],'contract-secret');assert.equal(body.max_tokens,8192);}if(protocol==='gemini'){assert.ok(url.endsWith(':generateContent'));assert.equal(headers['x-goog-api-key'],'contract-secret');}if(protocol==='ollama')assert.equal(body.stream,false);}assert.equal((await listModels({protocol:'openai',baseUrl}))[0].id,'test-only');}
finally{server.closeAllConnections();server.close();}
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();}
});