What is the best way to truncate long chat histories while preserving system instructions and recent tool results? | A1Lab@HamzaM to AI & LLMEnglish • 4 days ago

What is the best way to truncate long chat histories while preserving system instructions and recent tool results?

message-square
0

How History Truncation Works While Preserving Instructions and Tool Results

Truncating a long conversation requires keeping standing instructions and recent tool exchanges intact while avoiding two common failures: breaking tool_call_id pairs and invalidating prefix prompt caches.

  • Pin system and developer messages at the front: Keep leading instruction messages untouched so persona, safety boundaries, and output rules never drop out.
  • Treat assistant tool calls and tool responses as atomic groups: Never slice between an assistant tool_calls message and its matching role: "tool" result messages, or leave orphaned tool messages behind, because mismatched IDs cause immediate API validation errors.
  • Keep recent tool results and the active tail: Retain the latest user turn and recent assistant + tool exchanges so the model sees current outputs, errors, and state changes.
  • Compact stale bulky tool payloads before dropping turns: Large JSON or search outputs from older turns consume most of the context window. Trimming or summarizing old tool message contents first saves tokens without losing conversational flow.

Steps to Truncate Long Chat Histories

  1. Extract leading system and developer messages: Separate pinned instruction messages from the rest of the transcript so they remain at the start of the outbound array.
  2. Group turns into indivisible atomic units: Keep standard user or assistant text turns as single-message groups, and bundle an assistant message with tool_calls together with all following tool messages matching its tool_call_ids.
  3. Accumulate groups backward within your token budget: Walk from the newest group to the oldest and include complete groups until the next group would exceed your available history token budget.
  4. Compact oversized older tool outputs if still over budget: Shorten older tool message payloads (while preserving valid tool_call_id pairs) before dropping entire recent exchanges.

TypeScript Example: Atomic Group History Truncation

import OpenAI from "openai";

type ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;

interface TurnGroup {
  messages: ChatMessage[];
  tokens: number;
}

function estimateTokens(msg: ChatMessage): number {
  const contentStr =
    typeof msg.content === "string"
      ? msg.content
      : JSON.stringify(msg.content ?? "");
  const toolCallsStr =
    "tool_calls" in msg && msg.tool_calls ? JSON.stringify(msg.tool_calls) : "";
  // Rough heuristic (~4 chars/token); swap in tiktoken for exact counts
  return Math.ceil((contentStr.length + toolCallsStr.length + 16) / 4);
}

function buildAtomicGroups(history: ChatMessage[]): TurnGroup[] {
  const groups: TurnGroup[] = [];
  let i = 0;

  while (i < history.length) {
    const msg = history[i];

    // Bundle assistant tool_calls with all contiguous matching tool responses
    if (msg.role === "assistant" && "tool_calls" in msg && msg.tool_calls?.length) {
      const expectedIds = new Set(msg.tool_calls.map((tc) => tc.id));
      const groupMsgs: ChatMessage[] = [msg];
      let j = i + 1;

      while (j < history.length && history[j].role === "tool") {
        const toolMsg = history[j] as OpenAI.Chat.Completions.ChatCompletionToolMessageParam;
        if (expectedIds.has(toolMsg.tool_call_id)) {
          groupMsgs.push(toolMsg);
          j++;
        } else {
          break;
        }
      }

      const tokens = groupMsgs.reduce((sum, m) => sum + estimateTokens(m), 0);
      groups.push({ messages: groupMsgs, tokens });
      i = j;
      continue;
    }

    // Skip orphaned tool messages that lack a preceding assistant tool_calls turn
    if (msg.role === "tool") {
      i++;
      continue;
    }

    groups.push({ messages: [msg], tokens: estimateTokens(msg) });
    i++;
  }

  return groups;
}

export function truncateHistoryPreservingTools(
  messages: ChatMessage[],
  maxHistoryTokens: number
): ChatMessage[] {
  // 1. Pin leading system and developer instructions
  const pinned: ChatMessage[] = [];
  let idx = 0;
  while (
    idx < messages.length &&
    (messages[idx].role === "system" || messages[idx].role === "developer")
  ) {
    pinned.push(messages[idx]);
    idx++;
  }

  const pinnedTokens = pinned.reduce((sum, m) => sum + estimateTokens(m), 0);
  const availableForHistory = Math.max(0, maxHistoryTokens - pinnedTokens);

  // 2. Group remaining turns into atomic units
  const groups = buildAtomicGroups(messages.slice(idx));
  if (groups.length === 0) {
    return pinned;
  }

  // 3. Keep the latest group and walk backward while within budget
  const selectedGroups: TurnGroup[] = [];
  let usedTokens = 0;

  for (let g = groups.length - 1; g >= 0; g--) {
    const group = groups[g];
    const isLatest = g === groups.length - 1;
    if (!isLatest && usedTokens + group.tokens > availableForHistory) {
      break;
    }
    selectedGroups.unshift(group);
    usedTokens += group.tokens;
  }

  return [...pinned, ...selectedGroups.flatMap((g) => g.messages)];
}

Helpful Tips for Production Contexts

  • Shift truncation windows in batches to preserve prompt caches: Dropping one message per turn busts prefix caches on every request. Trigger truncation only when crossing a token threshold (e.g., 80% of budget) and prune down to a lower watermark (e.g., 50%) so subsequent turns hit cache.
  • Store full transcripts in your database, truncate only outbound payloads: Keep the complete history in persistent storage for auditing, replay, or summarization, and pass only the trimmed slice to the LLM API.
  • Combine sliding windows with rolling summaries for long sessions: For multi-step agent or coding tasks, keep recent turns and tool outputs verbatim while summarizing dropped older turns into a concise state note.