MTM Resource Sweep · Long-Horizon Agent Pipelines

Eight pipelines that turn an LLM from a demo into a system you can actually ship.

One report. Eight tabs. Each one names the problem, the 2026 tools, a working end-to-end pipeline, prompts you can copy, and the numbers that prove it works. A benchmarking segment at the end sorts what to build first, second, and not at all.

Date 2026-08-10 Sources swept 56 web queries · 30+ first-party docs · 12 papers Voice article-writer · kai persona Format self-contained HTML · no external deps

Tab 01 · End-to-End Agent Evaluation & Trajectory Benchmarking

Final-answer scoring marks a failing agent green. The answer was right. The path was wrong — 20 steps, two policy violations, an exfiltration. Trajectory eval closes that gap.

Why it matters

A correct answer reached in 20 steps with two policy-violating intermediate calls is a failing trajectory. Production agents need four layers: unit, trajectory, outcome, online. Anything less accumulates technical debt in the form of undetected regressions.

Latest 2026 landscape

LangSmith agentevals
MIT SDK · closed platform
4 trajectory-match modes (strict / unordered / subset / superset)
Arize Phoenix
ELv2 · OTel-native
~9.9k★ · OpenInference auto-instrumentation across 14+ frameworks
Braintrust
Closed · $249/mo Pro
$80M Series B Feb 2026 · best dataset-diff UX
DeepEval
Apache 2.0 · pytest-style
~16.3k★ · 50+ metrics incl. G-Eval, task completion, faithfulness
Confident AI
Closed · $200/mo Starter
CI/CD report, release gates, tool-call regression
Future AGI
Apache 2.0 · self-hostable
Trajectory-first, framework-neutral, span-attached evals + gateway
AgentAssay
arXiv:2603.02601
78–100% cost cut via SPRT · 86% detection where binary has 0%
Langfuse v4
MIT (was AGPL)
Observations-first data model · ClickHouse acquired Jan 2026

Benchmarks worth tracking: tau-bench, tau2-bench, SWE-Bench, AgentBench, LongMemEval, LoCoMo.

End-to-end pipeline demo

golden-50.yaml → OpenTelemetry spans (Phoenix) → trajectory diff (agentevals strict+unordered) → pytest gate (DeepEval task_completion ≥ 0.95) → PR block on threshold fail → nightly LLM-judge (Braintrust) → shadow 5% traffic → canary 50% with error budget → AgentAssay SPRT sampling in production → failed traces back to golden

Prompts that work

# 1) Strict trajectory match (reference) — bloqueia qualquer desvio de ordem/argumento
from agentevals import create_trajectory_match_evaluator
strict = create_trajectory_match_evaluator(mode="strict")
strict(inputs=case.input, outputs=agent_run, reference_trajectory=case.golden)

# 2) Tool-selection LLM judge (reference-free) — quando não dá pra manter golden
judge_prompt = """
You are grading an agent's tool selection.
For each tool call, decide:
  (a) Was the right tool picked for the user's goal?
  (b) Are the arguments schema-valid AND semantically correct?
  (c) Did the agent recover from a failed tool call, or did it loop?
Return JSON: { "tool_selection": 0-1, "args": 0-1, "recovery": 0-1, "reasoning": "..." }
Trajectory: {trajectory}
User goal: {goal}
"""

# 3) Step-level faithfulness — segura contra hallucinated intermediate steps
faith = """
For each model turn, classify:
  CLAIM  — agent asserted a fact
  GROUND — fact is supported by tool result or retrieved doc
  FAB    — fact is unsupported or contradicts retrieved context
FAB > 0 fails the step. Report counts and the offending turn IDs.
"""

Benchmarks that hold

LayerTriggerPatternCostGate
UnitEvery PRDeterministic tool/arg/schema~$0block merge
TrajectoryEvery PR50–200 cases, strict+unordered$0–$5block merge
OutcomeNightly100-prompt LLM-judge (4o-mini)~$2/nightalert on –5pp
OnlineContinuous1–5% sampled + judge$60+/moerror-budget burn → rollback

AgentAssay (arXiv 2603.02601): 78–100% cost reduction at equivalent statistical guarantees via SPRT; 86% behavioral detection power where binary pass/fail has 0%. Total: $227 across 5 models, 3 scenarios, 7,605 trials.

The unit is the trajectory, not the response. Score tool selection, argument extraction, result utilization, error recovery, plan coherence, and task completion — separately. If a framework can't do those six independently, it's LLM eval, not agent eval.

Tab 02 · Structured, Long-Term Memory with Automatic Consolidation

