Skip to content

Report an empty model response as itself, not as invalid JSON - #272

Closed
mostafaseyedan wants to merge 2 commits into
microsoft:mainfrom
mostafaseyedan:fix/llm-empty-response
Closed

mostafaseyedan wants to merge 2 commits into
microsoft:mainfrom
mostafaseyedan:fix/llm-empty-response

Conversation

@mostafaseyedan

Copy link
Copy Markdown
Contributor

Problem

When the language model returns an empty stream, callLlmJson reports a JSON parsing problem that did not happen.

parseLlmJson('') throws No JSON structure found in LLM response. That message matches the /JSON|parse/i test used to classify retry failures, so the attempt increments parseFailures, and the user sees:

LLM returned invalid JSON after 3 attempts. Please try again.

Nothing was wrong with the model's JSON — there was no response at all. The suggested remedy is wrong too: the usual causes are an exhausted request quota or a model declining the request, and neither is fixed by retrying.

This is actively misleading in practice. From a real runtime.log, with the Copilot auto model:

schema=skill_triage attempt=1 structured=true  model=auto textLen=0 error=No JSON structure found in LLM response
schema=skill_triage attempt=2 structured=false model=auto textLen=0 error=No JSON structure found in LLM response
schema=skill_triage attempt=3 structured=false model=auto textLen=0 error=No JSON structure found in LLM response

All three attempts failed in 11 ms total with textLen=0. The surfaced error sends the reader looking for a prompt or schema problem, when the model never produced a token. The same failure hit context_file_review a minute later, so it affects every AI feature, not one page.

Fix

Detect the empty stream directly and report it with the model id:

The language model (auto) returned an empty response 3 time(s). This usually means the request quota is exhausted or the model declined the request.

Empty responses are tracked separately from parse failures rather than folded into them, so a genuine malformed-JSON reply still reports as before.

Also adds a runtimeDebug line recording the available model catalog when no preferred family matches, so the log shows which models the fallback selection had to choose from — the model=auto above gave no indication of what else was on offer.

Testing

npm run typecheck and npm run lint clean (0 errors); 107 webview tests pass.

When the language model returns an empty stream, parseLlmJson throws
"No JSON structure found in LLM response". That message matches the
/JSON|parse/i test used to classify retry failures, so the attempt is
counted as a parse failure and the user is told:

  LLM returned invalid JSON after 3 attempts. Please try again.

Nothing was wrong with the model's JSON — there was no response at all.
The suggested remedy ("try again") is also wrong, since the usual cause
is an exhausted request quota or a model declining the request, neither
of which a retry fixes. Observed with three attempts failing in 11ms
with textLen=0, which no amount of retrying would have resolved.

Detect the empty stream directly and report it with the model id, so
the message names the real cause. An empty response is tracked
separately from parse failures rather than being folded into them.

Also log the available model catalog when no preferred family matches,
so the debug log records which models the selected fallback came from.

@san360 Sanjay Singh (san360) left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot mostafaseyedan for tracking this down! The runtime.log excerpt in the description made the root cause very clear: an empty stream reaches parseLlmJson, the "No JSON structure found" error matches the /JSON|parse/i check, and the user is told the model returned invalid JSON when it returned nothing at all. The fix is small and focused, which we appreciate.

