Skip to content

fix(backends): reject empty user content before sending chat request - #1632

Merged
planetf1 merged 6 commits into
generative-computing:mainfrom
simonyang08:codex/mellea-1597-empty-user-content-guard
Oct 14, 2026
Merged

planetf1 merged 6 commits into
generative-computing:mainfrom
simonyang08:codex/mellea-1597-empty-user-content-guard

Conversation

@simonyang08

Copy link
Copy Markdown
Contributor

Fixes #1597

Root cause

SimpleContext.view_for_generation() returns [] by design — it is a stateless context. But .add() still exists and returns a chainable context, which reads like it records the turn for the next call. A caller who .add()s a user message and then passes an empty or whitespace-only action to generate_from_context ends up sending the model a conversation with no user-role content at all, and nothing errors. This is exactly what happened in #1587's live Ollama telemetry tests, where Granite 4.2 rambled for 2000+ tokens on the resulting empty prompt and stalled CI.

Fix

Add a shared invariant guard in the chat-message assembly path of the three backends that build user-role conversations for chat APIs — OpenAIBackend._generate_from_chat_context_standard, LiteLLMBackend._generate_from_chat_context_standard, and OllamaModelBackend.generate_from_chat_context:

  • if the fully assembled messages list has no user-role message with non-whitespace content, raise ValueError before any HTTP/SDK call is issued;
  • whitespace-only content counts as empty; user messages that carry images, audio, or documents (_docs) still pass, so vision/RAG paths keep working.

ValueError matches the existing repo convention for "call cannot proceed" (cf. context_lengths.py, intrinsic/_util.py). SimpleContext.add/view_for_generation docstrings now state explicitly that recorded turns are never forwarded, so the .add()-then-empty-action trap is documented at the API surface too.

Note on scope: WatsonxAIBackend and LocalHFBackend also assemble user-role conversations and would benefit from the same guard, but are intentionally left untouched to keep this change focused on the backends named in the issue. Happy to mirror the guard in a follow-up if preferred.

Verification

New regression suite test/backends/test_simple_context_guard.py (mocked providers, no network):

  • empty / whitespace-only action raises on OpenAI, LiteLLM, and Ollama backends — verified RED on unpatched main (DID NOT RAISE ValueError), green after the fix;
  • non-empty user content still sends the request on all three backends;
  • a user message with images passes the guard (multimodal path);
  • the guardian.py call pattern (non-empty context + empty assistant action) is not affected.

Focused backend/context suites: 170 passed. test/stdlib/ regression run shows no new failures relative to unpatched main.

DCO: Signed-off-by: simonyang08 <[email protected]>. AI-assisted contribution per CONTRIBUTING.md (Assisted-by: ZCode (GLM) trailer on the commit).

@github-actions github-actions Bot added the bug Something isn't working label Sep 5, 2026
SimpleContext.view_for_generation() returns [] by design (stateless
context), so a caller who chains .add(...) and then passes an empty or
whitespace-only action to generate_from_context used to ship an
empty user-role conversation to the model. Some chat models — Granite
4.2 in particular, see issue generative-computing#1587 — spin on an empty prompt and burn
tokens silently, which is hard to diagnose in CI.

Raise ValueError in three concrete chat assembly paths:
  * OpenAIBackend._generate_from_chat_context_standard
  * LiteLLMBackend._generate_from_chat_context_standard
  * OllamaModelBackend.generate_from_chat_context

The check ignores whitespace-only strings but still accepts user
messages that carry images, audio, or documents (vision / RAG paths
must continue to work). Each guard raises a ValueError before any
HTTP or SDK call is issued.

WatsonxAIBackend (mellea/backends/watsonx.py) and LocalHFBackend
(mellea/backends/huggingface.py via mellea/backends/utils.py:to_chat)
also assemble user-role conversations and would benefit from the same
guard, but they are intentionally left untouched to keep this change
focused on the backends named in the issue. Happy to mirror the same
guard block in those two backends in a follow-up if preferred.