A context window is short-term and re-paid every turn. Memory is persistent, has its own storage tier, evolution rules, and a forgetting policy. The two are complements, not substitutes.

Why it matters

LongMemEval showed 1M-token models drop 30%+ accuracy when forced to recall across sessions without a memory layer. The dream is hybrid: structured graph for relations, vector store for surface recall, the agent itself paging between them — and a sleep-time process that consolidates the way the hippocampus does.

Latest 2026 landscape

Letta (MemGPT)
Open source · Berkeley lineage
83.2% LoCoMo · three tiers: core/archival/recall
Mem0 v3
41k★ · 14M downloads
94.4 on LongMemEval · p95 17.12s → 1.44s (–91%)
Zep / Graphiti
Open source
94.8% on Deep Memory Retrieval · bi-temporal graph
LangMem
LangGraph-native
Checkpointer + store · async background consolidation
Anthropic Memory Tool + Dreaming
Shipped May 6, 2026
Async hippocampal-style consolidation between sessions
Google Memory Bank
Gemini Enterprise
Identity-scoped DB primitive
APEX-MEM
ACL 2026 long
88.88% LoCoMo QA · 86.2% LongMemEval · property graph
Memanto
arXiv 2604.22085
89.8% LongMemEval · 87.1% LoCoMo · sub-90ms
GBrain (Garry Tan)
Open source · hybrid
49.1% P@5 vs 17.7% w/o graph · vector+BM25+KG

End-to-end pipeline demo

user turn → Mem0 single-pass ADD extraction (LLM-agnostic) → Zep Graphiti bi-temporal edge upsert → LangMem store (vector+graph, same canonical IDs) → Letta core memory block (always-in-context persona+task) → Anthropic Dreaming (nightly, async) merges duplicates, rewrites stale → retriever: vector similarity → graph hops → recency decay → top-k into context → agent turn

Prompts that work

# 1) Single-pass ADD-only extraction (Mem0 v3 idiom) — one LLM call, no UPDATE/DELETE
extract_prompt = """
Read this conversation turn. Emit only NEW facts about the user
that are not already in the existing memory store. Skip generic chit-chat.
Skip things the user already corrected this turn.
Each fact: { "subject": str, "predicate": str, "object": str, "confidence": 0-1, "ts": ISO8601 }
Existing memory (for dedup awareness): {existing}
Conversation: {turn}
"""

# 2) Conflict resolution — when new info contradicts old, stamp the old invalid, keep history
conflict_prompt = """
New fact: {new_fact}
Candidate conflicting edges: {candidates}
Decide:
  REPLACE — new supersedes (mark old invalid_at=now, add new with valid_at=now)
  COEXIST — both can be true (e.g., user has two roles over time)
  REJECT — new is hallucinated; ignore
Return JSON with decision, reason, and updated edges.
"""

# 3) Sleep-time reflection (Anthropic Dreaming / Letta sleep-time agent idiom)
reflect = """
Recent episodic trace (last 24h): {episodes}
Long-term store: {store}
Produce 0–5 NEW high-order insights that:
  (a) cross multiple episodes,
  (b) are not yet in the store,
  (c) are at a higher abstraction than the events themselves.
Do not summarize. Do not repeat. Output JSON array of insights.
"""

# 4) Recency-decay reranking (production default)
final_score = 0.7 * relevance + 0.3 * exp(-lambda * days_since)
#  lambda ≈ ln(2) / 14d → 14-day half-life, tune from production retrieval

Benchmarks that hold

SystemLongMemEvalLoCoMoNotes
Mem0 v394.4—~7k tokens/query vs 25k+ full-context
Memanto89.887.132× compression · sub-90ms · single retrieval
APEX-MEM86.288.88 (QA)Append-only, retrieval-time resolution
Letta—83.2MemGPT lineage, 3-tier model
Zep (Graphiti)94.8% Deep Memory Retrievalbeats MemGPT 93.4% · 90% latency cut

Production target: HOT tier <2K tokens (current session) · WARM 2K–8K (prefs+recent decisions) · COLD unlimited vector-indexed. Recency default: 14-day half-life.

Hybrid wins. Vector for surface, graph for relations, the agent itself for paging. Add a sleep-time process that consolidates every 25–50 task completions, and the store keeps getting smarter without retraining the model.

Tab 03 · Agent Observability, Guardrails, and Real-Time Interruption

Tracing tells you what happened. Eval tells you if it was good. Guardrails stop the bad from reaching the user — at sub-200ms, with graduated interventions, ideally before the tool call.

Why it matters

Agents autonomously call tools, send email, write rows. Enterprises won't deploy them without runtime enforcement. A keyword filter is too blunt. A post-hoc audit is too late. The new floor: streaming interception, intent modeling, and policy-as-code with hardware-rooted attestation behind it.

