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

assistantStreaming.ts

124 lines4.8 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​
84export function makeAssistantStreamingFilter(mode: ResponseStreamingMode) {
85 const delivered = new Map<string, { text: string; at: number }>();
86 return (
87 event: ProviderAdapter.ProviderAdapterV2Event,
88 now: number,
89 ): ProviderAdapter.ProviderAdapterV2Event | null => {
90 if (
91 event.type === "node.updated" &&
92 event.node.kind === "assistant_message" &&
93 event.node.status === "running"
94 )
95 return null;
96 const message =
97 event.type === "message.updated" && event.message.role === "assistant"
98 ? event.message
99 : event.type === "turn_item.updated" &&
100 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
101 ? event.turnItem
102 : null;
103 if (!message) return event;
104 const key = `${event.type}:${message.id}`;
105 if (!message.streaming) {
106 delivered.delete(key);
107 return event;
108 }
109 if (mode === "turn") return null;
110 const previous = delivered.get(key);
111 if (previous && now - previous.at < 400) return null;
112 const { ready } = splitBufferedAssistantText(message.text);
113 if (!ready || ready === previous?.text) return null;
114 delivered.set(key, { text: ready, at: now });
115 if (event.type === "message.updated")
116 return { ...event, message: { ...event.message, text: ready } };
117 if (
118 event.type === "turn_item.updated" &&
119 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
120 )
121 return { ...event, turnItem: { ...event.turnItem, text: ready } };
122 return event;
123 };