From b865f2979d43469e7c89dbf2dd460ed410568583 Mon Sep 17 00:00:00 2001 From: xhgit <1+xhgit@noreply.git.xhmcl.com> Date: Sat, 14 Nov 2026 11:13:06 +0800 Subject: [PATCH] =?UTF-8?q?fix(ai):=20=E6=A8=A1=E5=9E=8B=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E5=AE=B9=E9=94=99=E8=A7=A3=E6=9E=90=E4=B8=8E=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E9=87=8D=E8=AF=95=EF=BC=8C=E5=87=8F=E5=B0=91?= =?UTF-8?q?=20AI=20=E5=89=AA=E8=BE=91=E5=8A=A9=E6=89=8B=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - parseJson 支持思考标签、代码块、嵌套花括号与字符串内花括号的平衡扫描 - JSON 解析失败时自动重试一次:取消强制 format 并追加严格输出提示 - Anthropic 协议补齐 temperature=0.2,稳定输出 - 上下文超长等错误附带可操作的修复提示 --- desktop/core/providers.mjs | 31 ++++++++++++++++++++++++++----- tests/providers.test.mjs | 20 ++++++++++++++++++++ 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/desktop/core/providers.mjs b/desktop/core/providers.mjs index 1ddbcbb..7031f9f 100644 --- a/desktop/core/providers.mjs +++ b/desktop/core/providers.mjs @@ -20,14 +20,35 @@ export async function request(c,endpoint,body,signal){ } if(!res.ok){let detail=(await res.text()).slice(0,1200);if(c.key)detail=detail.replaceAll(c.key,'[已隐藏]');throw Error(`模型服务 HTTP ${res.status}:${detail}`);}return res; } -export function parseJson(text){const cleaned=text.replace(/[\s\S]*?<\/think>/g,'').replace(/^\s*```(?:json)?\s*/,'').replace(/\s*```\s*$/,'').trim();try{return JSON.parse(cleaned);}catch{const start=cleaned.indexOf('{'),end=cleaned.lastIndexOf('}');if(start>=0&&end>start)return JSON.parse(cleaned.slice(start,end+1));throw Error('模型未返回有效 JSON,请重试或更换模型');}} -export async function complete(c,prompt,images=[],signal){const started=Date.now();try{const result=await completeRequest(c,prompt,images,signal);observer({time:new Date().toISOString(),model:c.model,protocol:c.protocol,accountId:c.id,images:images.length,status:'ok',elapsed:Date.now()-started,usage:result.usage});return result;}catch(e){let error=String(e.message);if(c.key)error=error.replaceAll(c.key,'[已隐藏]');observer({time:new Date().toISOString(),model:c.model,protocol:c.protocol,accountId:c.id,images:images.length,status:'error',elapsed:Date.now()-started,error});throw Error(error);}} -async function completeRequest(c,prompt,images=[],signal){ +export function parseJson(text){ + let t=String(text||'').replace(/^/,'').replace(//g,'').replace(/<\/?thinking>/g,'').trim(); + const fence=/^```(?:json)?\s*([\s\S]*?)\s*```$/.exec(t);if(fence)t=fence[1].trim(); + try{return JSON.parse(t);}catch{} + const start=t.indexOf('{'); + if(start>=0){let depth=0,inStr=false,esc=false; + for(let i=start;i(await fs.readFile(i)).toString('base64')));let body,endpoint; - if(c.protocol==='ollama'){endpoint='api/chat';body={model:c.model,stream:false,format:'json',messages:[{role:'user',content:prompt,...(encoded.length?{images:encoded}:{})}],options:{temperature:0.2,num_ctx:16384}};} - else if(c.protocol==='anthropic'){endpoint='messages';body={model:c.model,max_tokens:8192,messages:[{role:'user',content:[...encoded.map(data=>({type:'image',source:{type:'base64',media_type:'image/jpeg',data}})),{type:'text',text:prompt}]}]};} + if(c.protocol==='ollama'){endpoint='api/chat';body={model:c.model,stream:false,...(formatJson?{format:'json'}:{}),messages:[{role:'user',content:prompt,...(encoded.length?{images:encoded}:{})}],options:{temperature:0.2,num_ctx:16384}};} + else if(c.protocol==='anthropic'){endpoint='messages';body={model:c.model,max_tokens:8192,temperature:0.2,messages:[{role:'user',content:[...encoded.map(data=>({type:'image',source:{type:'base64',media_type:'image/jpeg',data}})),{type:'text',text:prompt}]}]};} else if(c.protocol==='gemini'){endpoint=`models/${encodeURIComponent(c.model)}:generateContent`;body={contents:[{parts:[{text:prompt},...encoded.map(data=>({inline_data:{mime_type:'image/jpeg',data}}))]}],generationConfig:{responseMimeType:'application/json',temperature:0.2}};} else {endpoint='chat/completions';body={model:c.model,messages:[{role:'user',content:encoded.length?[{type:'text',text:prompt},...encoded.map(data=>({type:'image_url',image_url:{url:'data:image/jpeg;base64,'+data}}))]:prompt}],temperature:0.2};} const started=Date.now(),j=await(await request(c,endpoint,body,signal)).json();const text=c.protocol==='ollama'?j.message?.content:c.protocol==='anthropic'?j.content?.filter(x=>x.type==='text').map(x=>x.text).join(''):c.protocol==='gemini'?j.candidates?.[0]?.content?.parts?.map(x=>x.text||'').join(''):j.choices?.[0]?.message?.content; diff --git a/tests/providers.test.mjs b/tests/providers.test.mjs index 490a2e9..d2d851c 100644 --- a/tests/providers.test.mjs +++ b/tests/providers.test.mjs @@ -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('思考过程{"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();} +});