Latest 2026 landscape

Langfuse v4
MIT · observations-first
~29.8k★ · ClickHouse acquired Jan 2026
Arize Phoenix / AX
ELv2 / SaaS
~$50/mo entry · $70M Series C Feb 2025
LangSmith
Closed · $39/seat
SmithDB ~12× faster trace queries · 5K traces free
OpenTelemetry GenAI v1.41
Open standard
Status: Development (not yet Stable)
NeMo Guardrails
Apache 2.0
Colang DSL · 6 rail types · F5 integration GA Jul 2026
Lakera Guard
Closed · sub-200ms
Threat-intel DB · prompt-injection firewall
GAAT
arXiv 2604.05119
98.3% VPR · 8.4ms median detection · beats NeMo +19.5pp
Lean-Agent Protocol
arXiv 2604.01483
Lean 4 + Aristotle · deterministic financial compliance
Tumeryk
NemoClaw + NeMo
Trust-score control plane · Mar 15, 2026

End-to-end pipeline demo

agent run → OTel GenAI spans (Phoenix, gen_ai.* attrs) → Langfuse v4 observation table (one row per LLM call) → Lakera Guard <200ms injection/PII check → NeMo Colang topical + jailbreak rail → GAAT OPA policy check (graduated: L0 ALLOW → L4 QUARANTINE) → if high-stakes → Lean 4 type-checker (microsecond verdict) → PII redaction on tool results (TasmanianDevil / Openlayer) → span scored online → Datadog export via OTLP

Prompts that work

# 1) NeMo Colang — jailbreak + content safety rail
# config.yml
rails:
  input:
    flows:
      - content safety check input $model=llama-3.1-nemoguard-8b-content-safety
      - self check jailbreak
  output:
    flows:
      - content safety check output $model=llama-3.1-nemoguard-8b-content-safety
      - self check hallucination
  execution:
    flows:
      - check tool call $allowed_tools=['search','create_ticket']

# 2) GAAT Governance Telemetry Schema (OPA-compatible)
package agent.guardrails

deny[msg] {
  input.tool_call.name == "send_email"
  not input.user.consent.email_outbound
  msg := sprintf("tool %v requires email_outbound consent", [input.tool_call.name])
}

warn[msg] {
  input.tool_call.arguments.pii_detected == true
  msg := "PII in tool arguments — redact before send"
}

# 3) Graduated intervention (L0–L4)
intervene(severity, action) = {"L0":"allow","L1":"alert","L2":"flag","L3":"redirect","L4":"quarantine"}[severity]

Benchmarks that hold

SystemDetection (VPR)Latency medianNotes
GAAT (arXiv 2604.05119)98.3% ±0.78.4 ms (detect) · 127 ms (e2e)5,000 synthetic flows · 95% CI [97.1, 99.2]
NeMo Guardrails78.8%~45 msagent-boundary only · misses cross-agent
Centralized gateway89.4%—single chokepoint
Cedar (AWS)76.8%—policy engine
Dashboard-only27.1%—no enforcement

Deterministic checks <50ms · LLM-judge 1–5s on cloud Turing models · budget the synchronous chain <300ms end-to-end. Defense in depth beats any single layer.

Observability is a witness. Guardrails are the boundary. Wire the boundary with policy-as-code in version control, score every decision, and ship the audit log to the regulator's mailbox before they ask for it.

Tab 04 · Tool Integration & Dynamic API Orchestration

Function calling is a runtime convention inside one LLM API. MCP is a transport-level protocol that lives outside it. In 2026 you ship one MCP server and every compatible client can use it. That's the unlock.

Why it matters

Connecting agents to real APIs is still messy. The 2026-07-28 MCP spec — stateless core, MRTR, async tasks, formal extension system — pushed the protocol from a developer-facing tool-calling convention toward enterprise-grade production infrastructure. Auto-generation from OpenAPI collapsed the onboarding tax.

Latest 2026 landscape

MCP 2026-07-28
Anthropic-led, community standard
1,000+ community servers · stateless · MRTR
AutoMCP
arXiv 2507.16044
76.5% OOTB success · 99.9% with 19 LOC fixes (1,023 tool calls)
McProxy (Okta)
NL → MCP · patent-pending
Onboarding 16 hours → 30 seconds
Tyk AI Studio
Open source gateway
MCP tool generation from OpenAPI · scoped RBAC · PII redaction
Foundry Agent Service
Azure · managed identity
OpenAPI 3.0 → tool with Entra ID auth
Code mode (programmatic tool calling)
Deno · Monty · pctx · Wasmtime
Sandboxed code composes tool calls · only final result back
Semantic Kernel MCP
Microsoft
Native in Microsoft Agent Framework 1.0
AgentGuard / TasmanianDevil
.NET · offline
PII redaction on input, output, AND tool results