SimpleContext.add's docstring is updated to make the stateless
semantics explicit (recorded turns are never forwarded; the action
argument is the only thing that reaches the model) and to call out
which backends now enforce the invariant.

Closes generative-computing#1597

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
Add a TYPE_CHECKING import for ollama so the deferred return annotation
resolves at module level (MyPy name-defined error), and apply ruff format
to satisfy the CI pre-commit style gate. No behavioral change; all 10
guard tests pass.

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
@simonyang08
simonyang08 force-pushed the codex/mellea-1597-empty-user-content-guard branch from 65c1177 to d93723f Compare September 30, 2026 16:02
@simonyang08
simonyang08 marked this pull request as ready for review October 1, 2026 01:18
@simonyang08
simonyang08 requested a review from a team as a code owner October 1, 2026 01:18

@planetf1 planetf1 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 for tracking this down — the root cause write-up (SimpleContext.add() not forwarding to generation) is clear, and the regression test deliberately targeting the guardian false-positive case shows good instinct for where this guard could misfire. Ran the new suite plus test/stdlib/components/test_chat.py: all green, no regressions.

Two things I'd like addressed before merge, both about maintainability rather than correctness of the guard itself:

1. The guard is copy-pasted three times, not shared. The identical ~17-line check (predicate, comment, and raised message) is duplicated verbatim across openai.py, litellm.py, and ollama.py. All three already import from mellea/helpers/openai_compatible_helpers.py, which already hosts message_to_openai_message and messages_to_docs on the same list[Message] input. Could you pull this into a has_user_content(messages: list[Message]) -> bool there and call it from all three sites? Otherwise the Watsonx/HF follow-up you mentioned turns this into five copies, and a future tweak (new attachment type, wording change) has to land in lockstep everywhere.

2. Attachment pass-through is barely tested. The guard treats images, audio, and _docs as "has content" so multimodal/RAG messages don't trip it — but only the images branch is actually tested, and only on OpenAI. audio and documents have no coverage on any backend, and LiteLLM is also missing the whitespace-only case the other two cover. Not asking for nine near-duplicate tests — one audio=-only and one documents=-only case (even just on OpenAI, since the logic is identical across backends) would close the gap.

One scoping note on the PR description: deferring WatsonxAIBackend makes sense, it's already marked deprecated in favour of LiteLLM/OpenAI. LocalHFBackend isn't deprecated and builds its chat messages the same way (view_for_generation() → to_chat_messages()), so the same empty-prompt trap likely reproduces there. Happy for that to be a fast follow-up rather than blocking this PR, but could you open an issue for it so it doesn't fall through?

A couple of small docstring/message nits inline below and noted at the end. Nothing here blocks the fix itself, which is correct and well-placed — once the dedup and the attachment tests are in, this looks good to merge.