What we verified

  • On current main, callLlmJson still reports three empty (or whitespace-only) replies as "LLM returned invalid JSON after 3 attempts" (the plain-text callLlm path was fixed in #301, the JSON path wasn't). With this PR the message correctly says the response was empty, and real malformed JSON is still reported as invalid JSON.
  • Typecheck, knip and the full unit suite pass with the PR on current main; build size is within budget.
  • We also called the PR's callLlmJson against the real Copilot Auto model with a prompt that makes it reply with nothing.

One behaviour change we'd like to fix before merging

With the PR, an empty reply no longer adds the "respond ONLY with valid JSON" hint for the next attempt (details inline). In the live test, Copilot Auto returned an empty first reply in every run; on main the next attempt, with the hint, came back with JSON every time (4 of 4), while with this PR all three attempts came back empty (0 of 4) and the call failed. So an empty first reply that the hint can rescue now becomes an error. Could we keep sending the hint after an empty reply, and only count it separately for the final message?

Smaller points

  1. Message wording. callLlm already has EMPTY_RESPONSE_MESSAGE ("GitHub Copilot returned an empty response. Try again."). Reusing it would keep both paths consistent. The model was healthy when we saw empty replies, so we'd rather not suggest the quota is exhausted; quota and permission problems usually arrive as LanguageModelErrors rather than empty streams.
  2. Mixed failures. Right now a single empty attempt wins: two invalid-JSON replies followed by one empty reply are reported as "returned an empty response 1 time(s)". Reporting "empty" only when no attempt produced unparsable text would keep the message accurate.
  3. Test. A small case in src/webview/panel-llm-call.test.ts would lock this in, for example:
    it('reports empty replies as empty instead of invalid JSON', async () => {
      mocks.sendRequest.mockImplementation(() => Promise.resolve(reply('  ', '\n')));
      await expect(callLlmJson(prompt(), { name: 'test_schema', schema: { type: 'object' } }))
        .rejects.toThrow('GitHub Copilot returned an empty response');
      expect(mocks.sendRequest).toHaveBeenCalledTimes(3);
    });
  4. Merge conflict. Since #301, model selection lives in src/webview/panel-llm-model.ts and only uses Copilot Auto, so the "any model" fallback (and the model-catalog log) is gone; that hunk can simply be dropped when rebasing. #277 also changed the same retry block (structured output is now dropped on the first failure regardless of the error).
  5. callLlmJson now goes slightly over the lint limits (complexity 24/20, 54/50 lines). Moving the retry bookkeeping into a small helper would keep it under them.

For context, #253 makes a very similar change to the same function (it also needs a rebase on #277), so whichever lands second will need a rebase; we're happy to help line them up.

Thanks again for the careful write-up. A maintainer will approve the CI run once the branch is updated.

Comment thread src/webview/panel-llm.ts
}
// On parse failures, nudge the model to return valid JSON on the next attempt
if (lastError instanceof Error && /JSON|parse/i.test(lastError.message)) {
if (lastError instanceof Error && /empty response/i.test(lastError.message)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An empty reply now skips the JSON hint below, so the retry sends exactly the same prompt. When we tried this against Copilot Auto, an empty first reply came back with JSON on the next attempt every time with the hint (current main), and stayed empty for all three attempts without it. Could we count it separately but still add the hint? For example:

const emptyReply = lastError instanceof Error && lastError.message === EMPTY_RESPONSE_MESSAGE;
const parseFailure = !emptyReply && lastError instanceof Error && /JSON|parse/i.test(lastError.message);
if (emptyReply) emptyResponses++;
if (parseFailure) parseFailures++;
if ((emptyReply || parseFailure) && retryMessages.length === messages.length) {
  retryMessages.push(vscode.LanguageModelChatMessage.User(
    'Your previous response was not valid JSON. Please respond ONLY with a valid JSON object or array, no markdown fences, no commentary.'
  ));
}

(with throw new Error(EMPTY_RESPONSE_MESSAGE) on line 425).

Comment thread src/webview/panel-llm.ts
const label = parseFailures > 0
? `LLM returned invalid JSON after ${LLM_MAX_RETRIES + 1} attempts. Please try again.`
: (lastError instanceof Error ? lastError.message : 'LLM request failed after retries');
const label = emptyResponses > 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two small things here: callLlm already reports this case as EMPTY_RESPONSE_MESSAGE, so reusing it would keep the wording the same everywhere, and the quota/decline explanation didn't match what we saw (the model was healthy). Also, because emptyResponses > 0 is checked first, two invalid-JSON replies plus one empty reply are reported as "empty response 1 time(s)". One option:

const label = parseFailures > 0
  ? `LLM returned invalid JSON after ${LLM_MAX_RETRIES + 1} attempts. Please try again.`
  : emptyResponses > 0
    ? EMPTY_RESPONSE_MESSAGE
    : (lastError instanceof Error ? lastError.message : 'LLM request failed after retries');

@san360

Copy link
Copy Markdown
Contributor

Thank you mostafaseyedan for this fix, and for tracking down why an empty reply showed up as "invalid JSON"! #253 fixes the same problem (#91) and has now been merged. It also covers the structured-output path and adds tests for both cases. So we're closing this one as superseded. We really appreciate your contributions to the project. Please keep them coming!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants