Skip to Content
Patterns

Native compaction & provider fallback

Persist provider-native compaction (Anthropic context editing, OpenAI stored responses) across chat.agent turns so history is never re-sent, and fall back between providers without losing the conversation.

Providers compact a conversation within a single request. Anthropic's context editing clears old tool-use blocks server-side, and OpenAI's stored responses keep the thread server-side so you only send the delta. Neither changes what your agent has accumulated, so on its own the next turn re-sends the whole transcript again and the token saving is lost.

This is the gap this page closes. After each turn, mirror what the provider compacted into the agent's stored history with chat.history.set(), so the next turn is derived from the already-reduced conversation. And because a native handle is provider-specific, this page also shows how a provider-agnostic Trigger.dev compaction summary lets you fall back between providers without re-expanding the context.

The full runnable example is triggerdotdev/resilient-chat-example. See native-persist.ts for the Anthropic persistence flow and resilient-chat.ts for OpenAI stored responses plus provider fallback.

Two kinds of compaction

They are not competing; they compose. Native compaction is the per-turn optimization, and Trigger.dev compaction is the durable, portable checkpoint.

Native (provider)Trigger.dev compaction
RunsInside one provider requestBetween steps / turns, in your run
ScopeProvider-specific (Anthropic edits, OpenAI stored thread)Provider-agnostic
Portable across a provider switchNo, the handle is a cache miss on the other providerYes, summarize returns a plain string
Persisted by defaultNo, you mirror it in onTurnCompleteYes, replaces model messages and keeps UI messages

Persist Anthropic native context editing

Anthropic's contextManagement clears old tool-use/tool-result blocks server-side per request, and reports how many it cleared in providerMetadata.anthropic.contextManagement.appliedEdits (clearedToolUses, clearedInputTokens). It does not touch your accumulated history, so on its own the next turn still re-sends everything.

The fix: read the appliedEdits counts as they stream in onStepFinish, then after the turn mirror that clearing into stored history with chat.history.set(). No custom summarizer is involved, since the provider's native editing drives what gets persisted.

/trigger/native-persist.ts
import {  } from "@trigger.dev/sdk/ai";
import { , , type  } from "ai";
import {  } from "@ai-sdk/anthropic";
import { z } from "zod";

const fetchRecord = ({
  : "Fetch the full text of a record by its numeric id.",
  : z.object({ id: z.number() }),
  execute: async ({ id }) => ({ id, text: `RECORD ${id}: ...` }),
});

// How many tool-uses Anthropic cleared this turn, per chat. Captured in run(),
// applied in onTurnComplete. An in-memory Map is enough because the run stays
// alive across turns (idleTimeoutInSeconds).
const clearedByChat = new Map<string, number>();

const isToolPart = (p: { type?: string }) =>
  typeof p?.type === "string" && (p.type.("tool-") || p.type === "dynamic-tool");

// Drop the oldest n tool parts, mirroring what the provider cleared. A tool call
// and its result live in one part, so pairing stays intact. Once a message is
// edited, its thinking and every later message's thinking no longer verify on
// Claude 5.5 models, so those reasoning parts are dropped too.
function pruneOldestToolParts(messages: [], n: number): [] {
  let toRemove = n;
  let edited = false;
  const out: [] = [];
  for (const m of messages) {
    if (m. !== "assistant" || !m.) {
      out.(m);
      continue;
    }
    const kept = m..((p) => {
      if (toRemove > 0 && isToolPart(p)) {
        toRemove--;
        edited = true;
        return false;
      }
      return true;
    });
    const parts = edited ? kept.((p) => p.type !== "reasoning") : kept;
    if (parts. > 0) out.({ ...m,  });
  }
  return out;
}

export const nativePersist = .({
  : "native-persist",
  : 120,
  : { fetchRecord },
  : async ({ , , , ,  }) => {
    return ({
      : ("claude-sonnet-5-5"),
      messages,
      ,
      : ,
      : (12),
      : {
        anthropic: {
          contextManagement: {
            edits: [
              {
                type: "clear_tool_uses_20250919",
                trigger: { type: "tool_uses", value: 2 },
                keep: { type: "tool_uses", value: 1 },
                clearToolInputs: true,
              },
            ],
          },
        },
      },
      : ({  }) => {
        const cm = ?.anthropic?.contextManagement as
          | { appliedEdits?: Array<{ type?: string; clearedToolUses?: number }> }
          | undefined;
        let stepCleared = 0;
        for (const e of cm?.appliedEdits ?? []) {
          if (e.type === "clear_tool_uses_20250919") stepCleared += e.clearedToolUses ?? 0;
        }
        if (stepCleared > 0) {
          clearedByChat.(, (clearedByChat.() ?? 0) + stepCleared);
        }
      },
    });
  },
  // After the turn, mirror the server-side clearing into stored history.
  : async ({ ,  }) => {
    const cleared = clearedByChat.() ?? 0;
    if (cleared <= 0) return;
    ..(pruneOldestToolParts(, cleared));
    clearedByChat.(, 0);
  },
});

Turn 1 sends the user message and accumulates six tool results. Anthropic clears four of them server-side. onTurnComplete prunes those four from stored history, so turn 2 re-sends the smaller conversation (one tool result, not six) instead of the full transcript.

onTurnComplete is where persistence happens. Action turns fire onAction only, and a chat.history.set() inside run() is overwritten by the accumulator at turn end. See Persistence and replay.

Thinking is on by default on Claude 5.5 models, and each thinking block is bound to the conversation that came before it. Removing tool parts from earlier turns in your own code changes that history, so Anthropic can reject the next request with a 400 (Invalid signature in thinking block). Server-side context editing, as configured above, doesn't count as an edit. That's why pruneOldestToolParts also removes the reasoning parts from the turns it changes and every turn after them.

Persist OpenAI stored responses

OpenAI's store: true keeps the thread server-side and returns a responseId. Pass that back as previousResponseId on the next turn and send only the messages since the last assistant reply; everything before it lives on OpenAI's side.

/trigger/openai-store.ts
import {  } from "@trigger.dev/sdk/ai";
import { , type  } from "ai";
import {  } from "@ai-sdk/openai";

// Persist the stored-response handle between turns. Replace with your database.
const nativeStore = new Map<string, { previousResponseId: string }>();

// When OpenAI already holds the thread, send only what is new since the last
// assistant reply. Everything before that lives server-side.
function messagesSinceLastAssistant(messages: []): [] {
  let last = -1;
  for (let i = 0; i < messages.; i++) {
    if (messages[i]!.role === "assistant") last = i;
  }
  return last === -1 ? messages : messages.(last + 1);
}

export const openaiStore = .({
  : "openai-store",
  : 120,
  : async ({ , , ,  }) => {
    const native = nativeStore.();
    const outbound = native ? messagesSinceLastAssistant() : ;

    const result = ({
      : ("gpt-6-luna"),
      messages: outbound,
      : ,
      : (5),
      : {
        openai: native ? { store: true, previousResponseId: native.previousResponseId } : { store: true },
      },
    });

    // Capture the response id off the metadata for the next turn.
    void result..((meta) => {
      const rid = typeof meta?.openai?.responseId === "string" ? meta.openai.responseId : undefined;
      if (rid) nativeStore.(, { previousResponseId: rid });
    });

    return result;
  },
});

Turn 1 stores the thread and sends all three messages. Turn 2 sends only the new user message (1/3), because OpenAI already has the rest.

Fall back between providers without losing history

A native handle is a per-provider cache. An OpenAI previousResponseId means nothing to Anthropic, and Anthropic's server-side edits don't exist on OpenAI. So when a provider is down and you fall back to another, the native optimization is a cache miss, and a naive fallback re-sends the entire raw transcript to the new provider.

Trigger.dev's compaction is the portable checkpoint that closes this gap. summarize returns a plain string and compactModelMessages returns neutral ModelMessage[], so the summary survives any provider switch. Tag each native handle with the provider that produced it. On a switch it's a cache miss, and you rebuild from the summary instead of re-expanding the context.

/trigger/resilient-chat.ts
import {  } from "@trigger.dev/sdk/ai";
import { , , , type  } from "ai";
import {  } from "@ai-sdk/anthropic";
import {  } from "@ai-sdk/openai";

type Provider = "anthropic" | "openai";
const FALLBACK_ORDER: Provider[] = ["anthropic", "openai"];

// Native handle, tagged with the provider that produced it. Replace with your DB.
type NativeState = { provider: "openai"; previousResponseId: string };
const nativeStore = new Map<string, NativeState>();

