diff --git a/packages/ai-client/src/chat.ts b/packages/ai-client/src/chat.ts index af6ee25..947b669 100644 --- a/packages/ai-client/src/chat.ts +++ b/packages/ai-client/src/chat.ts @@ -30,20 +30,23 @@ export async function chat( body: JSON.stringify(body), }); + const text = await res.text(); if (!res.ok) { - const text = await res.text(); throw new Error(`Chat API error ${res.status}: ${text}`); } - const json = (await res.json()) as { - choices: { message: { content: string } }[]; - }; + let json: { choices: { message: { content: string } }[] }; + try { + json = JSON.parse(text); + } catch { + throw new Error(`Chat API returned invalid JSON: ${text.slice(0, 500)}`); + } // Guard against empty choices array or missing message/content fields const content = json.choices?.[0]?.message?.content; - if (content === undefined || content === null) { + if (typeof content !== "string") { throw new Error( - `Chat API returned no content. Response: ${JSON.stringify(json).slice(0, 500)}` + `Chat API returned no content. Response: ${text.slice(0, 500)}` ); } diff --git a/packages/ai-client/src/vision.ts b/packages/ai-client/src/vision.ts index 1ef9f2c..575a9c6 100644 --- a/packages/ai-client/src/vision.ts +++ b/packages/ai-client/src/vision.ts @@ -45,20 +45,23 @@ export async function interpretClick( clearTimeout(timeoutId); } + const text = await res.text(); if (!res.ok) { - const text = await res.text(); throw new Error(`Vision API error ${res.status}: ${text}`); } - const json = (await res.json()) as { - choices: { message: { content: string } }[]; - }; + let json: { choices: { message: { content: string } }[] }; + try { + json = JSON.parse(text); + } catch { + throw new Error(`Vision API returned invalid JSON: ${text.slice(0, 500)}`); + } // Guard against empty choices array or missing message/content fields const content = json.choices?.[0]?.message?.content; - if (content === undefined || content === null) { + if (typeof content !== "string") { throw new Error( - `Vision API returned no content. Response: ${JSON.stringify(json).slice(0, 500)}` + `Vision API returned no content. Response: ${text.slice(0, 500)}` ); }