End-to-end pipeline demo

OpenAPI 3.0 spec → AutoMCP compiler (auth scaffold + schemas) → MCP server (stdio / streamable HTTP) → Tyk AI Studio registers server, attaches policy + PII redaction → agent calls via tools/list + tools/call → if multi-step → code-mode sandbox composes → PII redaction on tool result (AgentGuard) → audit log to OTel → progressive discovery loads tool defs on demand

Prompts that work

# 1) Tool description generation — LLM writes the JSON-schema description a model will see
describe_tool = """
Given this OpenAPI operation, produce an MCP tool definition:
  - name: snake_case, action_object
  - description: 1–2 sentences stating WHEN to call (not what it returns)
  - inputSchema: JSON Schema, required fields marked
  - outputSchema: shape of the success response
  - examples: 2 input/output pairs
OpenAPI op: {op}
"""

# 2) Argument schema validation — never trust the LLM
from jsonschema import validate, ValidationError
try:
    validate(instance=tool_call.arguments, schema=tool.inputSchema)
except ValidationError as e:
    # refuse + emit structured error so agent can retry with corrected args
    return {"error": "schema_violation", "path": e.absolute_path, "msg": e.message}

# 3) Progressive discovery — defer tool defs into context
search_tools_prompt = """
Available MCP servers: {server_list}
For this user request, which 1–2 servers are needed? Reply with [server_name].
Do not list tools — defs load on demand.
"""

# 4) Tool-result PII redaction (the under-appreciated surface)
policy = (GuardrailPolicyBuilder()
    .RedactPii()             # order 20 — runs on input, output, AND tool results
    .GuardToolResults()      # wires the tool-result interception lane
    .Build())

Benchmarks that hold

ToolResult
AutoMCP OOTB76.5% of 1,023 tool calls
AutoMCP after ≤19 LOC fixes per API99.9%
McProxy onboarding16 h → 30 s
MCP community servers (2026)1,000+
Code-mode sandbox overhead (Monty, Wasmtime)near-native

PII has 4 entry points — training data, user inputs, retrieved context, model outputs. The fifth is tool-call arguments, which execute before any output guardrail sees them. Cover all five or you have a hole.

MCP is the new USB. One server, every client, every model. Auto-generate from OpenAPI, slap policy + PII redaction on the gateway, and the agent gets a tool that any model can drive.

Tab 05 · Self-Improving Agent Pipelines (Auto Fine-Tuning from Experience)

Human labels are expensive. Static prompts plateau. The agent should learn from production — failure → preference pair → DPO → canary → ship or roll back, all without a human in the loop.

Why it matters

Production agents accumulate failure modes faster than anyone can label them. The 2026 stack: SFT for instruction following, DPO/SimPO for general preferences, GRPO/DAPO with verifiable rewards for reasoning. The closed loop: capture failures → synthesize preference pairs → fine-tune a smaller model → canary it → beat the old one on cost and quality, or revert.

Latest 2026 landscape

OpenRLHF
Apache 2.0
PPO / GRPO / REINFORCE++ / DAPO · 34B DPO on 8 A100
TRL (Hugging Face)
Apache 2.0
DPOTrainer, SFTTrainer, QLoRA, Online-DPO
Voyager (Wang et al. 2023)
NVIDIA/Caltech
Skill library · 3.3× items · 15.3× tech tree · 0%→100% zero-shot
Claude Agent SDK Skills
Anthropic · 2026 reference
SKILL.md + 3-level disclosure (metadata/body/bundled)
skillkit
npm · cross-agent
Works with 32+ coding agents
GRPO / DAPO
Verifiable rewards
No reward model · rule-based · math/code/structured
Online DPO
Iterative
Iter-1: easy pairs → Iter-N: hard pairs
Evaluation-Driven Development (EDD)
explainx.ai 2026
3 JSON eval cases BEFORE the SKILL.md

End-to-end pipeline demo

production traces (Arize) → failure classifier (LLM judge, pass^k) → promote to golden dataset → Best-of-16 sampling (current policy) → rule-based judge = (won, lost) pair → TRL DPOTrainer (QLoRA, 1 epoch, β=0.1) → eval on golden (DeepEval) → if pass: canary 5% with error budget → if budget burn → rollback, ship skill to library → new model replaces old in router

Prompts that work

# 1) Best-of-N task prompt — rejection sampling for DPO pairs
bos_prompt = """
You are attempting: {task}.
Run the test suite when done. Return:
  status: "pass" | "fail"
  diff:   unified diff of your changes
  notes:  one-paragraph rationale
Do not explain before attempting. Just attempt.
"""

# 2) DPO preference pair generator — deterministic judge (no LLM cost)
def to_pair(trace, test_runner):
    won  = next((t for t in trace.attempts if test_runner(t) == "pass"), None)
    lost = next((t for t in trace.attempts if test_runner(t) == "fail"), None)
    if won and lost:
        return {"prompt": trace.prompt, "chosen": won.code, "rejected": lost.code}
    return None

# 3) Automatic curriculum (Voyager-style — what skill to learn next?)
curriculum = """
Current skill library (embeddings): {skill_descs}
Recent failures (last 24h): {failures}
Open unexplored territory in: {domain}
Propose the next 3 skills to acquire. Each skill: name, description (1 sentence), why now.
Do not duplicate. Do not propose skills already in the library.
"""

# 4) Self-verifier (Voyager iterative prompting)
verify = """
The skill output was: {output}
Environment state: {state}
Did the skill achieve its stated goal? Reply:
  VERIFIED — clear evidence in state
  REJECTED — no evidence, here's why
  AMBIGUOUS — partial; what to check next
"""

Benchmarks that hold

MethodDataComputeWhen
SFT(prompt, ideal_response) pairsLowFirst, always
DPO10K+ pairs (50–100K comfortable)Low (2 models in memory)Default for alignment 2026
Online DPOSelf-generated + judgeMedium (iterative)Continuous improvement
GRPO / DAPOVerifiable (math/code)MediumReasoning, structured output
PPO (full RLHF)50–500K comparisonsVery high (4 models)Frontier labs, max quality

Voyager: removing the skill library plateaued late runs; removing self-verification dropped performance 73%. Skill library transfer lifted AutoGPT zero-shot from 0/3 to 1–2/3.

Skills, not weights. Voyager showed you don't need fine-tuning to get accumulation — a well-indexed code store plus a capable base model is sufficient. Fine-tune only when the skill library has plateaued and the cost math works out above ~100M tokens/month per task.

Tab 06 · Multi-Agent Collaboration & Debate with Provenance

Three models agreed. It was still wrong. An ICML 2025 study found that when two models both err, they converge on the same wrong answer 60% of the time. The fix isn't more votes — it's structured debate with provenance.

Why it matters

Cross-model agreement is correlated evidence, not confirmation. Models share training data, architectures, post-training recipes. The 2026 audit: agreement-to-correctness Spearman ρ of 0.20–0.59 — positive but weak. The most agreement-prone model had the least trustworthy agreement signal. Real reconciliation is a designed process, not a vote count.

Latest 2026 landscape

LangGraph
MIT · production default
Klarna, Uber, LinkedIn · 36k★ · 1.2.7
CrewAI
MIT
~54k★ · role/goal/backstory · v1.15.1
Microsoft Agent Framework
Apr 3, 2026 · 1.0
AutoGen successor · .NET support
OpenAgents
Community
Native MCP + A2A · persistent agent networks
GAVEL
ACL Findings 2026
FEVEROUS 41.80 (+4.20) · HOVER 49.60 (+4.10)
Minority Sentinel
arXiv 2606.29270
10+4+8 dim fingerprint + LightGBM · 81.2% precision on majority-overturn
CARA
arXiv 2606.08457
Cross-agent reasoning alignment · consistency illusion
Evidence Tracing survey
arXiv 2606.04990
Provenance as typed graph: memory writes, handoffs, claims

End-to-end pipeline demo

question → 3 independent briefs (different framings, different words) → LangGraph supervisor dispatches → round 1: argue → round 2: forced refutation (strongest case AGAINST emerging answer) → GAVEL Evidence Contract: each atomic subclaim bound to evidence unit → Mechanized Scrutinizer validates cited IDs and quoted spans → Minority Sentinel: 10+4+8 dim fingerprint → LightGBM decides: keep majority OR overturn → Judge emits decision + provenance graph → audit log (who-said-what-when-with-what-evidence)

Prompts that work

# 1) Independent briefs (kill shared-input bias — different words, different framing)
def brief(question, framing):
    return f"""You are a {framing}. Answer ONLY this question, in 200 words.
Do not mention other reviewers. Do not hedge. State your position and the top 2 pieces
of evidence you would cite. Question: {question}"""

