How do you implement progressive summarization for infinite-length customer support chat threads? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you implement progressive summarization for infinite-length customer support chat threads?

message-square
0

How Progressive Summarization Works for Infinite Support Threads

In a long-running customer support thread, sending the entire raw message history on every turn increases token cost, exceeds context windows, and dilutes attention on recent actions. Progressive summarization maintains a compact, rolling state summary of older turns while keeping a recent verbatim sliding window of the latest messages—updating the summary incrementally as older turns age out of the window.

  • Rolling summary + sliding recent window: Instead of re-summarizing the entire transcript from scratch on every message, you summarize only newly evicted older messages and merge them into the existing running summary (previousSummary + evictedMessages -> nextSummary), while passing nextSummary + recentMessages to the responder model.
  • Structured state beats free-form prose: Storing the summary as a structured state object (customer intent, verified account/order IDs, resolved steps, open issues/blockers, and commitments) prevents important identifiers or promises from getting lost during compression.
  • Idempotent, concurrency-safe updates: Because support chats can receive rapid bursts of messages or concurrent webhook/agent turns, summary roll-ups should be guarded by a per-thread lock or version check so two workers do not overwrite each other’s evicted messages.

Steps to Implement Progressive Summarization

  1. Define a structured summary schema: Track key support state explicitly (customerGoal, keyFactsAndIds, actionsTaken, openIssues, pendingNextSteps) plus summarizedThroughSeq so you always know which message sequence number is covered.
  2. Partition history into rolled-up summary and recent window: Keep the most recent $W$ messages (or up to a token budget, e.g., last 8–12 turns) verbatim, and whenever older messages exceed the window/token threshold, batch them for incremental summarization.
  3. Merge evicted turns into the existing summary atomically: Pass the prior structured summary and only the newly evicted messages to a fast, low-cost summarizer model with strict schema output, then persist the updated summary and watermark (summarizedThroughSeq).
  4. Assemble bounded prompts for the support agent/model: Construct the active context from systemPrompt + structuredSummary + recentVerbatimMessages, falling back gracefully if a summarization call fails or times out.

TypeScript Example: Rolling Structured Summarizer for Long Support Threads

import OpenAI from "openai";

const openai = new OpenAI();

export interface ChatMessage {
  seq: number;
  role: "user" | "assistant" | "agent" | "system";
  content: string;
  timestampMs: number;
}

export interface SupportThreadSummary {
  customerGoal: string;
  keyFactsAndIds: string[];
  actionsTaken: string[];
  openIssues: string[];
  pendingNextSteps: string[];
  summarizedThroughSeq: number;
  updatedAtMs: number;
}

export interface ThreadContextState {
  threadId: string;
  messages: ChatMessage[];
  summary: SupportThreadSummary | null;
}

const SUMMARY_SCHEMA = {
  name: "support_thread_summary",
  strict: true,
  schema: {
    type: "object",
    additionalProperties: false,
    required: [
      "customerGoal",
      "keyFactsAndIds",
      "actionsTaken",
      "openIssues",
      "pendingNextSteps",
    ],
    properties: {
      customerGoal: { type: "string" },
      keyFactsAndIds: {
        type: "array",
        items: { type: "string" },
      },
      actionsTaken: {
        type: "array",
        items: { type: "string" },
      },
      openIssues: {
        type: "array",
        items: { type: "string" },
      },
      pendingNextSteps: {
        type: "array",
        items: { type: "string" },
      },
    },
  },
} as const;

export class ProgressiveSupportSummarizer {
  private readonly locks = new Map<string, Promise<void>>();

  constructor(
    private readonly recentWindowSize = 8,
    private readonly summarizeBatchSize = 6,
    private readonly summarizerModel = "gpt-4o-mini"
  ) {}

  async appendAndPrepareContext(
    state: ThreadContextState,
    newMessage: Omit<ChatMessage, "seq">
  ): Promise<{
    summary: SupportThreadSummary | null;
    recentMessages: ChatMessage[];
  }> {
    const nextSeq =
      state.messages.length > 0 ? state.messages[state.messages.length - 1].seq + 1 : 1;
    state.messages.push({ ...newMessage, seq: nextSeq });

    await this.withThreadLock(state.threadId, async () => {
      const currentSummarizedSeq = state.summary?.summarizedThroughSeq ?? 0;
      const cutoffSeq = Math.max(0, nextSeq - this.recentWindowSize);

      // Messages older than the recent window that haven't been folded into the summary yet
      const unsummarizedOlder = state.messages.filter(
        (m) => m.seq > currentSummarizedSeq && m.seq <= cutoffSeq
      );

      if (unsummarizedOlder.length >= this.summarizeBatchSize) {
        const batch = unsummarizedOlder.slice(0, this.summarizeBatchSize);
        state.summary = await this.rollUpBatch(state.summary, batch);
      }
    });

    const recentMessages = state.messages.slice(-this.recentWindowSize);
    return {
      summary: state.summary,
      recentMessages,
    };
  }

  private async rollUpBatch(
    previousSummary: SupportThreadSummary | null,
    batch: ChatMessage[]
  ): Promise<SupportThreadSummary> {
    const transcriptChunk = batch
      .map((m) => `[#\${m.seq} ${m.role.toUpperCase()}]:${m.content}`)
      .join("\n");

    const response = await openai.chat.completions.create({
      model: this.summarizerModel,
      temperature: 0,
      messages: [
        {
          role: "system",
          content: [
            "You maintain a cumulative support state summary.",
            "Merge the prior summary with the newly evicted messages without dropping exact IDs, amounts, dates, or unresolved issues.",
            "Remove items that were clearly resolved unless still relevant as context.",
          ].join(" "),
        },
        {
          role: "user",
          content: [
            "Previous Summary JSON:",
            JSON.stringify(previousSummary ?? null),
            "\nNew Evicted Messages:",
            transcriptChunk,
          ].join("\n"),
        },
      ],
      response_format: {
        type: "json_schema",
        json_schema: SUMMARY_SCHEMA,
      },
    });

    const raw = response.choices[0]?.message.content ?? "{}";
    const parsed = JSON.parse(raw) as Omit<
      SupportThreadSummary,
      "summarizedThroughSeq" | "updatedAtMs"
    >;

    const lastSeq = batch[batch.length - 1]?.seq ?? previousSummary?.summarizedThroughSeq ?? 0;

    return {
      ...parsed,
      summarizedThroughSeq: lastSeq,
      updatedAtMs: Date.now(),
    };
  }

  private async withThreadLock(threadId: string, fn: () => Promise<void>): Promise<void> {
    const prev = this.locks.get(threadId) ?? Promise.resolve();
    const current = prev.catch(() => {}).then(fn);
    this.locks.set(threadId, current);
    try {
      await current;
    } finally {
      if (this.locks.get(threadId) === current) {
        this.locks.delete(threadId);
      }
    }
  }
}

Helpful Tips for Production Support Thread Summarization

  • Preserve exact identifiers verbatim (order_id, ticket_id, error codes, dates): Instruct the summarizer to copy IDs and constraints literally rather than paraphrasing them, since paraphrased IDs break tool calls and lookup queries later in the thread.
  • Trigger roll-ups asynchronously or before the reply when thresholds are crossed: If a batch roll-up adds 300–800ms of latency, consider running background roll-ups on incoming messages when possible or keeping the summarizer on a fast, lightweight model with a strict timeout and fallback to the previous summary.
  • Archive raw messages in durable storage while keeping active context bounded: Store full message logs in your database/object store for auditability and agent transcripts, and keep only the latest summary + recent window in hot memory or Redis context caches.