{"record":{"id":"f06950249bb9ce6d","repo":"BigPizzaV3/CodexPlusPlus","slug":"api-choices-0-message-content-chat-completions-external","errorCode":null,"errorMessage":"API 未返回有效的 choices[0].message.content，请确认兼容 Chat Completions","messagePattern":"API 未返回有效的 choices\\[0\\]\\.message\\.content，请确认兼容 Chat Completions","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"tools/conversation-canvas/external-api.mjs","lineNumber":82,"sourceCode":"      else buffer+=text;\n      if(sse){let end;while((end=buffer.indexOf('\\n'))>=0){consume(buffer.slice(0,end).replace(/\\r$/,''));buffer=buffer.slice(end+1);}}\n      progress({bytes:size,chars:content.length});if(done)break;\n    }\n    const tail=decoder.decode();if(sse){buffer+=tail;if(buffer.trim())consume(buffer.replace(/\\r$/,''));\n      if(!done&&!finish)throw Object.assign(Error('API 流式连接提前结束，本批未提交'),{canvasApiLocal:true,retryable:true});\n      return {choices:[{finish_reason:finish,message:{content}}]};\n    }\n    try{return JSON.parse(raw+tail);}catch{throw Object.assign(Error('API 返回的不是 JSON，请检查 API 地址'),{canvasApiLocal:true});}\n  }finally{void reader.cancel().catch(()=>{});try{reader.releaseLock();}catch{}}\n}\n\nexport function completionText(body){\n  const choice=body?.choices?.[0];\n  if(choice?.finish_reason==='length')throw Error('API 输出达到长度上限，本批未提交；请使用输出容量更大的模型');\n  if(choice?.finish_reason==='content_filter'||choice?.message?.refusal)throw Error('API 未能生成本批整理结果');\n  const content=choice?.message?.content;\n  const value=typeof content==='string'?content:Array.isArray(content)?content.filter(p=>p?.type==='text').map(p=>p.text||'').join(''):'';\n  if(!value.trim())throw Error('API 未返回有效的 choices[0].message.content，请确认兼容 Chat Completions');\n  return value;\n}\n\nexport function waitForApi(promise,signal){\n  signal?.throwIfAborted();\n  if(!signal)return promise;\n  return new Promise((resolve,reject)=>{\n    const abort=()=>{signal.removeEventListener('abort',abort);reject(signal.reason||new DOMException('Aborted','AbortError'));};\n    signal.addEventListener('abort',abort,{once:true});\n    promise.then(value=>{signal.removeEventListener('abort',abort);resolve(value);},error=>{signal.removeEventListener('abort',abort);reject(error);});\n  });\n}\n\nexport function createApiOrganizer({request,timeoutMs=300000,maxRetries=2,retryDelayMs=2000}){\n  const requests=new Map();\n  const closed=()=>new DOMException('整理连接已关闭','AbortError');\n  const dispose=()=>{for(const entry of requests.values())entry.controller.abort(closed());requests.clear();};\n  async function run(config,prompt,requestId,session,onSession,signal,progress=()=>{}){","sourceCodeStart":64,"sourceCodeEnd":100,"githubUrl":"https://github.com/BigPizzaV3/CodexPlusPlus/blob/b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6/tools/conversation-canvas/external-api.mjs#L64-L100","documentation":"completionText() extracts choices[0].message.content and requires a non-empty string after normalization (string content, or array of {type:'text'} parts joined). If the trimmed value is empty — or the response lacks the standard OpenAI choices[0].message.content shape entirely — this error is thrown, indicating the endpoint is not behaving like Chat Completions.","triggerScenarios":"Response with choices: [] or missing choices; message.content null/'' (e.g. only tool_calls or reasoning returned); content array of non-text parts; endpoints returning Responses-API or other non-Chat-Completions shapes.","commonSituations":"Pointing the base URL at a non-chat endpoint (e.g. /v1/embeddings or /v1/responses); providers that return reasoning-only output with empty content; proxies that strip message.content; model that only emitted tool calls.","solutions":["Verify the endpoint URL resolves to .../chat/completions (apiEndpoint appends it automatically — don't pre-strip it)","Use a provider/model that returns plain message.content text for chat requests","Inspect the raw JSON body to confirm choices[0].message.content exists and is non-empty","If using a reasoning model, request the final-answer content or configure the proxy to surface it in message.content"],"exampleFix":"// before\nconst body = await fetch(embeddingsUrl, ...); // wrong endpoint shape\nconst text = completionText(await body.json()); // throws\n// after\nconst body = await fetch('https://api.example.com/v1/chat/completions', {method:'POST', body: JSON.stringify({model, messages})});\nconst text = completionText(await body.json());","handlingStrategy":"validation","validationCode":"function hasChatContent(body) {\n  const c = body?.choices?.[0]?.message?.content;\n  const v = typeof c === 'string' ? c : Array.isArray(c) ? c.filter(p => p?.type === 'text').map(p => p.text || '').join('') : '';\n  return v.trim().length > 0;\n}\nif (!hasChatContent(body)) console.warn('endpoint not Chat-Completions compatible', JSON.stringify(body).slice(0, 500));","typeGuard":"function isChatCompletionBody(b) { return Array.isArray(b?.choices) && b.choices.length > 0 && b.choices[0]?.message != null; }","tryCatchPattern":"try { text = completionText(body); }\ncatch (e) { if (String(e).includes('choices[0].message.content')) { dumpRawBodyForDebug(body); showError('Endpoint incompatible with Chat Completions'); } return; }","preventionTips":["Point baseUrl at the chat completions root; let apiEndpoint append /chat/completions","Smoke-test the endpoint with a tiny 1-message request before large batches","Avoid reasoning-only or tool-only models for batch organization","Log the raw JSON on failure to see the actual response shape"],"tags":["api-response","openai-compatible","unexpected-shape"],"backgroundTag":"unexpected-api-response-shape","analyzedSha":"b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6","analyzedAt":"2026-09-19T23:35:21.129Z","contentChangedAt":"2026-09-19T23:35:21.129Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}