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

assistantStreaming.ts

111 lines4.2 KB

1import type { ResponseStreamingMode } from "@t3tools/contracts";
2import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
3​
4// List fences can open at any indentation; closers may be at most three spaces deeper.
5const MARKDOWN_FENCE_PATTERN = /^( *)(`{3,}|~{3,})/;
6// CommonMark blank lines contain only spaces and tabs.
7const BLANK_LINE_PATTERN = /^[ \t]*$/;
8// Require trailing space so partial list markers cannot match during streaming.
9const LIST_ITEM_START_PATTERN = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]/;
10const SECTION_TITLE_PATTERN = /^ {0,3}(?:#{1,6}(?:[ \t]|$)|\*\*(?:[^*]|\*(?!\*))+\*\*:?$)/;
11// Unindented ATX headings end preceding paragraphs and lists without blank lines; bold lines do not.
12const TOP_LEVEL_HEADING_PATTERN = /^#{1,6}(?:[ \t]|$)/;
13​
14/** Emit terminated lines only, except partial list-start lookahead for tight lists. Hold section titles until content follows. */
15export function splitBufferedAssistantText(text: string): { ready: string; rest: string } {
16 let openFence: { marker: string; indent: number } | null = null;
17 let boundary = -1;
18 let lineStart = 0;
19 let titleAwaitingContent = false;
20 for (;;) {
21 const newline = text.indexOf("\n", lineStart);
22 const line = text
23 .slice(lineStart, newline === -1 ? text.length : newline)
24 .replace(/[ \t\r]+$/, "");
25 if (
26 openFence === null &&
27 lineStart > 0 &&
28 !titleAwaitingContent &&
29 LIST_ITEM_START_PATTERN.test(line)
30 ) {
31 boundary = lineStart;
32 }
33 if (newline === -1) {
34 break;
35 }
36 const fenceMatch = MARKDOWN_FENCE_PATTERN.exec(line);
37 if (fenceMatch) {
38 const indent = fenceMatch[1]!.length;
39 const marker = fenceMatch[2]!;
40 if (openFence === null) {
41 openFence = { marker, indent };
42 titleAwaitingContent = false;
43 } else if (
44 marker[0] === openFence.marker[0] &&
45 marker.length >= openFence.marker.length &&
46 indent <= openFence.indent + 3 &&
47 line.length === indent + marker.length
48 ) {
49 // CommonMark: a closing fence carries no info string.
50 openFence = null;
51 boundary = newline + 1;
52 }
53 } else if (openFence === null && BLANK_LINE_PATTERN.test(line) && lineStart > 0) {
54 if (!titleAwaitingContent) {
55 boundary = newline + 1;
56 }
57 } else if (openFence === null) {
58 if (lineStart > 0 && !titleAwaitingContent && TOP_LEVEL_HEADING_PATTERN.test(line)) {
59 boundary = lineStart;
60 }
61 titleAwaitingContent = SECTION_TITLE_PATTERN.test(line);
62 }
63 lineStart = newline + 1;
64 }
65 if (boundary === -1) {
66 return { ready: "", rest: text };
67 }
68 return { ready: text.slice(0, boundary), rest: text.slice(boundary) };
70​
71export function makeAssistantStreamingFilter(mode: ResponseStreamingMode) {
72 const delivered = new Map<string, { text: string; at: number }>();
73 return (
74 event: ProviderAdapter.ProviderAdapterV2Event,
75 now: number,
76 ): ProviderAdapter.ProviderAdapterV2Event | null => {
77 if (
78 event.type === "node.updated" &&
79 event.node.kind === "assistant_message" &&
80 event.node.status === "running"
81 )
82 return null;
83 const message =
84 event.type === "message.updated" && event.message.role === "assistant"
85 ? event.message
86 : event.type === "turn_item.updated" &&
87 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
88 ? event.turnItem
89 : null;
90 if (!message) return event;
91 const key = `${event.type}:${message.id}`;
92 if (!message.streaming) {
93 delivered.delete(key);
94 return event;
95 }
96 if (mode === "turn") return null;
97 const previous = delivered.get(key);
98 if (previous && now - previous.at < 400) return null;
99 const { ready } = splitBufferedAssistantText(message.text);
100 if (!ready || ready === previous?.text) return null;
101 delivered.set(key, { text: ready, at: now });
102 if (event.type === "message.updated")
103 return { ...event, message: { ...event.message, text: ready } };
104 if (
105 event.type === "turn_item.updated" &&
106 (event.turnItem.type === "assistant_message" || event.turnItem.type === "reasoning")
107 )
108 return { ...event, turnItem: { ...event.turnItem, text: ready } };
109 return event;
110 };