From c610efcb2623d84078291a87ae47b3f1fbec18d0 Mon Sep 17 00:00:00 2001 From: yuanzonghao Date: Sun, 31 May 2026 12:38:55 +0800 Subject: [PATCH] fix(ai-client): improve error handling in chat function - Add explicit check for empty choices array - Add optional chaining for message property access - Throw descriptive error when API returns no content - Fixes debugging issues when upstream returns empty responses Resolves: chat.ts silent empty string return on malformed responses --- packages/ai-client/src/chat.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/packages/ai-client/src/chat.ts b/packages/ai-client/src/chat.ts index f039fdd..ab5be4f 100644 --- a/packages/ai-client/src/chat.ts +++ b/packages/ai-client/src/chat.ts @@ -38,5 +38,14 @@ export async function chat( const json = (await res.json()) as { choices: { message: { content: string } }[]; }; - return json.choices[0]?.message.content ?? ""; + + // 修复问题2和问题5:检查choices是否为空,以及message是否存在 + const content = json.choices?.[0]?.message?.content; + if (content === undefined || content === null) { + throw new Error( + `Chat API returned no content. Response: ${JSON.stringify(json).slice(0, 500)}` + ); + } + + return content; }