# 2) Forced refutation (kill agreeableness)
refute = """The other reviewers currently lean toward: "{emerging_answer}".
Make the STRONGEST possible case that this answer is WRONG.
Cite specific evidence. Do NOT play devil's advocate — only argue if you genuinely believe it.
If you cannot find a real flaw, say "I cannot refute this on present evidence."
"""

# 3) GAVEL Evidence Contract (atomic subclaim ↔ evidence unit)
claim = {
  "id": "C1",
  "text": "The acquisition closed on 2025-04-12",
  "evidence": [
    {"type": "doc", "id": "sec-filing-2025-Q2.pdf#p14", "span": "...closed April 12, 2025..."},
    {"type": "doc", "id": "press-release-2025-04-12.html#body", "span": "...today announced the closing..."}
  ]
}

# 4) Minority Sentinel fingerprint (LightGBM input)
fingerprint = {
  "dynamics":  [agreement_velocity, persistence, refutation_strength]*3 + [...],   # 10 dims
  "voting":    [majority_size, dissent_persistence, refuter_count, vote_flip],     # 4 dims
  "semantic":  [novel_evidence_introduced, claim_grounding, citation_density, ...]  # 8 dims
}

Benchmarks that hold

SetupResultSource
Multi-model errors converge on same wrong answer60%ICML 2025, 350+ LLMs
Agreement ↔ correctness correlationρ = 0.20–0.59July 2026 audit, 265k samples
Minority is correct when agents diverge~25%Minority Sentinel preprint, Jun 2026
Minority Sentinel precision on overturn81.2%arXiv 2606.29270
GAVEL FEVEROUS (with evidence)41.80 (+4.20)ACL Findings 2026
GAVEL HOVER (with evidence)49.60 (+4.10)ACL Findings 2026

Self-consistency (one model, vote) still works for checkable answers (+17.9pp on GSM8K). But cross-model consensus on open-ended judgment is unproven — that's a different claim with weaker evidence.

Vote count is not a verification method. Evidence-locked debate with mechanized scrutiny is. When the minority consistently introduces new evidence while the majority only endorses each other, overturn.

Tab 07 · Privacy-Preserving Local-First Agents

The most useful agents need intimate data. The most intimate data is the one you can't send to a third party. Local-first isn't a preference in 2026 — it's a regulatory and trust floor.

Why it matters

Cloud agents leak. Always. Even with the best contract. The 2026 answer: on-device processing by default, confidential compute for the heavy lifts, no raw data ever leaving the user's machine or its attested enclave. Federighi's line: privacy is non-negotiable, verifiable by outside experts.

Latest 2026 landscape

Apple Intelligence + PCC
iOS 27 · fall 2026
~3B param on-device · Private Cloud Compute for heavy lifts
Foundation Models framework
iOS 26+
~3B on-device LLM · NPU-optimized
MLX LM Server
Apple Silicon-native
Local LLM serving on macOS, optimal perf
iClaw (barrasso.me)
Apr 27, 2026
Local agent using Apple Intelligence, App Sandbox
AgenTEE
arXiv 2604.18231
Multi-cVM on Arm CCA · <5.15% overhead
Confidential Computing Summit
Jun 23–24, 2026 · SF
Workload-based identity, Confidential Tenancy
Multi-Agent Firewall
arXiv 2607.08282
Local-first, browser+MiTM, F1 94.93% on PII
ADAPT
ACL ARR 2026 Jan
Local LLM learns dynamic privacy-preserving delegation

End-to-end pipeline demo

user data (Health, Mail, Calendar) → Foundation Models framework loads 3B on-device LLM → PII detector local (TasmanianDevil) → agent runs entirely on Apple Silicon → if task exceeds on-device cap → escalate to Private Cloud Compute → PCC: data never stored, only used to fulfill request, verifiable by outside experts → result back on device → audit log on device (Apple Intelligence Report export) → zero raw data persistence

Prompts that work

# 1) ADAPT dynamic privacy-preserving delegation (local decides what to ship)
delegate_prompt = """
Local user context: {context}
Remote task: {task}
Decide:
  LOCAL_ONLY      — task can be answered from local context, do not call remote
  PRIVACY_SAFE    — sanitize context, then call remote with the sanitized prompt
  FULL_CONTEXT    — task needs full context; call remote but only over attested PCC
For each decision emit: { "mode": ..., "sanitized_prompt": ..., "why": "..." }
"""

# 2) iClaw scaffolding for the Apple Foundation Model (small-model constraints)
instructions = InstructionsBuilder() \\
    .limit_tool_choice(max_tools=2-3)             # AFM gets distracted past that
    .set_maximum_response_tokens(256)             # keep responses predictable
    .temperature(0.3)                              # diverse but constrained
    .prewarm()                                     # reduce latency, cache prefix
    .build()

