An AI-powered search engine with a generative UI
TypeScript generative-aigenerative-uinextjsollamareactsearxngshadcn-uitailwindcsstavilytypescriptupstashvercel-ai-sdk
feat(tracing): record the turn's carried context weight by kind (#987)
Yoshiki Miuraa3b9b59b3b28
diff --git a/lib/streaming/__tests__/create-chat-stream-response.test.ts b/lib/streaming/__tests__/create-chat-stream-response.test.tsindex b63b3fbe..b61bf5eb 100644--- a/lib/streaming/__tests__/create-chat-stream-response.test.ts+++ b/lib/streaming/__tests__/create-chat-stream-response.test.ts@@ -435,7 +435,10 @@ describe('createChatStreamResponse', () => {expect(mocks.span.update).toHaveBeenCalledWith({input: '"earlier.png" (image/png)',- output: 'Answer'+ output: 'Answer',+ metadata: {+ carriedContext: { attachments: 1, attachmentTokens: 10_000 }+ }})})diff --git a/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts b/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.tsindex 99030303..eab41c01 100644--- a/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts+++ b/lib/streaming/__tests__/create-ephemeral-chat-stream-response.test.ts@@ -10,7 +10,8 @@ const mocks = vi.hoisted(() => ({},forceFlush: vi.fn(),finishPromise: Promise.resolve(),- serializedError: undefined as string | undefined+ serializedError: undefined as string | undefined,+ shouldTruncateMessages: vi.fn(() => false)}))vi.mock('ai', () => ({@@ -39,6 +40,11 @@ vi.mock('@/lib/agents/researcher', () => ({researcher: vi.fn(() => ({ stream: mocks.stream }))}))+vi.mock('@/lib/utils/context-window', async importOriginal => ({+ ...(await importOriginal<typeof import('@/lib/utils/context-window')>()),+ shouldTruncateMessages: mocks.shouldTruncateMessages+}))+vi.mock('@/lib/utils/telemetry', () => ({isTracingEnabled: vi.fn(() => true)}))@@ -236,6 +242,50 @@ describe('createEphemeralChatStreamResponse', () => {expect(mocks.stream).not.toHaveBeenCalled()})+ it('keeps the carried context and the failure metadata on one update', async () => {+ const streamError = new Error('stream failed')+ mocks.stream.mockImplementation(async (options: StreamOptions) => {+ options.onError({ error: streamError })+ return createFakeResult()+ })++ await createEphemeralChatStreamResponse(+ createConfigWithParts([+ { type: 'data-pastedContent', data: { text: 'ab' } }+ ])+ )+ await mocks.finishPromise++ const update = mocks.span.update.mock.calls.at(-1)?.[0]+ expect(update).toMatchObject({+ level: 'ERROR',+ metadata: {+ carriedContext: { pastedChars: 2 },+ streamErrorPhase: 'generation'+ }+ })+ })++ it('flags a turn whose converted history hit the context window', async () => {+ mocks.shouldTruncateMessages.mockReturnValueOnce(true)+ mocks.stream.mockResolvedValue(createFakeResult())++ await createEphemeralChatStreamResponse(+ createConfigWithParts([+ { type: 'data-pastedContent', data: { text: 'ab' } }+ ])+ )+ await mocks.finishPromise++ const update = mocks.span.update.mock.calls.at(-1)?.[0]+ expect(update).toMatchObject({+ metadata: {+ carriedContext: { pastedChars: 2 },+ contextWindowTruncated: true+ }+ })+ })+it('omits the output when the answer is only whitespace', async () => {mocks.stream.mockResolvedValue(createFakeResult({ parts: [{ type: 'text', text: ' \n' }] })@@ -367,7 +417,10 @@ describe('createEphemeralChatStreamResponse', () => {expect(mocks.span.update).toHaveBeenCalledWith({input: '"report.pdf" (application/pdf)',- output: 'Answer'+ output: 'Answer',+ metadata: {+ carriedContext: { attachments: 1, attachmentTokens: 50_000 }+ }})})@@ -383,7 +436,8 @@ describe('createEphemeralChatStreamResponse', () => {expect(mocks.span.update).toHaveBeenCalledWith({input: 'pasted content (600 characters)',- output: 'Answer'+ output: 'Answer',+ metadata: { carriedContext: { pastedChars: 600 } }})expect(JSON.stringify(mocks.span.update.mock.calls)).not.toContain('secret')})@@ -422,7 +476,14 @@ describe('createEphemeralChatStreamResponse', () => {expect(mocks.span.update).toHaveBeenCalledWith({input: '"notes.txt" (text/plain), pasted content (2 characters)',- output: 'Answer'+ output: 'Answer',+ metadata: {+ carriedContext: {+ attachments: 1,+ attachmentTokens: 50_000,+ pastedChars: 2+ }+ }})})diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.tsindex 270f14c2..aefd10ba 100644--- a/lib/streaming/create-chat-stream-response.ts+++ b/lib/streaming/create-chat-stream-response.ts@@ -45,6 +45,7 @@ import {type StreamErrorStage} from './helpers/stream-error-diagnostics'import { stripSpecFromMessages } from './helpers/strip-spec-from-messages'+import { summarizeCarriedContext } from './helpers/summarize-carried-context'import type { StreamContext } from './helpers/types'import { BaseStreamConfig } from './types'@@ -113,6 +114,8 @@ export async function createChatStreamResponse(// carries no incoming message, so its input comes from the prepared history.let rootInput = describeTurnInput(message?.parts)let rootOutput: string | undefined+ let carriedContext: Record<string, number> | undefined+ let contextWindowTruncated = falseconst endTracing = async () => {if (rootSpan) {@@ -132,10 +135,23 @@ export async function createChatStreamResponse(// whatever was streamed before it. That is not the turn's answer, so// it is not recorded as one.const hasAnswer = !hasStreamError && !hasEmptyResponse+ // A failure update carries its own metadata (#945), so the two are+ // merged rather than spread as siblings: whichever came last would+ // otherwise drop the other one entirely.+ const failureMetadata =+ failureUpdate && 'metadata' in failureUpdate+ ? failureUpdate.metadata+ : undefined+ const metadata = {+ ...(carriedContext !== undefined && { carriedContext }),+ ...(contextWindowTruncated && { contextWindowTruncated }),+ ...failureMetadata+ }const update = {...(rootInput !== undefined && { input: rootInput }),...(hasAnswer && rootOutput !== undefined && { output: rootOutput }),- ...failureUpdate+ ...failureUpdate,+ ...(Object.keys(metadata).length > 0 && { metadata })}if (Object.keys(update).length > 0) rootSpan.update(update)rootSpan.end()@@ -195,6 +211,7 @@ export async function createChatStreamResponse(compactHistoricalMessages(messagesWithAttachmentSizes)))+ carriedContext = summarizeCarriedContext(messagesToConvert)// Convert to model messages and apply context window managementstreamErrorStage = 'convert-messages'@@ -207,6 +224,7 @@ export async function createChatStreamResponse(const maxTokens = getMaxAllowedTokens(model)const originalCount = modelMessages.lengthmodelMessages = truncateMessages(modelMessages, maxTokens, model.id)+ contextWindowTruncated = trueif (process.env.NODE_ENV === 'development') {console.log(diff --git a/lib/streaming/create-ephemeral-chat-stream-response.ts b/lib/streaming/create-ephemeral-chat-stream-response.tsindex 11f2ba9e..60eb3b92 100644--- a/lib/streaming/create-ephemeral-chat-stream-response.ts+++ b/lib/streaming/create-ephemeral-chat-stream-response.ts@@ -39,6 +39,7 @@ import {type StreamErrorStage} from './helpers/stream-error-diagnostics'import { stripSpecFromMessages } from './helpers/strip-spec-from-messages'+import { summarizeCarriedContext } from './helpers/summarize-carried-context'import { BaseStreamConfig } from './types'import { langfuseSpanProcessor } from '@/instrumentation'@@ -83,6 +84,8 @@ export async function createEphemeralChatStreamResponse(messages.findLast(m => m.role === 'user')?.parts)let rootOutput: string | undefined+ let carriedContext: Record<string, number> | undefined+ let contextWindowTruncated = falseconst endTracing = async () => {if (rootSpan) {@@ -102,10 +105,23 @@ export async function createEphemeralChatStreamResponse(// whatever was streamed before it. That is not the turn's answer, so// it is not recorded as one.const hasAnswer = !hasStreamError && !hasEmptyResponse+ // A failure update carries its own metadata (#945), so the two are+ // merged rather than spread as siblings: whichever came last would+ // otherwise drop the other one entirely.+ const failureMetadata =+ failureUpdate && 'metadata' in failureUpdate+ ? failureUpdate.metadata+ : undefined+ const metadata = {+ ...(carriedContext !== undefined && { carriedContext }),+ ...(contextWindowTruncated && { contextWindowTruncated }),+ ...failureMetadata+ }const update = {...(rootInput !== undefined && { input: rootInput }),...(hasAnswer && rootOutput !== undefined && { output: rootOutput }),- ...failureUpdate+ ...failureUpdate,+ ...(Object.keys(metadata).length > 0 && { metadata })}if (Object.keys(update).length > 0) rootSpan.update(update)rootSpan.end()@@ -119,6 +135,7 @@ export async function createEphemeralChatStreamResponse(const messagesToConvert = dedupeAttachments(capHistoricalAttachments(compactHistoricalMessages(messagesWithoutSpec)))+ carriedContext = summarizeCarriedContext(messagesToConvert)streamErrorStage = 'convert-messages'let modelMessages = await convertToModelMessages(messagesToConvert, {@@ -129,6 +146,7 @@ export async function createEphemeralChatStreamResponse(if (shouldTruncateMessages(modelMessages, model)) {const maxTokens = getMaxAllowedTokens(model)modelMessages = truncateMessages(modelMessages, maxTokens, model.id)+ contextWindowTruncated = true}streamErrorStage = 'build-agent'diff --git a/lib/streaming/helpers/__tests__/summarize-carried-context.test.ts b/lib/streaming/helpers/__tests__/summarize-carried-context.test.tsnew file mode 100644index 00000000..44289e46--- /dev/null+++ b/lib/streaming/helpers/__tests__/summarize-carried-context.test.ts@@ -0,0 +1,70 @@+import type { UIMessage } from 'ai'+import { describe, expect, it } from 'vitest'++import { summarizeCarriedContext } from '@/lib/streaming/helpers/summarize-carried-context'+import { IMAGE_ATTACHMENT_TOKENS } from '@/lib/utils/attachment-tokens'++function createMessages(parts: unknown[]): UIMessage[] {+ return [{ id: 'message-1', role: 'user', parts: parts as UIMessage['parts'] }]+}++describe('summarizeCarriedContext', () => {+ it('returns undefined for text-only history', () => {+ expect(+ summarizeCarriedContext(createMessages([{ type: 'text', text: 'hello' }]))+ ).toBeUndefined()+ })++ it('counts file parts and their estimated tokens', () => {+ expect(+ summarizeCarriedContext(+ createMessages([+ {+ type: 'file',+ mediaType: 'image/png',+ url: 'https://example.com/a'+ },+ {+ type: 'file',+ mediaType: 'application/pdf',+ size: 39,+ url: 'https://example.com/b'+ }+ ])+ )+ ).toEqual({+ attachments: 2,+ attachmentTokens: IMAGE_ATTACHMENT_TOKENS + 10+ })+ })++ it('counts each structured text kind by characters', () => {+ expect(+ summarizeCarriedContext(+ createMessages([+ { type: 'data-pastedContent', data: { text: 'paste' } },+ { type: 'data-quotedContext', data: { text: 'quote' } },+ { type: 'data-noteContext', data: { text: 'note' } }+ ])+ )+ ).toEqual({ pastedChars: 5, quotedChars: 5, noteChars: 4 })+ })++ it('omits zero-valued keys and ignores non-string data text', () => {+ expect(+ summarizeCarriedContext(+ createMessages([+ {+ type: 'file',+ mediaType: 'application/pdf',+ size: 0,+ url: 'https://example.com/a'+ },+ { type: 'data-pastedContent', data: { text: '' } },+ { type: 'data-quotedContext', data: { text: 42 } },+ { type: 'data-noteContext', data: { text: null } }+ ])+ )+ ).toEqual({ attachments: 1 })+ })+})diff --git a/lib/streaming/helpers/summarize-carried-context.ts b/lib/streaming/helpers/summarize-carried-context.tsnew file mode 100644index 00000000..f1c45f7e--- /dev/null+++ b/lib/streaming/helpers/summarize-carried-context.ts@@ -0,0 +1,65 @@+import type { UIMessage } from 'ai'++import { estimateAttachmentTokens } from '@/lib/utils/attachment-tokens'++import { isFilePart } from './attachment-parts'++/**+ * The weight a turn carries in structured parts, split by kind.+ *+ * An attachment and a pasted block are the same thing to a bill: both are+ * replayed on every later turn and both can be the largest thing in a request.+ * The trace could not tell them apart, because `describeTurnInput` summarizes+ * structured parts only when the turn has no typed text, and nothing described+ * the history at all.+ *+ * Kind and size only, never content, for the same reason `describeTurnInput`+ * gives: the content itself already reaches the child generations.+ *+ * Run this on the messages that are about to be converted, after the history+ * guards. An attachment they turned into a placeholder is a text part by then+ * and is correctly not counted, so this reports the weight the guards left+ * rather than what the conversation holds.+ *+ * It cannot be taken any later than that: `truncateMessages` runs on converted+ * messages, where a pasted block is already indistinguishable from any other+ * text, so the kinds this reports no longer exist there. A turn that reached+ * that last resort therefore carries less than this says, and is flagged with+ * `contextWindowTruncated` so the two cases are never confused.+ */+export function summarizeCarriedContext(+ messages: UIMessage[]+): Record<string, number> | undefined {+ let attachments = 0+ let attachmentTokens = 0+ let pastedChars = 0+ let quotedChars = 0+ let noteChars = 0++ for (const message of messages) {+ for (const part of message.parts) {+ if (isFilePart(part)) {+ attachments += 1+ attachmentTokens += estimateAttachmentTokens(part)+ continue+ }++ const text = (part as { data?: { text?: unknown } }).data?.text+ if (typeof text !== 'string') continue++ if (part.type === 'data-pastedContent') pastedChars += text.length+ if (part.type === 'data-quotedContext') quotedChars += text.length+ if (part.type === 'data-noteContext') noteChars += text.length+ }+ }++ const summary = {+ ...(attachments > 0 && { attachments }),+ ...(attachmentTokens > 0 && { attachmentTokens }),+ ...(pastedChars > 0 && { pastedChars }),+ ...(quotedChars > 0 && { quotedChars }),+ ...(noteChars > 0 && { noteChars })+ }++ return Object.keys(summary).length > 0 ? summary : undefined+}