Skip to content

LLM Quality and Safety

Sergey Gerasimov edited this page Oct 23, 2026 · 2 revisions

LLM Quality & Safety

Last verified: 2026-10-23 Applies to: DerivLab 1.2.0 Owner: @SergeyGer

DerivLab is local-first. LLM output is an optional narrative and decision-assist layer; it is never an unquestioned source of truth. A response either passes an explicit contract or is replaced by a deterministic local result.

The detailed repo version is docs/LLM-QUALITY.md.


TL;DR

  • Every artifact is accepted or falls back; there is no fake numeric “quality score”.
  • Transport errors, empty responses, invalid JSON, missing sections, too few news items, and invalid agent mandates are handled without raising into the UI.
  • Agent decisions are clamped to allowed strategies and numeric ranges.
  • The critic/news outputs are not fed back into the simulation.
  • Factual truth is not automatically verified; that residual risk is documented and mitigated by grounding prompts, disclaimers, and human review.
  • The local deterministic path is always available and remains reproducible.

Acceptance pipeline

flowchart LR
    A[Configured LLM] --> B{Transport OK?}
    B -->|no| L[Local deterministic output + error]
    B -->|yes| C{Parse + contract OK?}
    C -->|no| L
    C -->|yes| D[Accepted + provenance]
    D --> E[Report / news / optional mandate]
    L --> E
    E --> F[Model Stack: source, model, latency, error]
Loading

Quality gates

Gate Automated? Pass condition Code
Configuration ✅ Provider/base URL/key/non-local models; otherwise no network LLMSettings.enabled in llm.py
Transport ✅ HTTP 2xx, non-empty text, timeout respected LLMClient.generate
Result shape ✅ ok, model, provider, source, latency_ms, error LLMResult
JSON extraction ✅ Fenced/chatty JSON extracted; invalid → None parsing.py
Decision schema ✅ Whitelisted strategy/tenor, bounded numbers, per-agent fallback normalize_agent_decision
Report contract ✅ All three required headings present validate_report
News contract ✅ Array, 3–5 usable items, normalized fields generate_news, _normalize_news_item
Grounding ⚠️ partial Prompt restricts the model to the payload; no retrieval/web system prompts, payload builder
Factual truth ❌ Not automatically proven residual risk
Prose quality ❌ Human rubric reviewer

There is deliberately no LLM-as-judge in CI: it would add cost, non-determinism, and another failure mode without proving truth.


Report contract

The prompt requires exactly these three sections, in order:

### 📊 Performance Summary & Comparative Analysis
### 🔍 Tactical Critique of User's Performance
### 💡 Elite Quant Recommendation

generate_report returns the deterministic local_report if:

  • no client is enabled;
  • the call fails or is empty;
  • validate_report cannot find all three headings.

The fallback carries source="local" and an error message. An accepted LLM report carries the actual model, provider, and latency.

Important limitation: validate_report is a presence-based structural guard, not a fact-checker. It does not prove that every number in the prose is correct. The prompt says “use only the supplied numbers”; the report is never consumed by the backtest or the user portfolio. The UI shows the model and fallback status.

Implementation: commentary.py.


NewsWire contract

generate_news accepts a JSON array with 3–5 usable items. Each item is normalized:

  • tag: uppercase, max 24 characters;
  • headline: required, max 120 characters;
  • detail: required, max 260 characters;
  • severity: high / medium / low; unknown → medium.

A non-array, malformed JSON, or fewer than three valid items triggers the local four-item wire. The Model Stack tab shows the reason.


Agent decisions: bounded autonomy

LLM mandates are opt-in (default: local policy). One JSON call covers all three personas. normalize_agent_decision applies:

Field Rule
strategy_key Must be one of the five supported strategies; otherwise policy fallback
tenor_days 30 / 60 / 90; otherwise policy
strike_offset_pct Clamped −25…25; 0 for basis;
wing_width_pct Clamped 1…10
basis_pct Clamped 0…15
rationale Policy rationale if missing; max 320 characters

Missing agents fall back individually. The LLM cannot introduce a new strategy, asset, leverage, or unbounded parameter. These bounds make malformed output safe to simulate; they do not claim the mandate is profitable.

Implementation: personas.py.


Grounding and non-interference

  • build_market_context uses only bars before the scenario.
  • The critic/news payload contains actual NAV, return, drawdown, Sharpe, premium, leaderboard, and extract_critical_triggers.
  • Prompts say: use only supplied numbers and do not invent prices, dates, or trades. The NewsWire prompt explicitly forbids investment advice; the UI adds the educational disclaimer to every report.
  • The critic/news never feed back into the backtest, user portfolio, or scoring.
  • Optional LLM mandates affect only simulated agents, after clamps/fallbacks.
  • There is no broker connection and no live order.

A hallucination cannot silently rewrite the simulation; it can still misinterpret a supplied metric. That is why the report is explicitly commentary, not advice.


Runtime observability

ArenaResult.llm_status and the Model Stack tab expose:

  • provider and model;
  • source (llm / local);
  • latency;
  • error (timeout, malformed JSON, missing sections, provider error);
  • the decision-call result.

When a fallback occurs, run_arena updates the visible model stack to the local model and provider. The UI cannot claim “gpt-4.1” was the active critic if the accepted output came from derivlab-local-critic-v1.


Automated quality tests

The full suite is 248 tests; the 26 agent tests are offline and mocked:

pytest -q tests/test_agents.py
pytest -q
Test Protects
test_openai_client_parses_response Response normalization
test_openai_client_retries_max_completion_tokens API parameter compatibility
test_openai_client_failure_falls_back Network failure → local
test_anthropic_client_parses_response Anthropic response shape
test_json_parsing_helpers Fenced/chatty JSON
test_normalize_agent_decision_clamps Strategy/parameter bounds
test_decide_agents_llm_path Valid JSON → mandates
test_decide_agents_invalid_json_falls_back Invalid JSON → policies
test_generate_report_llm_and_fallback Missing headings → local critic
test_news_invalid_json_falls_back Invalid wire → local news
test_arena_llm_path Full mocked LLM path + model stack
test_arena_local_run Deterministic offline Arena

tests/conftest.py forces the local provider, so a developer's .env key cannot cause network traffic or cost in tests.


Human review rubric

Automated checks cannot judge usefulness. Reviewers check:

  1. numeric accuracy against the payload;
  2. causal specificity (names the actual breach/assignment/IV spike);
  3. actionability of the recommendation;
  4. no invented prices, dates, trades, or model names;
  5. exactly the three sections, no raw HTML, no investment advice.

The local report is the reference output for the same payload.


Residual risks

Risk Mitigation Remaining exposure
Hallucinated metric Grounding prompt, visible payload, local fallback No automatic numeric proof
Missing section validate_report → local critic Extra prose can still be shown
Invalid JSON Parser + fallback A valid but poor decision can pass
Out-of-range mandate Clamps / policy fallback Legal but unprofitable choice
Provider outage Local fallback No LLM prose for that cycle
Prompt injection No free-text retrieval; payload is generated Low, not zero
Over-trust Disclaimer, no execution, human review User judgement

No LLM output is investment advice. The simulation cannot place live orders.


Code map

Related: AI Agents · AI Model Guide · Compatibility & Versions · Documentation feedback

Clone this wiki locally