# Stop Guessing What Your AI Meant: Why Loose Output Parsing Is a Security Nightmare for AI Agents

> Source: <https://pub.towardsai.net/stop-guessing-what-your-ai-meant-why-loose-output-parsing-is-a-security-nightmare-for-ai-agents-22be3657d77e?source=rss----98111c9905da---4>
> Published: 2026-12-05 10:45:57+00:00

**Recommendation:** Reject any planner output that does not strictly match your schema instead of falling back to regex or newline splitting, and require each step to declare its depends_on indices so unverified actions cannot execute.
More in the playbook "Securing agents and AI tools": <https://wpnews.pro/playbooks/agent-security>

When developers first build an AI agent, they quickly run into a frustrating reality: Large Language Models (LLMs) are inconsistent. Ask one model for a list of steps, and it gives you clean JSON. Ask another model or even the same model with a slightly different prompt and it wraps the answer in conversational filler, markdown headers, or numbered bullet points.

To make their pipelines resilient, developers often write “smart” parsers. If JSON parsing fails, the code falls back to regex matching. If regex fails, it splits the text by newlines or semicolons.

In a low-stakes chatbot, that kind of forgiving parsing is harmless. In a high-stakes domain like **banking, healthcare, or cloud infrastructure**, it is a critical *** security vulnerability***. When a parser guesses what an LLM meant, ordinary sentences can easily be mistaken for executable commands.

**The Anatomy of a Parsing Disaster: A Banking Example**

“I lost my wallet. Please freeze my debit card.”

Behind the scenes, your agent uses a **Planner** (an LLM) to decide which internal APIs to call, and an **Executor** (your backend code) to run them.

Ideally, the agent should follow a strict sequence:

Now, suppose your planner model ignores formatting instructions and replies with a helpful, conversational explanation instead of a structured plan:

“Before I block your card, I need to make sure you are who you say you are. First, I will verify your identity. Then, I will check your account status. Finally, I will block the card.”

If your backend uses a loose text parser that splits sentences and looks for action keywords, a catastrophe unfolds:

An unverified user just altered the state of a bank account because the parser treated a cautionary sentence as an executable step.

**The Anti-Pattern: “Best-Effort” Fallback Parsing**

Imagine you are building a customer-support banking agent. A user messages the bot:

“Before I block your card, I need to make sure you are who you say you are. First, I will verify your identity. Then, I will check your account status. Finally, I will block the card.”Behind the scenes, your agent uses a **Planner** (an LLM) to decide which internal APIs to call, and an **Executor** (your backend code) to run them.

Consider this common Python pattern used to extract steps from an LLM’s response:

``` python
def parse_steps(plan_text):  if isinstance(plan_text, list):    return [str(x).strip() for x in plan_text if str(x).strip()]  text = str(plan_text)  lines = text.splitlines()  steps = []  # 1. Regex parsing for numbered lists or arrows  for line in lines:    line = line.strip()    match = re.match(r"^\d+[\).:-]\s*(.+)$", line)    if match:      steps.append(match.group(1).strip())    elif "→" in line:      steps.extend([s.strip() for s in line.split("→") if s.strip()])  # 2. Try JSON only if regex failed  if not steps:    try:      data = json.loads(text)      steps = data.get("steps", [])    except Exception:      # 3. THE DANGER ZONE: Fallback text splitting      steps = [s.strip() for s in re.split(r"[;\n]", text) if s.strip()][:8]  return steps
```

This function exhibits three classic security flaws categorized under **Insecure Output Handling** in the [OWASP Top 10 for LLM Applications](https://owasp.org/www-project-top-10-for-large-language-model-applications/):

**Five Rules for Safe Agent Output Handling**

To prevent conversational chatter or adversarial prompts from triggering real-world actions, your parser must **fail closed**. If the output does not strictly match expectations, reject it immediately.

**Designing a Dependency-Aware Schema**

Instead of a flat list of strings, a banking planner should output a structured, dependency-aware execution graph:

```
{  "steps": [    {      "tool": "verify_identity",      "depends_on": []    },    {      "tool": "check_account_status",      "depends_on": [0]    },    {      "tool": "block_card",      "depends_on": [1]    }  ]}
```

Why is this structure so much safer?

**Implementing a Strict Validator in Python**

Here is how you replace the fragile regex parser with a strict, fail-closed validator:

``` python
import jsonALLOWED_TOOLS = {"verify_identity", "check_account_status", "block_card"}def parse_steps(plan_text: str) -> list[dict]:  # 1. Require strict JSON (no regex or text fallbacks)  try:    data = json.loads(plan_text)  except json.JSONDecodeError as e:    raise ValueError(f"Rejected malformed JSON from planner: {e}")  # 2. Validate top-level structure  if not isinstance(data, dict) or "steps" not in data:    raise ValueError("Missing required 'steps' object in planner output.")  steps = data["steps"]  if not isinstance(steps, list) or not steps:    raise ValueError("'steps' must be a non-empty list.")  validated_steps = []  for idx, step in enumerate(steps):    if not isinstance(step, dict):      raise ValueError(f"Step {idx} must be a JSON object.")    # 3. Reject unknown fields    allowed_keys = {"tool", "arguments", "depends_on"}    if not set(step.keys()).issubset(allowed_keys):      raise ValueError(f"Step {idx} contains unknown fields.")    tool = step.get("tool")    depends_on = step.get("depends_on", [])    # 4. Validate tool name against strict allowlist    if tool not in ALLOWED_TOOLS:      raise ValueError(f"Rejected unknown or unauthorized tool: '{tool}'")    # 5. Validate dependency indices (prevent forward/circular dependencies)    if not isinstance(depends_on, list) or not all(        isinstance(d, int) and 0 <= d < idx for d in depends_on    ):      raise ValueError(f"Invalid 'depends_on' indices in step {idx}.")    validated_steps.append({        "tool": tool,        "arguments": step.get("arguments", {}),        "depends_on": depends_on,    })  return validated_steps
```

**The Takeaway**

When building AI agents, **robustness does not mean accepting messy data-it means safely rejecting bad data.** Different models will always produce formatting quirks, and prompt injections will always attempt to blur the line between conversation and commands.

Stop writing regex fallbacks to guess what your LLM meant. Lock down your schema, validate every tool and dependency, and when in doubt, fail closed.

[Stop Guessing What Your AI Meant: Why Loose Output Parsing Is a Security Nightmare for AI Agents](https://pub.towardsai.net/stop-guessing-what-your-ai-meant-why-loose-output-parsing-is-a-security-nightmare-for-ai-agents-22be3657d77e) was originally published in [Towards AI](https://pub.towardsai.net) on Medium, where people are continuing the conversation by highlighting and responding to this story.
