Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assistantStreaming.ts

138 lines5.4 KB

1import type { ResponseStreamingMode } from "@t3tools/contracts";
2import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
3​
4// An opening fence may sit at any indentation, since fences inside list items
5// are indented past the marker. A closing fence may be indented at most three
6// spaces more than its opener.
7const MARKDOWN_FENCE_PATTERN = /^( *)(`{3,}|~{3,})/;
8// CommonMark blank lines hold only spaces and tabs. Other whitespace, such as
9// a no-break space, is paragraph content.
10const BLANK_LINE_PATTERN = /^[ \t]*$/;
11// The trailing space is required, so a partial `-` or `1.` never matches before
12// the model finishes the marker.
13const LIST_ITEM_START_PATTERN = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]/;
14const SECTION_TITLE_PATTERN = /^ {0,3}(?:#{1,6}(?:[ \t]|$)|\*\*(?:[^*]|\*(?!\*))+\*\*:?$)/;
15// An unindented ATX heading ends the paragraph or list above it, even with no
16// blank line between them. A bold line would continue the paragraph instead.
17const TOP_LEVEL_HEADING_PATTERN = /^#{1,6}(?:[ \t]|$)/;
18​
19/**
20 * Only fully terminated lines count, so a trailing partial line never leaks; a
21 * list item start is the one lookahead that may sit on the partial line, since
22 * tight lists have no blank lines between items and would otherwise land all at
23 * once.
24 *
25 * A section title holds the boundary until a content line follows it, so a
26 * title never lands alone and waits above a block that is still streaming.
27 */
28export function splitBufferedAssistantText(text: string): { ready: string; rest: string } {
29 let openFence: { marker: string; indent: number } | null = null;
30 let boundary = -1;
31 let lineStart = 0;
32 let titleAwaitingContent = false;
33 for (;;) {
34 const newline = text.indexOf("\n", lineStart);
35 const line = text
36 .slice(lineStart, newline === -1 ? text.length : newline)
37 .replace(/[ \t\r]+$/, "");
38 if (
39 openFence === null &&
40 lineStart > 0 &&
41 !titleAwaitingContent &&
42 LIST_ITEM_START_PATTERN.test(line)
43 ) {
44 boundary = lineStart;
45 }
46 if (newline === -1) {
47 break;
48 }
49 const fenceMatch = MARKDOWN_FENCE_PATTERN.exec(line);
50 if (fenceMatch) {
51 const indent = fenceMatch[1]!.length;
52 const marker = fenceMatch[2]!;
53 if (openFence === null) {
54 openFence = { marker, indent };
55 titleAwaitingContent = false;
56 } else if (
57 marker[0] === openFence.marker[0] &&
58 marker.length >= openFence.marker.length &&
59 indent <= openFence.indent + 3 &&
60 line.length === indent + marker.length
61 ) {
62 // CommonMark: a closing fence carries no info string.
63 openFence = null;
64 boundary = newline + 1;
65 }
66 } else if (openFence === null && BLANK_LINE_PATTERN.test(line) && lineStart > 0) {
67 if (!titleAwaitingContent) {
68 boundary = newline + 1;
69 }
70 } else if (openFence === null) {
71 if (lineStart > 0 && !titleAwaitingContent && TOP_LEVEL_HEADING_PATTERN.test(line)) {
72 boundary = lineStart;
73 }
74 titleAwaitingContent = SECTION_TITLE_PATTERN.test(line);
75 }
76 lineStart = newline + 1;
77 }
78 if (boundary === -1) {
79 return { ready: "", rest: text };
80 }
81 return { ready: text.slice(0, boundary), rest: text.slice(boundary) };
83​
84// Each passed snapshot is a durable event holding the full text, so paragraph
85// streaming would store bytes growing with the square of the length. Past this
86// length a snapshot that extends the last passes only once it is a quarter
87// longer, keeping the stored total within a few times the final text.
88const SNAPSHOT_GROWTH_START_LENGTH = 8_000;
89const SNAPSHOT_GROWTH_FACTOR = 1.25;
90​
91export function makeAssistantStreamingFilter(mode: ResponseStreamingMode) {
92 const delivered = new Map<string, { text: string; at: number }>();
93 return (
94 event: ProviderAdapter.ProviderAdapterV2Event,
95 now: number,
96 ): ProviderAdapter.ProviderAdapterV2Event | null => {
97 if (
98 event.type === "node.updated" &&
99 event.node.kind === "assistant_message" &&
100 event.node.status === "running"
101 )
102 return null;
103 const message =
104 event.type === "message.updated" && event.message.role === "assistant"
105 ? event.message
106 : event.type === "turn_item.updated" &&
107 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
108 ? event.turnItem
109 : null;
110 if (!message) return event;
111 const key = `${event.type}:${message.id}`;
112 if (!message.streaming) {
113 delivered.delete(key);
114 return event;
115 }
116 if (mode === "turn") return null;
117 const previous = delivered.get(key);
118 if (previous && now - previous.at < 400) return null;
119 const { ready } = splitBufferedAssistantText(message.text);
120 if (!ready || ready === previous?.text) return null;
121 if (
122 previous &&
123 previous.text.length >= SNAPSHOT_GROWTH_START_LENGTH &&
124 ready.length < previous.text.length * SNAPSHOT_GROWTH_FACTOR &&
125 ready.startsWith(previous.text)
126 )
127 return null;
128 delivered.set(key, { text: ready, at: now });
129 if (event.type === "message.updated")
130 return { ...event, message: { ...event.message, text: ready } };
131 if (
132 event.type === "turn_item.updated" &&
133 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
134 )
135 return { ...event, turnItem: { ...event.turnItem, text: ready } };
136 return event;
137 };