Unexpected model replies across the demos: crashes, silently truncated writes, and guardrails that misjudge the answer

Author: WWILLVCreated Sep 20, 2026Updated Sep 24, 2026

Hi, thanks for awesome-llm-apps; it is one of the reference collections we keep coming back to. We have been running several of the demos against a local OpenAI-compatible endpoint and replaying unexpected model replies (empty content, null content, JSON missing a key, tool arguments containing a comma, endpoint errors). We believe we found 13 bugs across five of the demos. Every one is about what the app does when the reply is not what it expects, not about the model's answers and not about code quality, and each is reproducible with the endpoint alone.

  1. rag_failure_diagnostics_clinic stores an empty reply as a diagnosis and prints "Saved report" with exit 0.
  2. rag_failure_diagnostics_clinic indexes the reply envelope with no guard, on a line that sits outside the try that wraps the request.
  3. ai_agent_governance has no error handling around the model call, so any endpoint error (429/400/404/500/disconnect) ends the run with a traceback.
  4. ai_agent_governance raises TypeError on a content: null reply, because the reply is tested with "TOOL:" in llm_response.
  5. ai_agent_governance silently truncates tool arguments that contain a comma and then reports the truncated write as a success.
  6. ai_agent_governance swallows its own approval prompt in headless runs and reports Tool error: with no message.
  7. ai-knowledge-explorer raises IndexError on a reply that is only a code fence (```), on a line outside the try, in all three tools.
  8. ai-knowledge-explorer indexes JSON keys directly, so a reply that omits a key crashes the tool after a successful parse — and the keys the prompt asks for do not match the keys the app stores.
  9. agentic_rag_math_agent's few-shot classifier is dead code, and the guardrail accepts only the exact string yes.
  10. agentic_rag_math_agent's web fallback hides its own failures (no request timeout, no raise_for_status, and a JSONDecodeError that escapes the function).
  11. openai_remote_mcp_bridge turns empty tool arguments into a valid empty call and never validates arguments against the tool's schema.
  12. openai_remote_mcp_bridge's requirements.txt allows mcp 2.x while the code only runs on 1.x.
  13. ai-deep-research-agent indexes the sub-agent's last message with no guard, and turns search failures into "content" for the model.

Bug 1 — an empty reply is stored as a diagnosis, and the run reports success

Where: rag_tutorials/rag_failure_diagnostics_clinic/rag_failure_diagnostics_clinic.py

  • run_once (line 268): the reply is coerced, never validated
  • run_once (lines 271-282): the report is written and "Saved report" is printed unconditionally
python
reply = completion.choices[0].message.content or ""      # line 268
print(reply)
report = {
    "bug_description": bug,
    "model": model_name,
    "assistant_markdown": reply,                          # line 274
}
...
print("\nSaved report to rag_failure_report.json\n")      # line 280

What happens: if the model answers with nothing, the app prints an empty line, writes "assistant_markdown": "", prints "Saved report to rag_failure_report.json" and exits 0. Nothing checks that the diagnosis is non-empty or that it contains the "Primary pattern" section the system prompt mandates. A whitespace-only reply (" ") is truthy and is stored as-is, and finish_reason is never inspected, so a reply truncated by the token limit is stored as if it were complete.

Reproduced: with the endpoint replying "", the bad round and a normal round both exit 0; only the JSON on disk differs — the empty one is a file that downstream tooling would read as a real diagnosis.

Bug 2 — the reply envelope is indexed with no guard, outside the request's try

Where: rag_tutorials/rag_failure_diagnostics_clinic/rag_failure_diagnostics_clinic.py

  • run_once line 268 — outside the try: at line 248 whose except Exception is at lines 264-266
python
    completion = client.chat.completions.create(...)     # line 249, guarded
except Exception as exc:
    print(f"Error while calling the model: {exc}")
    return

reply = completion.choices[0].message.content or ""      # line 268, not guarded

What happens: a 200 response that carries no choices raises IndexError (and choices: null raises TypeError) in main(), which has no handler — the process dies with a traceback and exit 1. The official API does not return such bodies, but this app deliberately supports any OPENAI_BASE_URL (line 177), and gateways, proxies and mocks do.

Bug 3 — any endpoint error ends the run with a traceback

Where: advanced_ai_agents/single_agent_apps/ai_agent_governance/ai_agent_governance.py

  • GovernedAgent.run lines 462-469: the model call, with no try
  • main line 604: result = agent.run(request), also unguarded
python
response = self.client.chat.completions.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_request}
    ],
    max_tokens=500
)

What happens: a 429, 400, 500, a timeout or a dropped connection propagates out of main() as a traceback (exit 1). The only try/except in main is at lines 567-579, and it wraps the static policy demo, not the agent. The declared model, gpt-4, is hardcoded, so a 404 is a realistic trigger as well.

Reproduced: six distinct endpoint faults (400 context-length, 429, 500, connection drop, stall, generic error) — all six end in a traceback with exit 1, while the matching normal round exits 0.

Bug 4 — a content: null reply raises TypeError

Where: advanced_ai_agents/single_agent_apps/ai_agent_governance/ai_agent_governance.py

  • GovernedAgent.run line 471, used at line 475
python
llm_response = response.choices[0].message.content        # line 471 - no `or ""`
print(f"\n Agent response: {llm_response}")

if "TOOL:" in llm_response:                               # line 475

What happens: replies whose content is null (tool-call turns, refusals, several providers) print None and then raise TypeError: argument of type 'NoneType' is not iterable — uncaught, because the tool-call try only starts at line 501. Note the sibling demo above does use or ""; here the guard is simply missing.

Bug 5 — tool arguments containing a comma are silently truncated, and the truncated write is reported as success

Where: advanced_ai_agents/single_agent_apps/ai_agent_governance/ai_agent_governance.py

  • _execute_tool_call lines 493-496: the argument parser
  • write_file line 406: the success message
python
for arg in args_str.split(", "):                          # line 493
    if "=" in arg:                                        # line 494 - fragments without "=" are dropped
        key, value = arg.split("=", 1)
        kwargs[key.strip()] = value.strip().strip('"\'')

What happens: for a reply of

TOOL: write_file(path="/workspace/report.md", content="Total, by region")

the split yields ['path="/workspace/report.md"', 'content="Total', 'by region"']; the last fragment has no =, so it is discarded and content becomes Total. The file is written with the truncated text and the app reports Successfully wrote 5 characters to /workspace/report.md. Silent data loss, no error, no warning.

Two smaller issues in the same parser, same lines:

  • lines 475-477: only the first TOOL: in a reply is executed, and .split("\n")[0] keeps only the first line of a multi-line call — anything else in the reply is ignored without a word;
  • line 496: .strip('"\'') also removes legitimate leading/trailing spaces and any stray quotes from the value.

Bug 6 — the approval prompt is swallowed in headless runs

Where: advanced_ai_agents/single_agent_apps/ai_agent_governance/ai_agent_governance.py

  • get_human_approval line 345, called from the policy wrapper at line 375
  • the wrapper is invoked inside _execute_tool_call's try (line 501), whose handler is at lines 506-507
python
response = input("   Approve? [y/N]: ").strip().lower()   # line 345
...
    result = self.tools[tool_name](**kwargs)              # line 502
    return f"Tool result: {result}"
except PolicyViolation as e:
    return str(e)
except Exception as e:
    return f"Tool error: {e}"                             # line 507

What happens: with no stdin (server, cron, container), input() raises EOFError, which is caught at line 507. Since str(EOFError()) is empty, the user sees:

Tool result: Tool error:

"nobody was there to approve" is reported as "the tool is broken", the run continues, and the denial is never recorded — the audit entry written at line 257 only says REQUIRE_APPROVAL. This is reachable whenever the model volunteers TOOL: execute_shell(...) or TOOL: delete_file(...), i.e. it is model-controlled.

Bug 7 — a reply that is only a code fence raises IndexError, outside the try

Where: generative_ui_agents/ai-knowledge-explorer/agent/src/tools.py

  • extract_knowledge lines 146-147 (the same two lines appear at 267-268 in find_connections and 393-394 in expand_node)
  • the try: that guards parsing starts at line 149, i.e. after the split
python
if content.startswith("```"):
    content = content.split("\n", 1)[1].rsplit("```", 1)[0].strip()

try:
    data = json.loads(content)
except json.JSONDecodeError:

What happens: a reply of exactly ``` or ```json has no newline, so split("\n", 1) returns a single-element list and [1] raises IndexError: list index out of range. The try below only covers json.loads, so the exception leaves the tool. This is precisely the "the model wrapped its answer in a fence and nothing else" case.

Bug 8 — missing JSON keys crash the tool after a successful parse, and the prompt's key names disagree with the app's

Where: generative_ui_agents/ai-knowledge-explorer/agent/src/tools.py

  • extract_knowledge lines 163-164 and 181-182
  • find_connections lines 284-285
  • expand_node lines 419 and 434-435
  • the prompt's requested keys: lines 93-94 (and 128); the app's own Edge schema: agent/src/state.py; the shape sent back to the model: line 250
python
for node_data in data.get("nodes", []):
    label = node_data["label"]                                          # 164
...
for edge_data in data.get("edges", []):
    src_id = label_to_id.get(edge_data["source_label"].lower())         # 181
    tgt_id = label_to_id.get(edge_data["target_label"].lower())         # 182

What happens: the only handler in each function is except json.JSONDecodeError (lines 152, 273, 399). So a reply that drops a key, returns a top-level array (AttributeError: 'list' object has no attribute 'get') or {"nodes": null} (TypeError) leaves the tool as an exception rather than the friendly "Failed to parse extraction results. Try again." message that the JSON-decode branch produces.

The underlying inconsistency is that the prompt asks the model for source_label / target_label while the app's own state schema and the "EXISTING EDGES" block it feeds back to the model use source / target:

python
EXISTING EDGES (don't duplicate):
{json.dumps([(e['source'], e['target'], e['label']) for e in existing_edges])}   # line 250

A model that mirrors the shape it was shown — a reasonable behaviour — hits line 181 with a KeyError. Two shapes for the same data is the thing worth removing here.

Related, same file: the upload is deleted at line 39 before extraction is attempted, so any of the failures above also loses the source text; the display name is truncated by split("-", 1)[-1] at line 36 (quarterly-report.pdf becomes report.pdf); edge_data.get("weight", 1) (lines 188-189) stores whatever type the model sent ("3" stays a string); and a node whose label collides case-insensitively is dropped at line 165 together with its edges at line 183, so a reply can produce "0 nodes, 0 relationships" with no error at all.

Bug 9 — the few-shot classifier is dead code, and the guardrail accepts only the exact string yes

Where: rag_tutorials/agentic_rag_math_agent/rag/guardrails.py

  • lines 31-32: a zero-shot classifier is built, and a 38-example ChainOfThought is built next to it
  • line 76: the zero-shot one is the only one ever used
  • line 78 (and 98): the verdict comparison
python
self.classifier = dspy.Predict(ClassifyMath)                       # line 31 - this is what runs
self.validate_question = dspy.ChainOfThought(                      # line 32 - 38 worked examples
    ClassifyMath, examples=[...])                                  #        never referenced again
...
response = self.classifier(question=question)                      # line 76
...
return response.verdict.lower().strip() == "yes"                   # line 78

What happens: validate_question is defined and never called anywhere in the repository, so the examples meant to anchor the decision never reach the model. And because the verdict is compared with ==, only the bare word is accepted: "Yes.", "**Yes**", "Yes, this is a math question." and an empty verdict are all read as "not a math question", and rag/query_router.py lines 95-96 return the canned refusal — no retry, no log of what the model actually said. The reverse is also true: any casing or whitespace variant of yes is accepted, so the check is at once too strict and too loose.

Bug 10 — the web fallback hides its own failures

Where: rag_tutorials/agentic_rag_math_agent/rag/query_router.py

  • query_web lines 61-63, called at lines 135 and 145 — both outside the try at lines 101-131
python
response = requests.post(url, json=payload, headers=headers)      # line 61 - no timeout
data = response.json()                                            # line 62
return data.get("answer", "No answer found.")                     # line 63

What happens:

  • there is no timeout=, so a stalled connection blocks for as long as the socket lives;
  • there is no raise_for_status(), so a 401 or 429 returns "No answer found.", which is then handed to the model as the "Web Content" it should explain, while line 139 still prints Answer Source: Web;
  • an explicit "answer": null slips past .get's default and renders the literal text None into the prompt (lines 74-76);
  • a non-JSON body raises requests.exceptions.JSONDecodeError, and since the two call sites are outside the try, the exception escapes answer_math_question — in the Streamlit page (app/streamlit.py line 35) that surfaces as a traceback in the browser.

Related, same app: the output guardrail's retry (lines 142-148) is not re-validated, so an answer that failed the check is returned anyway; and the benchmark scores answers with a substring test (app/benchmark.py line 28, expected.lower() in response.lower()), so a gold answer of 12 counts as correct inside 112 or 0.12.

Bug 11 — empty tool arguments become a valid empty call, and arguments are never validated against the schema

Where: mcp_ai_agents/openai_remote_mcp_bridge/openai_remote_mcp_bridge.py

  • line 180: the empty string is replaced
  • line 198: the call is made
  • lines 70-78: the schema is used only to build the OpenAI parameters
python
raw_arguments = tool_call.function.arguments or "{}"              # line 180
...
result = await session.call_tool(name, arguments)                 # line 198

What happens: an empty arguments string is silently normalised into {}, which passes the isinstance(arguments, dict) check and is forwarded to the MCP server without ever being checked against the tool's own inputSchema. Missing required arguments, a typo'd key ({"qery": "x"}), null values and extra keys all reach the server unchecked and only fail if that server enforces its own schema — against a permissive server this is a silent wrong invocation, not an error.

Two smaller items in the same file: a duplicated tool_call.id in one reply (line 211) makes the next request fail with a 400, and messages.append(message.model_dump(exclude_none=True)) (line 170) replays every non-null field the SDK parsed, including ones the API rejects on input. There is also no timeout on the client (line 159, SDK default 600 s) and the tool-discovery loop follows nextCursor with no overall bound (lines 46-52), so a server that always returns a cursor never returns.

Bug 12 — requirements.txt allows an mcp major that the code cannot run

Where: mcp_ai_agents/openai_remote_mcp_bridge/requirements.txt, line 2 (mcp>=1.28.1)

What happens: installing the declared range today resolves to mcp 2.x, where streamable_http_client(...) yields two values instead of three and FastMCP was renamed (mcp/server/fastmcp.py raises ModuleNotFoundError with the migration note). The bridge dies immediately:

[connect] http://127.0.0.1:8760/mcp
Bridge failed: not enough values to unpack (expected 3, got 2)

Pinning mcp<2 is enough to restore it, so this is only a version-range issue — but a fresh clone is broken out of the box.

Bug 13 — the sub-agent's last message is indexed with no guard, and search failures become "content"

Where: generative_ui_agents/ai-deep-research-agent/agent/tools.py

  • line 156: the summary is taken from the last message
  • lines 35-62: _do_internet_search converts every failure into data
  • line 165: the source status is hardcoded
python
result = research_agent.invoke({"messages": [HumanMessage(content=query)]})
summary = result["messages"][-1].content                          # line 156

What happens: an empty result raises IndexError/KeyError inside the tool, and when the last message is a tool-call-only turn the summary is a blank string — the main agent then narrates around the empty "findings". Meanwhile a failed search returns [{"error": str(e)}] as an ordinary value, which is handed to the sub-agent as the tool observation, and the sources entries carry "status": "found" unconditionally, so the UI cannot show that a search failed. Also: the TAVILY_API_KEY check at lines 31-33 raises before the try at line 35, so a configuration problem becomes an exception inside the tool node rather than a message; and the default model at line 128 ("gpt-5.5") does not exist, so an unset OPENAI_MODEL fails at the first call.


None of this is meant as criticism, the demos are clear and well written, and several of them handle exactly these cases correctly (the diagnostics app guards its request, the MCP bridge validates its JSON arguments and reports them to the model). We are happy to send PRs for whichever items you consider worth fixing, in whatever order suits you.

Source: Shubhamsaboo/awesome-llm-apps