# 3) Multi-Agent Firewall local PII redaction (T10 config, best F1)
firewall_config = {
  "interceptors": ["browser", "mitm_proxy"],
  "agents": [
    {"role":"deterministic_pii", "model":"regex+ner", "lane":"sync"},
    {"role":"semantic_pii",      "model":"llm-judge", "lane":"async"},
    {"role":"code_leakage",      "model":"ast_diff",   "lane":"sync"},
  ],
  "policy": "block_on_high_confidence, redact_on_medium"
}

# 4) CryptoKit + Secure Enclave for credentials
let key = SecKeyCreateRandomKey(...)             # never leaves enclave
let att = SecKeyCreateAttestation(key, ...)      # prove enclave-bound

Benchmarks that hold

SystemResult
AgenTEE (Arm CCA, multi-cVM)<5.15% runtime overhead
Multi-Agent Firewall (PII)P 94.95 · R 94.92 · F1 94.93
Apple Foundation Model on-device~3B params · 4,096-token window
Apple Intelligence availability (iOS 27)iPhone 16+ · iPhone 15 Pro · M1+

Hybrid is the production standard: local for data-sensitive + high-frequency + pre-processing; cloud frontier for complex reasoning, long context, MCP-compatible local-model endpoints. Pure-local is not yet recommended for most production requirements in 2026.

The cloud is an accelerator, not a default. Send the minimum. Keep the keys in the enclave. Verify the contract by hardware, not by promise. When Apple can prove PCC and outside experts can audit the binaries, the trust math actually works.

Tab 08 · Cost-Optimisation & Inference Routing for Agent Loops

Frontier models cost 20–100× more than their small-model cousins. The cheapest way to cut an AI bill without cutting capability is to stop paying frontier prices for easy requests.

Why it matters

40–70% of production queries can be served by the cheap model with no detectable quality loss. 20–30% require frontier. The middle 10–20% benefits from cascade verification. The 2026 stack: semantic cache → difficulty router → cheap → escalate on confidence → cost attribution per step → drift monitor. Done right, you keep 95% of frontier quality at 15–30% of the bill.

Latest 2026 landscape

RouteNLP
arXiv 2604.23577
40–85% cost cut · p99 1847ms → 387ms · 91% acceptance
RouteLLM
LMSYS
95% GPT-4 quality at 26% cost · 74% production savings
FrugalGPT
Chen et al. 2023
Original cascade framework
Martian
Commercial · 200+ models
$9M NEA · claims 20–97% cost cut
Not Diamond
Meta-model router
Default inside OpenRouter Auto
OpenRouter
500+ models · 60+ providers
5.5% markup · inverse-square price weighting
LiteLLM
Open source proxy
Self-hostable · routing + fallback + retry
PILOT
2025
Budget-constrained contextual bandit

End-to-end pipeline demo

query → semantic cache (cosine > 0.92) hit-rate ~40% → else RouteLLM classifier (difficulty) → nano tier (Haiku 4.5 / GPT-5.4 nano) at $0.05–$0.30/M → conformal confidence check → if low confidence → Sonnet 4 / GPT-5 mid ($0.50–$3/M) → if still low → Opus 4 / o3 frontier ($3–$15/M) → PII redact result → cost attribution per agent step → weekly re-routing audit (drift check)

Prompts that work

# 1) Difficulty classifier (the cheap-LLM-as-router)
classify = """
Read this user query and rate its difficulty on 3 axes (0=trivial, 10=hard):
  reasoning      — multi-step logic required?
  tool_count     — how many distinct tools will the agent need?
  context_depth  — needs deep retrieval / long doc reasoning?
Reply JSON: {"reasoning": int, "tool_count": int, "context_depth": int, "tier": "nano|mid|frontier"}
Query: {query}
"""

# 2) Conformal threshold setter (distribution-free, no calibration drift)
def conformal_threshold(scores, alpha=0.1):
    # 90% of cheap-model outputs that score above this are actually correct
    return np.quantile(scores, 1 - alpha)

# 3) Cascade trigger (cheaper than re-querying)
trigger = cheap_response if confidence(conformal, cheap.score) > tau else escalate(cheap, mid)

# 4) SLO tier → model pool mapping (production default)
TIERS = {
  "realtime":  {"latency_ms": 500,  "cost_per_req": 0.001,  "pool": ["haiku-4.5", "gpt-5.4-nano"]},
  "standard":  {"latency_ms": 3000, "cost_per_req": 0.01,   "pool": ["sonnet-4", "gpt-5"]},
  "premium":   {"latency_ms": 30000,"cost_per_req": 0.10,   "pool": ["opus-4", "o3"]},
  "batch":     {"latency_ms": None, "cost_per_req": 0.0001, "pool": ["local-llama", "deepseek-r1"]}
}