On the docstrings (these fall outside the diff's hunks so I can't anchor inline suggestions to them, but worth doing while you're in these files):

  • openai.py — _generate_from_context (the method the Backend ABC actually dispatches to, ~line 904) already has a Raises: section for the ALoraRequirement case. Add: ValueError: If the assembled conversation has no user-role message with non-whitespace content, images, audio, or documents.
  • ollama.py — generate_from_chat_context (~line 1073) already has a Raises: section for the image/audio cases. Same addition there.
  • litellm.py — _generate_from_context (~line 191) has no formal Raises: section yet, just prose ("raises NotImplementedError otherwise"). Worth adding one with both NotImplementedError: If ctx is not a chat context. and the new ValueError line.

Comment thread mellea/backends/openai.py Resolved
Comment thread mellea/backends/litellm.py Resolved
Comment thread mellea/backends/ollama.py Resolved

@planetf1 planetf1 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.

Requesting changes per the two warnings in my review above — the triplicated guard logic should be factored into a shared helper, and the untested attachment pass-through branches (audio, documents) need coverage before this merges. Everything else is non-blocking.

…ontent

Factor the triplicated ~17-line check into
mellea/helpers/openai_compatible_helpers.has_user_content and import it
from all three backends. Add regression coverage for the remaining
attachment pass-through branches: a user message with empty text but
audio, and one with documents, must both reach the model.

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
@simonyang08

Copy link
Copy Markdown
Contributor Author

Both points addressed in 6142775:

1. Shared guard. The triplicated check now lives in mellea/helpers/openai_compatible_helpers.py as has_user_content(messages) (docstring carries the #1597/#1587 rationale, including why whitespace-only text counts as empty and why images/audio/documents count as content), re-exported through mellea.helpers and used by all three backends. The raised message is unchanged.

2. Attachment pass-through coverage. Two new tests pin the previously untested branches: a user message with empty text but an AudioBlock reaches chat.completions.create, and one with documents=[...] (coerced via Message's documents parameter) does too — both assert the guard does not fire and the request is issued.

Verification: guard suite 12/12 (10 existing + 2 new) and the test/stdlib/components/test_chat.py suite you ran both green locally (92 tests total across the two), ruff format + lint clean on the touched files.

@planetf1

planetf1 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Thanks, both blocking points are fixed in 6142775:

  1. Shared guard. has_user_content() in openai_compatible_helpers.py is now the single copy, called from the OpenAI, LiteLLM, and Ollama backends.
  2. Attachment coverage. The new audio and documents tests pass, and each one fails if its branch is removed from the helper, so they pin the right thing.

At 6142775 the guard suite passes 12/12 with all extras installed (LiteLLM tests included) and test_chat.py passes 80/80. I've dismissed my changes-requested review. The inline comments are non-blocking and I'll follow those up separately.

@planetf1
planetf1 dismissed their stale review October 2, 2026 08:29

Both blocking points addressed in 6142775 (shared has_user_content helper, audio and documents test coverage). Details in the comment above.

Comment thread mellea/backends/ollama.py Resolved
Comment thread mellea/backends/openai.py Resolved
@planetf1

planetf1 commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

For info: I've filed #1705 for the same gap in LocalHFBackend, which builds messages through to_chat() and has no guard. It's out of scope here, so no change needed in this PR.

… ValueError

Per review: add Args/Returns sections to has_user_content, switch its
double backticks to single (AGENTS.md rules out double), and document
the empty-user-content ValueError in generate_from_chat_context on
both the ollama and openai backends. Passes audit_coverage.py
--quality --fail-on-quality (0 issues).

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
@simonyang08

Copy link
Copy Markdown
Contributor Author

All three docstring points addressed in cb6a106:

  1. has_user_content now carries Args: / Returns: exactly as your suggestion (and the double backticks are gone), applied verbatim from the suggestion block.
  2. ollama.py generate_from_chat_context gained the ValueError case in its existing Raises: section.
  3. openai.py generate_from_chat_context gained a Raises: section with the same entry.

Verified locally: audit_coverage.py --quality --fail-on-quality reports 0 issues, ruff format + lint clean on the touched files, guard suite 12/12 green.

@planetf1

planetf1 commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Two from the original review that don't have an inline thread to hang off:

  • openai.py — _generate_from_context (~line 904) still only lists the ALoraRequirement case under Raises:. Could you add the ValueError for no user-role content there too?
  • litellm.py — _generate_from_context (~line 178) has no Raises: section at all yet. Needs both NotImplementedError: If ctx is not a chat context. and the new ValueError line.

Also still open: the issue-number drop in the three raised messages (threads above), and the LiteLLM whitespace-only test case.

…uard

- Drop the issue-number citation from the three raised messages (kept
  in the code comments and docstrings, where it belongs).
- openai.py _generate_from_context: add the guard's ValueError to its
  existing Raises section.
- litellm.py _generate_from_context: add a Raises section covering the
  non-chat-context NotImplementedError and the new ValueError.
- tests: add the LiteLLM whitespace-only pass/fail counterpart.

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
@simonyang08

Copy link
Copy Markdown
Contributor Author

All four outstanding items are addressed in 2be9201:

  1. Issue number dropped from the three raised messages (openai / litellm / ollama) — they now end at "...recorded turns are not forwarded to the model." The SimpleContext.add() content is silently discarded from generation — add a safety net #1597 reference stays in the code comments and docstrings, where it belongs.
  2. openai.py _generate_from_context: the guard's ValueError added alongside the existing ALoraRequirement case under Raises:.
  3. litellm.py _generate_from_context: new Raises: section with both NotImplementedError (non-chat context) and the guard's ValueError.
  4. LiteLLM whitespace-only test added (mirrors the OpenAI one; asserts the raise happens before litellm.acompletion is touched).

Verification: guard suite 13/13 green, ruff format + lint clean, audit_coverage.py --quality --fail-on-quality → 0 issues.

One note on this round's CI: the quality job failures are in test/telemetry/test_tracing_streaming.py (4 tracing-span tests) — untouched by this PR's diff and unrelated to the guard work; they look environment/upstream-side rather than something this branch introduced.

@planetf1

planetf1 commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

Thanks, everything from my review is in at 2be9201. I've checked each item, and I'll resolve the three message threads.

Two CI notes before this can merge:

1. The test_tracing_streaming.py failures come from this PR. All four raise the guard's own ValueError (it's in the CI log), and they reproduce locally at 2be9201. _run_streaming() (line 226) adds the user turn to a SimpleContext and then streams an empty assistant message. That's exactly the case the guard exists to catch: "Count to three." never reached the model, so the test was streaming from an empty prompt all along. It's a nice confirmation the guard works, but the fixture needs updating. Switching it to ChatContext gets all nine tests passing locally:

    from mellea.stdlib.context import ChatContext
    ...
    ctx = ChatContext().add(Message(role="user", content="Count to three."))

2. Expect actions-audit / zizmor to go red on the next run. That one isn't yours. It has been failing on every PR since 2026-10-07 and is tracked in #1712, so there's nothing to do about it here.

Once the fixture is updated I'm happy to approve.

…g fixture

_run_streaming added a user turn to a SimpleContext and then streamed an
empty assistant message. SimpleContext discards recorded turns from
view_for_generation, so the assembled conversation had no user-role
content and the issue generative-computing#1597 guard correctly refused the call - the
streamed prompt was empty all along. Switch the fixture to ChatContext,
which keeps the turn, per review.

Assisted-by: ZCode (GLM)
Signed-off-by: simonyang08 <[email protected]>
@simonyang08

Copy link
Copy Markdown
Contributor Author

Fixture updated in 342001d exactly per your suggestion: _run_streaming now builds a ChatContext (with a comment explaining why — SimpleContext drops the turn, the streamed assistant message is empty, and the #1597 guard correctly refused that call). You're right that the four failures were this PR's doing; my earlier read of them as environment-side was wrong.

On zizmor: understood, pre-existing and tracked in #1712 — nothing done here.

One verification caveat, stated for completeness: locally these nine tests skip behind the conftest's ollama capability gate (no server here), so the local run shows 9 skipped. The change is your exact suggested two lines, and the CI quality job runs with ollama available, so its run on this push is the authoritative check. Guard suite still 13/13 green locally.

@planetf1 planetf1 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, the fixture change in 342001d fixes it. I ran test_tracing_streaming.py locally against Ollama and all nine pass, so the four failures are gone. The guard, telemetry and chat suites are green too. Everything from my review is in, so approving. The zizmor failure is the repo-wide one tracked in #1712.

@planetf1
planetf1 added this pull request to the merge queue Oct 14, 2026
@planetf1

Copy link
Copy Markdown
Contributor

looks good so merging

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

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

SimpleContext.add() content is silently discarded from generation — add a safety net

3 participants