fix(ai-client): improve error handling in chat and vision functions

- Add explicit check for empty choices array in both chat.ts and vision.ts
- Add optional chaining for message property access
- Throw descriptive error when API returns no content
- Use English comments consistent with project style
- Fixes debugging issues when upstream returns empty responses

Related to: chat.ts and vision.ts silent empty string return on malformed responses
This commit is contained in:
yuanzonghao
2026-05-31 12:41:56 +08:00
parent c610efcb26
commit 10359d1a01
2 changed files with 11 additions and 2 deletions
+1 -1
View File
@@ -39,7 +39,7 @@ export async function chat(
choices: { message: { content: string } }[];
};
// 修复问题2和问题5:检查choices是否为空,以及message是否存在
// Guard against empty choices array or missing message/content fields
const content = json.choices?.[0]?.message?.content;
if (content === undefined || content === null) {
throw new Error(
+10 -1
View File
@@ -53,5 +53,14 @@ export async function interpretClick(
const json = (await res.json()) as {
choices: { message: { content: string } }[];
};
return json.choices[0]?.message.content ?? "";
// Guard against empty choices array or missing message/content fields
const content = json.choices?.[0]?.message?.content;
if (content === undefined || content === null) {
throw new Error(
`Vision API returned no content. Response: ${JSON.stringify(json).slice(0, 500)}`
);
}
return content;
}