Your LLM will return broken JSON, made-up IDs and quotes nobody ever said. The real question is what your code does next.
agentdream is an open source tool that runs "dreams" over an agent's memory: it reads your memory notes and recent session transcripts, then proposes merges, stale-value replacements and corrections, each citing transcript lines. When it uses a model to do that, it treats every byte the model sends back as untrusted input. This post walks through how, using the actual code in src/agentdream/engine/llm.py.
The analogy: a customs desk
Think of the model as a traveler arriving at a border. The traveler may be honest. They may also carry a bag that is half zipped, a passport with a typo, or a story that does not match the paperwork. A good customs officer does not shout "liar" and send everyone home. They fix what can be fixed (zip the bag), check what can be checked (does this passport exist in the system?), and turn back only what fails the check. If the desk itself goes down, there is a manual backup process.
agentdream has all four of those steps: repair, resolve, verify, fall back.
Step 1: repair the bag (tolerant JSON parsing)
The system prompt asks for one thing: "Output ONLY a JSON object, no prose". Models still wrap it in code fences, add trailing commas, use curly quotes, or get cut off mid-object. parse_json_loose builds a list of candidate strings and tries each one:
candidates = [] t = text.strip() candidates.append(t) fenced = _strip_fences(t).strip() candidates.append(fenced) bal = _balanced(fenced) if bal: candidates.append(bal) for c in list(candidates): fixed = re.sub(r",\s*([}\]])", r"\1", c) fixed = fixed.replace("“", '"').replace("”", '"').replace("‘", "'").replace("’", "'") candidates.append(fixed) _balanced finds the first { or [, walks the string while tracking quotes and escapes, and returns the balanced span. If the output was truncated, it closes whatever is still open:
# unterminated: close what is open (truncated output) return text[start:] + "".join(reversed(stack)) if stack and not in_str else None If json.loads fails on every candidate, there is one last try: swap true/false/null for their Python names and run ast.literal_eval, which catches single-quoted, Python-style dicts that small models like to emit. Only a dict or list result is accepted.
After parsing, split_operations looks for the list under operations, ops or changes, accepts a single bare operation object, and drops non-object items. A list of pure junk like [1, 2, 3] raises an error rather than silently passing.
Step 2: check the passport (entry ID resolution)
Every operation names targets, the memory entries it wants to change. This is where models are most creative. The docstring for normalize_entry_id shows real examples:
def normalize_entry_id(raw: Any) -> str: """Peel what models wrap around an entry id: whitespace, repeated ``id=`` / ``id:`` prefixes, quotes and backticks, brackets, trailing commas. ``"id='id='MEMORY.md#6'"`` -> ``MEMORY.md#6``; ``"[MEMORY.md#6] The API..."`` -> ``MEMORY.md#6``. Repeats until nothing changes.""" There is a nice design detail upstream of this. The prompt used to render entries as id='...', and a small model (qwen2.5:1.5b, per the comment in render_memory) echoed it back verbatim. So the prompt now shows [MEMORY.md#1] text, a format "even small models copy back correctly". Fix the input format first, then normalize what still slips through.
resolve_targets then tries, in order: an exact match, a match after normalizing, a case-insensitive match, and a match by file basename (project.md#1 to notes/project.md#1). The last two count only when exactly one known ID matches:
for table, key in ((self.folded, n.casefold()), (self.base, n.replace("\\", "/").casefold())): hits = table.get(key, []) if len(hits) == 1: return hits[0] if len(hits) > 1: return None That len(hits) > 1 branch matters. An ambiguous guess is treated the same as no guess. The tool never picks one of two candidates on your behalf.
If any target cannot be resolved, the whole operation is dropped with a warning. The edge-case table in docs/EDGE_CASES.md lists one hostile version of this: "A model naming '../../etc/passwd' as a target id: op dropped as unknown id, nothing written outside."
Step 3: check the story (evidence and rules)
convert_operations applies a series of rules to each operation that survives resolution. Here are the ones worth copying into your own agent code.
Each phase gets an allow-list of operation types.
allowed = {"consolidate": {"merge", "replace", "contradiction"}, "verify": {"correct", "contradiction"}, "insights": {"insight", "contradiction"}}[phase] A model in the consolidate phase cannot sneak in a correct.
Citations must point at a real transcript line. validate_evidence looks up each citation in an index built from the loaded transcripts. Unknown citations are counted as bad and discarded. If the citation is real but the quote does not appear in that message (after whitespace and case folding), the quote is replaced with the real message text:
if quote and _norm_ws(quote.rstrip(".…")) in _norm_ws(msg.content): out.append(Evidence.from_message(msg, quote, str(it.get("stance") or "supports"))) else: bad += 1 out.append(Evidence.from_message(msg, msg.content, "supports")) So the report can never show a quote the model invented.
No evidence means a weaker operation, or none. A correct without verifiable evidence is downgraded to a flag:
if not evidence: ctx.warn(f"{phase}{where}: LLM correction #{i} had no verifiable evidence; downgraded to a flag") typ, kind, new_content = "contradiction", "evidence", None An insight without evidence is dropped entirely.
The model can only edit what it saw. With large stores, agentdream splits input into token-budgeted chunks. If an operation targets entries not shown in that chunk, it is dropped. If it would rewrite an entry it only saw an excerpt of, it becomes a flag instead.
Field types are coerced, not trusted. confidence is clamped to 0 to 1 and defaults to 0.6 if it is not a number. A new_content that comes back as a dict is unwrapped from content or text, and anything else non-textual is ignored with a warning.
Step 4: the manual backup (retries and fallback)
Transient failures get bounded retries. is_retryable returns true for timeouts and for backend errors flagged retryable, which its docstring describes as "HTTP 408 / 429 / 5xx". Retry-After is honored but capped:
def retry_delay(exc: BaseException, attempt: int, backoff: float, max_wait: float) -> float: after = getattr(exc, "retry_after", None) wait = float(after) if isinstance(after, (int, float)) and after >= 0 else backoff * (2 ** attempt) return max(0.0, min(float(max_wait), wait)) Bad output and auth errors are not retried. Asking again rarely fixes a broken prompt.
When every model call in a phase fails, engine/__init__.py logs a warning and runs the rule-based engine instead:
except Exception as exc: # backend down, bad JSON, ... -> deterministic fallback ctx.warn(f"{phase}: {backend.describe()} failed ({type(exc).__name__}: {exc}); " "fell back to deterministic heuristics") HEURISTICS[phase](ctx) If only some chunks failed, the result is marked partial and the heuristics fill in the rest. The dream completes either way, and the report says what happened.
How it is tested
None of this relies on a real model misbehaving on cue. tests/edge/test_model_misbehavior.py uses a fake backend that returns exactly the garbage you want to test. One parametrized test feeds nine bad outputs, including prose, an empty string, a half-written operations array, and "[" * 50_000:
@pytest.mark.parametrize("output", [ "I'm sorry, I can't help with that.", "", " \n ", "{\"operations\": [{\"type\": \"merge\", \"targets\": [}", "``` json\nnot json\n ```", "[" * 50_000, "null", "42", "\"just a string\"", ]) def test_junk_or_empty_output_falls_back(tmp_path, output, sleeps): It asserts the job completes, that all three phases warn about the fallback, and that the deterministic correction still appears. A sleeps fixture records back-off waits instead of sleeping, so it can also assert that parse failures are not retried.
You can try the safe path yourself with no model at all:
pip install agentdream git clone https://github.com/mvplab-ai/agentdream && cd agentdream agentdream dream --memory examples/memory --sessions examples/sessions Then rerun with --backend claude-cli or --backend ollama --model llama3.1:8b and read the warnings section of the report to see which proposals were dropped or downgraded.
And remember that the validation layer is the second line of defense. The first is that a dream never touches your store: it writes a staged copy, and nothing is applied until you agentdream accept.
Takeaways
- Parse model JSON leniently (fences, trailing commas, truncation), but only accept real objects and lists.
- Resolve IDs the model names against what actually exists, and refuse ambiguous matches.
- Make every citation point at a real source line, and replace quotes that don't match.
- Downgrade claims that lack evidence instead of applying them.
- Retry only transient errors, cap
Retry-After, and keep a non-LLM fallback so the job still finishes. - Test with a fake backend that returns the exact garbage you fear.