// Retained messages follow a different history after compaction, so their thinking
// blocks no longer verify on Claude 5.5 models. Drop reasoning parts before replaying them.
function stripReasoning(message: ):  {
  if (message.role !== "assistant" || typeof message.content === "string") return message;
  return { ...message, content: message.content.((part) => part.type !== "reasoning") };
}

// Provider-agnostic summary: a plain string, portable across any provider.
async function summarizeConversation(messages: []): Promise<string> {
  const {  } = await ({
    : ("gpt-6-luna"),
    messages: [
      ...messages,
      {
        role: "user",
        content:
          "Summarize this conversation so it can continue with ANY model. " +
          "Preserve decisions made, facts established, open questions, and the user's intent.",
      },
    ],
  });
  return ;
}

export const resilientChat = .({
  : "resilient-chat",
  : 120,

  compaction: {
    : ({  }) => ( ?? 0) > 80_000,
    : ({  }) => summarizeConversation(),
    : ({ ,  }) => [
      { role: "user", content: `Summary of the conversation so far:\n\n${}` },
      ....(-2).(stripReasoning),
    ],
    : ({ ,  }) => [
      {
        : (),
        : "assistant",
        : [{ type: "text", text: `[Conversation summary]\n\n${}` }],
      },
      ....(-2),
    ],
  },

  // A Trigger.dev compaction is the reset point: the provider's server-side thread
  // no longer matches the compacted baseline, so invalidate the native handle.
  : async ({  }) => {
    if () nativeStore.delete();
  },

  : async ({ , , ,  }) => {
    let lastError: unknown;
    for (const providerId of FALLBACK_ORDER) {
      const native = nativeStore.();
      try {
        if (providerId === "openai") {
          // On a switch to OpenAI with no matching handle, `messages` is already the
          // compacted baseline (summary + recent), so raw history is not re-sent.
          const useHandle = native?.provider === "openai";
          const result = ({
            : ("gpt-6-luna"),
            messages,
            : ,
            : (5),
            : {
              openai: useHandle
                ? { store: true, previousResponseId: native!.previousResponseId }
                : { store: true },
            },
          });
          void result..((meta) => {
            const rid = typeof meta?.openai?.responseId === "string" ? meta.openai.responseId : undefined;
            if (rid) nativeStore.(, { provider: "openai", previousResponseId: rid });
          });
          return result;
        }

        return ({
          : ("claude-sonnet-5-5"),
          messages,
          : ,
          : (5),
          : {
            anthropic: {
              contextManagement: {
                edits: [{ type: "clear_tool_uses_20250919", trigger: { type: "input_tokens", value: 80_000 }, keep: { type: "tool_uses", value: 3 } }],
              },
            },
          },
        });
      } catch (error) {
        lastError = error; // Provider failed, try the next one in the order.
      }
    }
    throw lastError;
  },
});

When Anthropic is down, the loop falls through to OpenAI. Because compaction has already reduced messages to a summary plus the last couple of exchanges, the switch sends the portable baseline, not megabytes of raw transcript.

The messages that compactModelMessages keeps after the summary now follow a different history from the one their thinking blocks were produced in. Claude 5.5 models reject those blocks with a 400 (Invalid signature in thinking block), which is why the example runs the retained messages through stripReasoning.

Fallback here retries a turn that hasn't started streaming yet. Once a response is streaming to the client, a mid-stream provider failure can't be swapped transparently. Surface the error and let the frontend regenerate the turn. See Error handling.

Production notes

  • Persist the handles. The Maps above (nativeStore, clearedByChat) work in the example because the run stays alive across turns, but they don't survive a run boundary. Store native handles and summaries in your database keyed by chatId, alongside your message persistence.
  • No cross-provider translation. Native compaction from one provider never transfers to another. The Trigger.dev compaction summary is the only portable baseline across a switch.
  • Native compaction is opt-in per turn. It applies only for the provider whose providerOptions you set on that turn's streamText call.

See also

  • Compaction: the provider-agnostic compaction option, onCompacted, and manual chat.compact().
  • Prompt caching: the other per-turn token optimization, and how it interacts with a growing history.
  • Database persistence: where to store native handles and summaries for real.
  • Lifecycle hooks: onTurnComplete and onCompacted in the broader hook taxonomy.

Was this page helpful?

Last updated

Edit on GitHub

On this page