An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
perf(chat): cap replayed history when the prompt cache is cold (#1018)
Yoshiki Miura84751759a1af
diff --git a/lib/streaming/__tests__/create-chat-stream-response.test.ts b/lib/streaming/__tests__/create-chat-stream-response.test.tsindex 380250b7..bf0885ac 100644--- a/lib/streaming/__tests__/create-chat-stream-response.test.ts+++ b/lib/streaming/__tests__/create-chat-stream-response.test.ts@@ -8,7 +8,8 @@ const mocks = vi.hoisted(() => ({end: vi.fn()},forceFlush: vi.fn(),- finishPromise: Promise.resolve()+ finishPromise: Promise.resolve(),+ trimColdStartHistory: vi.fn()}))vi.mock('ai', () => ({@@ -50,6 +51,11 @@ vi.mock('@/lib/streaming/helpers/attachment-sizes', () => ({resolveAttachmentSizes: vi.fn(async (messages: unknown) => messages)}))+vi.mock('@/lib/streaming/helpers/trim-cold-start-history', () => ({+ COLD_START_HISTORY_TOKEN_LIMIT: 200_000,+ trimColdStartHistory: mocks.trimColdStartHistory+}))+vi.mock('@/lib/streaming/helpers/persist-stream-results', () => ({persistStreamResults: vi.fn(async () => undefined)}))@@ -74,6 +80,7 @@ import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-resimport { describeStreamError } from '@/lib/streaming/helpers/describe-stream-error'import { EMPTY_RESPONSE_STATUS_MESSAGE } from '@/lib/streaming/helpers/is-empty-response'import { prepareMessages } from '@/lib/streaming/helpers/prepare-messages'+import { getMaxAllowedTokens } from '@/lib/utils/context-window'type StreamOptions = {onError: (event: { error: unknown }) => void@@ -150,6 +157,10 @@ describe('createChatStreamResponse', () => {beforeEach(() => {vi.clearAllMocks()mocks.finishPromise = Promise.resolve()+ mocks.trimColdStartHistory.mockImplementation((messages: unknown[]) => ({+ messages,+ trimmedAtCurrentTurn: false+ }))vi.spyOn(console, 'error').mockImplementation(() => {})})@@ -341,6 +352,38 @@ describe('createChatStreamResponse', () => {})})+ it('records a cold-start history trim on the root span', async () => {+ mocks.trimColdStartHistory.mockImplementationOnce(+ (messages: unknown[]) => ({+ messages,+ trimmedAtCurrentTurn: true+ })+ )+ mocks.stream.mockResolvedValue(createFakeResult())++ await createChatStreamResponse(createConfig())+ await mocks.finishPromise++ expect(mocks.span.update).toHaveBeenCalledWith({+ input: 'hello',+ output: 'Answer',+ metadata: { coldStartHistoryTrimmed: true }+ })+ })++ it('bounds the cold-start history limit by the model input window', async () => {+ const config = createConfig()+ mocks.stream.mockResolvedValue(createFakeResult())++ await createChatStreamResponse(config)+ await mocks.finishPromise++ expect(mocks.trimColdStartHistory).toHaveBeenCalledWith(expect.any(Array), {+ limit: Math.min(200_000, getMaxAllowedTokens(config.model)),+ modelId: 'gpt-4o-mini'+ })+ })+it('omits the output when the answer is only whitespace', async () => {mocks.stream.mockResolvedValue(createFakeResult(false, [{ type: 'text', text: ' \n' }])diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex cd913a73..1d34adc8 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -48,6 +48,10 @@ import {} from './helpers/stream-error-diagnostics'import { stripSpecFromMessages } from './helpers/strip-spec-from-messages'import { summarizeCarriedContext } from './helpers/summarize-carried-context'+import {+ COLD_START_HISTORY_TOKEN_LIMIT,+ trimColdStartHistory+} from './helpers/trim-cold-start-history'import type { StreamContext } from './helpers/types'import { BaseStreamConfig } from './types'@@ -128,6 +132,7 @@ export async function createChatStreamResponse(let rootOutput: string | undefinedlet carriedContext: Record<string, number> | undefinedlet contextWindowTruncated = false+ let coldStartHistoryTrimmed = falseconst endTracing = async () => {if (rootSpan) {@@ -157,6 +162,7 @@ export async function createChatStreamResponse(const metadata = {...(carriedContext !== undefined && { carriedContext }),...(contextWindowTruncated && { contextWindowTruncated }),+ ...(coldStartHistoryTrimmed && { coldStartHistoryTrimmed }),...failureMetadata}const update = {@@ -219,9 +225,23 @@ export async function createChatStreamResponse(messagesWithoutSpec,userId)+ const coldStartHistory = trimColdStartHistory(+ messagesWithAttachmentSizes,+ {+ limit:+ COLD_START_HISTORY_TOKEN_LIMIT > 0+ ? Math.min(+ COLD_START_HISTORY_TOKEN_LIMIT,+ getMaxAllowedTokens(model)+ )+ : 0,+ modelId: model.id+ }+ )+ coldStartHistoryTrimmed = coldStartHistory.trimmedAtCurrentTurnconst messagesToConvert = dedupeAttachments(capHistoricalAttachments(- compactHistoricalMessages(messagesWithAttachmentSizes)+ compactHistoricalMessages(coldStartHistory.messages)))carriedContext = summarizeCarriedContext(messagesToConvert)diff --git a/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts b/lib/streaming/helpers/__tests__/trim-cold-start-history.test.tsnew file mode 100644index 00000000..1c98ff47--- /dev/null+++ b/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts@@ -0,0 +1,286 @@+import type { UIMessage } from 'ai'+import { describe, expect, it } from 'vitest'++import {+ parseColdStartHistoryTokenLimit,+ trimColdStartHistory+} from '../trim-cold-start-history'++const START = new Date('2026-01-01T00:00:00.000Z')+const WARM_GAP_MS = 30 * 60 * 1000+const COLD_GAP_MS = WARM_GAP_MS + 1++function timestamp(offsetMs: number): Date {+ return new Date(START.getTime() + offsetMs)+}++function message(+ id: string,+ role: 'user' | 'assistant',+ createdAt: Date | string | undefined,+ parts: UIMessage['parts'] = [{ type: 'text', text: 'content'.repeat(8) }]+): UIMessage {+ return {+ id,+ role,+ parts,+ ...(createdAt !== undefined && { metadata: { createdAt } })+ }+}++function turn(+ index: number,+ createdAt: Date | string | undefined,+ assistantParts?: UIMessage['parts']+): UIMessage[] {+ return [+ message(`u${index}`, 'user', createdAt),+ message(`a${index}`, 'assistant', createdAt, assistantParts)+ ]+}++function userIds(messages: UIMessage[]): string[] {+ return messages.filter(item => item.role === 'user').map(item => item.id)+}++describe('trimColdStartHistory', () => {+ it('only advances the cut as cold turns are appended', () => {+ let messages: UIMessage[] = []+ let dropped = new Set<string>()++ for (let i = 0; i < 8; i++) {+ messages = messages.concat(turn(i, timestamp(i * COLD_GAP_MS)))+ const result = trimColdStartHistory(messages, {+ now: timestamp(i * COLD_GAP_MS),+ limit: 20+ })+ const kept = new Set(userIds(result.messages))+ const nextDropped = new Set(userIds(messages).filter(id => !kept.has(id)))++ for (const id of dropped) expect(nextDropped.has(id)).toBe(true)+ dropped = nextDropped+ }++ expect(dropped.size).toBeGreaterThan(0)+ })++ it('keeps the previous output as a prefix when a warm turn is appended', () => {+ const atColdStart = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS)),+ ...turn(2, timestamp(2 * WARM_GAP_MS)),+ ...turn(3, timestamp(3 * WARM_GAP_MS)),+ ...turn(4, timestamp(3 * WARM_GAP_MS + COLD_GAP_MS))+ ]+ const first = trimColdStartHistory(atColdStart, {+ now: timestamp(3 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 20+ }).messages+ const second = trimColdStartHistory(+ atColdStart.concat(turn(5, timestamp(4 * WARM_GAP_MS + COLD_GAP_MS))),+ {+ now: timestamp(4 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 20+ }+ ).messages++ expect(second.slice(0, first.length)).toEqual(first)+ })++ it('leaves fewer than five turns untouched', () => {+ const messages = Array.from({ length: 4 }, (_, i) =>+ turn(i, timestamp(i * COLD_GAP_MS))+ ).flat()+ const result = trimColdStartHistory(messages, {+ now: timestamp(4 * COLD_GAP_MS),+ limit: 1+ })++ expect(result.messages).toBe(messages)+ expect(result.trimmedAtCurrentTurn).toBe(false)+ })++ it('does not trim when every gap is at most the idle boundary', () => {+ const messages = Array.from({ length: 7 }, (_, i) =>+ turn(i, timestamp(i * WARM_GAP_MS))+ ).flat()++ expect(+ trimColdStartHistory(messages, {+ now: timestamp(7 * WARM_GAP_MS),+ limit: 1+ }).messages+ ).toBe(messages)+ })++ it('does not treat a missing historical timestamp as cold', () => {+ const messages = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS)),+ ...turn(2, timestamp(2 * WARM_GAP_MS)),+ ...turn(3, undefined),+ ...turn(4, timestamp(2 * WARM_GAP_MS + COLD_GAP_MS))+ ]++ expect(+ trimColdStartHistory(messages, {+ now: timestamp(2 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 1+ }).messages+ ).toBe(messages)+ })++ it('uses now for a missing timestamp on the last user message', () => {+ const now = timestamp(3 * WARM_GAP_MS + COLD_GAP_MS)+ const messages = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS)),+ ...turn(2, timestamp(2 * WARM_GAP_MS)),+ ...turn(3, timestamp(3 * WARM_GAP_MS)),+ ...turn(4, undefined)+ ]+ const result = trimColdStartHistory(messages, { now, limit: 20 })++ expect(userIds(result.messages)).toEqual(['u0', 'u4'])+ expect(result.trimmedAtCurrentTurn).toBe(true)+ })++ it('keeps the first and current turns whole', () => {+ const toolParts = [+ {+ type: 'tool-search',+ toolCallId: 'call-current',+ state: 'output-available',+ input: { query: 'current' },+ output: { results: ['current'] }+ }+ ] as unknown as UIMessage['parts']+ const messages = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS), toolParts),+ ...turn(2, timestamp(2 * WARM_GAP_MS)),+ ...turn(3, timestamp(3 * WARM_GAP_MS)),+ ...turn(4, timestamp(3 * WARM_GAP_MS + COLD_GAP_MS), toolParts)+ ]+ const result = trimColdStartHistory(messages, {+ now: timestamp(3 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 20+ })++ expect(result.messages.map(item => item.id)).toEqual([+ 'u0',+ 'a0',+ 'u4',+ 'a4'+ ])+ expect(result.messages[0].role).toBe('user')+ expect(result.messages.at(-1)?.parts).toEqual(toolParts)+ })++ it('budgets history by what is replayed, not by execution details', () => {+ const executionHeavyParts = [+ { type: 'reasoning', text: 'r'.repeat(100_000) },+ {+ type: 'tool-search',+ toolCallId: 'call-heavy',+ state: 'output-available',+ input: { query: 'heavy' },+ output: {+ results: [+ {+ title: 'Source',+ url: 'https://example.com',+ content: 'x'.repeat(100_000)+ }+ ]+ }+ },+ { type: 'text', text: 'Short answer.' }+ ] as unknown as UIMessage['parts']+ const messages = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS), executionHeavyParts),+ ...turn(2, timestamp(2 * WARM_GAP_MS), executionHeavyParts),+ ...turn(3, timestamp(3 * WARM_GAP_MS), executionHeavyParts),+ ...turn(4, timestamp(3 * WARM_GAP_MS + COLD_GAP_MS))+ ]+ const result = trimColdStartHistory(messages, {+ now: timestamp(3 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 1_000+ })++ expect(result.messages).toBe(messages)+ expect(result.trimmedAtCurrentTurn).toBe(false)+ })++ it('counts replayed text with the model tokenizer when a model is given', () => {+ const denseText = '日本語の文章'.repeat(100)+ const coldAt = timestamp(3 * WARM_GAP_MS + COLD_GAP_MS)+ const messages = Array.from({ length: 5 }, (_, i) => {+ const createdAt = i === 4 ? coldAt : timestamp(i * WARM_GAP_MS)+ return [+ message(`u${i}`, 'user', createdAt, [+ { type: 'text', text: denseText }+ ]),+ message(`a${i}`, 'assistant', createdAt)+ ]+ }).flat()+ const options = { now: coldAt, limit: 1_200 }++ expect(trimColdStartHistory(messages, options).messages).toBe(messages)+ expect(+ trimColdStartHistory(messages, { ...options, modelId: 'gpt-4o-mini' })+ .trimmedAtCurrentTurn+ ).toBe(true)+ })++ it('disables trimming when the limit is zero', () => {+ const messages = Array.from({ length: 6 }, (_, i) =>+ turn(i, timestamp(i * COLD_GAP_MS))+ ).flat()++ expect(+ trimColdStartHistory(messages, {+ now: timestamp(6 * COLD_GAP_MS),+ limit: 0+ }).messages+ ).toBe(messages)+ })++ it('parses the configured limit', () => {+ expect(parseColdStartHistoryTokenLimit(undefined)).toBe(200_000)+ expect(parseColdStartHistoryTokenLimit('')).toBe(200_000)+ expect(parseColdStartHistoryTokenLimit('not-a-number')).toBe(200_000)+ expect(parseColdStartHistoryTokenLimit('-1')).toBe(200_000)+ expect(parseColdStartHistoryTokenLimit('0')).toBe(0)+ expect(parseColdStartHistoryTokenLimit('3.9')).toBe(3)+ expect(parseColdStartHistoryTokenLimit('0.5')).toBe(1)+ })++ it('flags only the turn whose cold event advances the cut', () => {+ const coldMessages = [+ ...turn(0, timestamp(0)),+ ...turn(1, timestamp(WARM_GAP_MS)),+ ...turn(2, timestamp(2 * WARM_GAP_MS)),+ ...turn(3, timestamp(3 * WARM_GAP_MS)),+ ...turn(4, timestamp(3 * WARM_GAP_MS + COLD_GAP_MS))+ ]+ const coldResult = trimColdStartHistory(coldMessages, {+ now: timestamp(3 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 20+ })+ const warmResult = trimColdStartHistory(+ coldMessages.concat(turn(5, timestamp(4 * WARM_GAP_MS + COLD_GAP_MS))),+ {+ now: timestamp(4 * WARM_GAP_MS + COLD_GAP_MS),+ limit: 20+ }+ )++ expect(coldResult.trimmedAtCurrentTurn).toBe(true)+ expect(warmResult.trimmedAtCurrentTurn).toBe(false)+ expect(warmResult.messages.length).toBeLessThan(+ coldMessages.length + turn(5, timestamp(0)).length+ )+ })+})diff --git a/lib/streaming/helpers/trim-cold-start-history.ts b/lib/streaming/helpers/trim-cold-start-history.tsnew file mode 100644index 00000000..3e733653--- /dev/null+++ b/lib/streaming/helpers/trim-cold-start-history.ts@@ -0,0 +1,190 @@+import type { UIMessage } from 'ai'++import { estimateAttachmentTokens } from '@/lib/utils/attachment-tokens'+import { countTextTokens } from '@/lib/utils/context-window'++import { compactHistoricalMessages } from './compact-historical-messages'++const DEFAULT_COLD_START_HISTORY_TOKEN_LIMIT = 200_000+const CACHE_IDLE_MS = 30 * 60 * 1000+const MIN_TURNS = 5+const MESSAGE_TOKEN_OVERHEAD = 4++export function parseColdStartHistoryTokenLimit(+ raw: string | undefined+): number {+ const value = raw?.trim()+ if (!value) return DEFAULT_COLD_START_HISTORY_TOKEN_LIMIT++ const parsed = Number(value)+ if (!Number.isFinite(parsed) || parsed < 0) {+ return DEFAULT_COLD_START_HISTORY_TOKEN_LIMIT+ }++ return parsed === 0 ? 0 : Math.max(1, Math.floor(parsed))+}++export const COLD_START_HISTORY_TOKEN_LIMIT = parseColdStartHistoryTokenLimit(+ process.env.COLD_START_HISTORY_TOKEN_LIMIT+)++type ReplayedText = {+ text: string+ fixedTokens: number+}++type Turn = {+ messages: UIMessage[]+ timestamp?: number+ replayed: ReplayedText[]+}++const textEncoder = new TextEncoder()++function serialize(value: unknown): string {+ if (value === undefined) return ''++ try {+ return JSON.stringify(value) ?? ''+ } catch {+ return ''+ }+}++function describeReplayedMessage(message: UIMessage): ReplayedText {+ const texts: string[] = []+ let attachmentTokens = 0++ for (const part of message.parts) {+ if (part.type === 'text' || part.type === 'reasoning') {+ texts.push(part.text)+ } else if (part.type === 'dynamic-tool' || part.type.startsWith('tool-')) {+ const toolPart = part as { input?: unknown; output?: unknown }+ texts.push(serialize(toolPart.input), serialize(toolPart.output))+ } else if (part.type.startsWith('data-')) {+ texts.push(serialize((part as { data?: unknown }).data))+ } else if (part.type === 'file') {+ const filePart = part as { mediaType?: string; size?: number }+ attachmentTokens += estimateAttachmentTokens(filePart)+ }+ }++ return {+ text: texts.join(''),+ fixedTokens: MESSAGE_TOKEN_OVERHEAD + attachmentTokens+ }+}++// Described on the message's historical replay form, which depends only on+// the message itself, so the estimate does not change as the thread grows.+function describeMessage(message: UIMessage): ReplayedText[] {+ return compactHistoricalMessages([message]).map(describeReplayedMessage)+}++// A token always spans at least one UTF-8 byte, so this bounds any tokenizer+// without running one.+function tokenUpperBound(turn: Turn): number {+ return turn.replayed.reduce(+ (total, { text, fixedTokens }) =>+ total + textEncoder.encode(text).length + fixedTokens,+ 0+ )+}++function countTurnTokens(turn: Turn, modelId?: string): number {+ return turn.replayed.reduce(+ (total, { text, fixedTokens }) =>+ total + countTextTokens(text, modelId) + fixedTokens,+ 0+ )+}++function parseTimestamp(value: unknown): number | undefined {+ if (!(value instanceof Date) && typeof value !== 'string') return undefined++ const timestamp = value instanceof Date ? value.getTime() : Date.parse(value)+ return Number.isFinite(timestamp) ? timestamp : undefined+}++function getCreatedAt(message: UIMessage): unknown {+ const metadata = message.metadata+ if (!metadata || typeof metadata !== 'object') return undefined++ return (metadata as { createdAt?: unknown }).createdAt+}++function buildTurns(messages: UIMessage[], now: Date): Turn[] {+ const userIndexes = messages.flatMap((message, index) =>+ message.role === 'user' ? [index] : []+ )+ if (userIndexes.length === 0) return []++ return userIndexes.map((userIndex, turnIndex) => {+ const start = turnIndex === 0 ? 0 : userIndex+ const end = userIndexes[turnIndex + 1] ?? messages.length+ const turnMessages = messages.slice(start, end)+ const timestamp =+ parseTimestamp(getCreatedAt(messages[userIndex])) ??+ (turnIndex === userIndexes.length - 1 ? now.getTime() : undefined)++ return {+ messages: turnMessages,+ timestamp,+ replayed: turnMessages.flatMap(describeMessage)+ }+ })+}++export function trimColdStartHistory(+ messages: UIMessage[],+ options: { now?: Date; limit?: number; modelId?: string } = {}+): { messages: UIMessage[]; trimmedAtCurrentTurn: boolean } {+ const limit = options.limit ?? COLD_START_HISTORY_TOKEN_LIMIT+ if (limit <= 0) return { messages, trimmedAtCurrentTurn: false }++ const turns = buildTurns(messages, options.now ?? new Date())+ if (turns.length < MIN_TURNS) {+ return { messages, trimmedAtCurrentTurn: false }+ }++ const upperBound = turns.reduce(+ (total, turn) => total + tokenUpperBound(turn),+ 0+ )+ if (upperBound <= limit) return { messages, trimmedAtCurrentTurn: false }++ const tokens = turns.map(turn => countTurnTokens(turn, options.modelId))+ let cut = 1+ let trimmedAtCurrentTurn = false++ for (let i = 1; i < turns.length; i++) {+ const previousTimestamp = turns[i - 1].timestamp+ const timestamp = turns[i].timestamp+ const cold =+ previousTimestamp !== undefined &&+ timestamp !== undefined &&+ timestamp - previousTimestamp > CACHE_IDLE_MS++ if (!cold || i + 1 < MIN_TURNS) continue++ let total = tokens[0]+ for (let j = cut; j <= i; j++) total += tokens[j]++ const cutBefore = cut+ while (total > limit && cut < i) {+ total -= tokens[cut]+ cut += 1+ }++ if (i === turns.length - 1 && cut > cutBefore) {+ trimmedAtCurrentTurn = true+ }+ }++ if (cut === 1) return { messages, trimmedAtCurrentTurn: false }++ return {+ messages: [turns[0], ...turns.slice(cut)].flatMap(turn => turn.messages),+ trimmedAtCurrentTurn+ }+}diff --git a/lib/utils/context-window.ts b/lib/utils/context-window.tsindex b09571f5..9dec37cf 100644--- a/lib/utils/context-window.ts+++ b/lib/utils/context-window.ts@@ -154,6 +154,24 @@ function getEncoder(modelId: string) {}}+/**+ * Token count for plain text, using the model's tokenizer when available+ */+export function countTextTokens(text: string, modelId?: string): number {+ if (!text) return 0++ const encoder = modelId ? getEncoder(modelId) : null+ if (encoder) {+ try {+ return encoder.encode(text).length+ } catch {+ // Fall through to the character approximation+ }+ }++ return Math.ceil(text.length / 4)+}+/*** Estimate token count for a message* Uses tiktoken for accurate counting when available