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:
@@ -39,7 +39,7 @@ export async function chat(
|
|||||||
choices: { message: { content: string } }[];
|
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;
|
const content = json.choices?.[0]?.message?.content;
|
||||||
if (content === undefined || content === null) {
|
if (content === undefined || content === null) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
|
|||||||
@@ -53,5 +53,14 @@ export async function interpretClick(
|
|||||||
const json = (await res.json()) as {
|
const json = (await res.json()) as {
|
||||||
choices: { message: { content: string } }[];
|
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;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user