Benchmarks that hold

StrategyCost cutQuality
Model routing only (learned)40–85%95% of frontier
Routing + semantic caching40–70%95%+
Cascade at 80% cheap-resolution~72%95%+
Single-provider overspend (no routing)–30% to –50% (lost)100%

Tier price gap in 2026: 100×. Claude Opus 4.6 $5/$25 vs GPT-5.4 nano $0.05/$0.40 per 1M. Route 70% cheap / 20% mid / 10% frontier → $15/M → $2.10/M blended.

Stop defaulting to GPT-4. Static rules for the obvious 70%, learned router for the rest, cascade for the ambiguous middle. Semantic caching before routing. Cost attribution per step. Monthly re-audit or the routing mix drifts toward the cheap model and quality dies silently.

Benchmarking · What to build first, second, and not at all

Cross-cutting comparison: maturity, leverage, time-to-value, lock-in, and the order you should ship them.

Maturity × leverage matrix

PipelineMaturityLeverageTime to shipLock-in
1 · Agent EvalProductionCritical — without it you ship regressions blind1–2 weeksLow (Langfuse MIT, DeepEval Apache)
2 · Long-Term MemoryProductionHigh — unlocks multi-session agents2–4 weeksMedium (Mem0 proprietary, Letta/Zep OSS)
3 · Observability & GuardrailsProductionCritical — without it you can't ship to enterprise2–3 weeksMedium (NeMo OSS, Lakera/GAAT mixed)
4 · Tool OrchestrationProductionHigh — every tool you add is a new revenue surface1 week per tool with MCP + AutoMCPLow (MCP is open standard)
5 · Self-Improving AgentsPilotHigh long-term, marginal short-term4–8 weeksMedium (TRL/OpenRLHF OSS)
6 · Multi-Agent DebatePilotNiche — high-stakes domains only3–6 weeksLow (LangGraph OSS, GAVEL OSS)
7 · Privacy / Local-FirstProduction (Apple) / Pilot (cross-platform)Critical for regulated industries4–12 weeks (depends on stack)High (PCC is Apple-only; AgenTEE needs Arm CCA)
8 · Cost & RoutingProductionHighest dollar leverage, 1st-week ROI3–7 daysLow (LiteLLM OSS, OpenRouter plug-in)

The shipping order, ranked by ROI

  1. Tab 8 — Cost & Routing. Three days of work, recovers 40–70% of the bill. The money funds everything else. Start with semantic cache + static rules, then RouteLLM.
  2. Tab 1 — Agent Eval. You cannot safely ship anything else without it. Two weeks. Start with DeepEval in CI on golden-50.
  3. Tab 3 — Observability + Guardrails. Phoenix + Langfuse for the trace story, NeMo + Lakera for the runtime story. Two to three weeks. Required for enterprise.
  4. Tab 4 — Tool Orchestration. Stand up MCP server per API, wire AutoMCP. Pays off the moment you have a second tool.
  5. Tab 2 — Long-Term Memory. Add Mem0 + Zep hybrid the moment your agent has cross-session requirements. Two to four weeks.
  6. Tab 5 — Self-Improving Agents. Pilot Online DPO only after eval infrastructure catches the regressions. Then iterate.
  7. Tab 7 — Privacy / Local-First. Apple-native if iOS/macOS; AgenTEE on Arm for cross-platform confidential compute. Required for health, legal, finance.
  8. Tab 6 — Multi-Agent Debate. Niche. Add GAVEL + Minority Sentinel only when stakes justify the cost — legal review, medical, financial analysis.

Concrete dollar math (illustrative)

OptimizationTypical savingsEffort
Prompt caching (60–80% on agent/chat)60–80%1–2 days
Model routing (50–70% on mixed workloads)50–70%3–7 days
Batch API for async work (50%)50%1 day
Output-shape engineering (strict JSON, max-tokens, no CoT bloat)20–40%1 week
Semantic caching (repetitive workloads)30–60%3–5 days
Fine-tune a small model (>100M tokens/month/task)10–30× cost/request4–8 weeks

The benchmark that matters most

It's not the one in the paper. It's the one in your production: CPSO — cost per successful outcome. Not tokens. Not traces. Successful outcomes — generated, sent, accepted by the business without rework. That single number tells you whether every other optimization is real or theater.

Eight pipelines. One report. The cheap ones — cost routing and agent eval — fund the expensive ones — memory, debate, confidential compute. Ship the cheap ones first. They pay for the rest.