omi icon indicating copy to clipboard operation
omi copied to clipboard

[Bug] iq_rating: unguarded OpenAI response indexing crashes on an empty choices array

Open inklife opened this issue 2 months ago • 3 comments

Symptom

plugins/iq_rating/main.py reads the OpenAI chat-completion payload with bare subscripts in two places. Any 200 response whose choices array is empty raises an uncaught IndexError, and any context_snippets value that is not a list raises TypeError on the slice. Both take down the whole IQ-scoring run rather than degrading to the existing fallback path.

Evidence

calculate_iq_with_ai, line 1081:

if response.status_code == 200:
    result = response.json()
    answer = result["choices"][0]["message"]["content"].strip()   # L1081

filter_names_with_openai, line 295 — the same shape:

if response.status_code == 200:
    result = response.json()
    answer = result["choices"][0]["message"]["content"].strip()   # L295

calculate_iq_with_ai, line 1017:

context = " | ".join(data.get("context_snippets", [])[:10])       # L1017

data.get("context_snippets", []) only falls back to [] when the key is absent. When the key is present but holds a non-list value, the slice raises TypeError: unhashable type: 'slice' — the same defect class already fixed for the public-holidays plugin in #13928.

Why a 200 with no choices is reachable

status_code == 200 is treated as "the call succeeded", but it is not the same as "there is a completion". The Azure OpenAI content-filter documentation describes the case where a completion yields no output content, and the same empty-choices shape is reported upstream in other clients (OmniRoute #3424 is a concrete report of an empty choices array arriving with a 200). This module feeds user-supplied names and transcript context into the prompt, so a moderation-triggered empty response is a realistic input, not a hypothetical one. There is precedent for exactly this guard: Graphify-Labs/graphify#924 ("guard against empty choices and None message in LLM responses").

Impact

calculate_iq_with_ai already has a working non-AI fallback (calculate_iq_score_random, used when OPENAI_API_KEY is unset, L1010-1012). The bug is that a malformed success response bypasses that fallback and aborts the run, and filter_names_with_openai has no guard at all.

Proposed fix

One shared extraction helper used by both call sites:

def _first_message_content(payload) -> Optional[str]:
    """Return the first completion content, or None when the response carries none."""
    if not isinstance(payload, dict):
        return None
    choices = payload.get("choices")
    if not isinstance(choices, list) or not choices:
        return None
    message = choices[0].get("message") if isinstance(choices[0], dict) else None
    if not isinstance(message, dict):
        return None
    content = message.get("content")
    return content if isinstance(content, str) else None

Both call sites then fall back to their existing non-AI path when it returns None, and line 1017 becomes context = " | ".join(_as_text_list(data.get("context_snippets"))[:10]) so a non-list value degrades instead of raising.

Tests

A hermetic suite (stdlib stubs, no network) exercising the real functions through the requests.post seam: a 200 whose body is {"choices": []} must fall back rather than raise; {"choices": [{}]} and {"choices": [{"message": {}}]} likewise; a non-list context_snippets must not raise. Each case fails on current main and passes with the fix.


Proposed bounty: US$25, matching the rate of the other single-plugin correctness fixes in this repository.

cc @josancamon19 @kodjima33

inklife avatar Sep 15 '26 06:09 inklife

Hi maintainers,

I have identified the root causes in plugins/iq_rating/main.py:

  1. calculate_iq_with_ai (L1081) and filter_names_with_openai (L295) indexing into an empty choices list on 200 responses.
  2. calculate_iq_with_ai (L1017) crashing with TypeError when context_snippets is present but None.

I have a minimal defensive fix and regression unit tests ready to cover:

  • Empty choices array
  • Missing or malformed message / content
  • Non-list context_snippets values

Before submitting the PR, could you please confirm if this issue has an active/funded bounty ($25) and what the official payout/claim process is? If confirmed, I'm happy to open the PR immediately. Thanks!

1998LJ avatar Sep 15 '26 06:09 1998LJ

I'd like to work on this bounty. Is it still available, and may I claim/reserve it before I begin?

omnesandre avatar Sep 15 '26 06:09 omnesandre

Closing as already fixed on current main.

Current main iq_rating guards empty/non-list choices before [0] and coerces context_snippets to a list

aryanorastar avatar Sep 20 '26 16:09 aryanorastar