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

assistantStreaming.ts

91 lines3.7 KB

1import type { ResponseStreamingMode } from "@t3tools/contracts";
2import type { ProviderAdapterV2Event } from "./ProviderAdapter.ts";
3​
4// An opening fence may sit at any indentation, since fences inside list
5// items are indented past the marker. A closing fence may be indented at most
6// three spaces more than its opener. Deeper lines are content in the block.
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​
12/**
13 * Splits buffered assistant text at the last blank line or closing code fence
14 * that is not inside an open fenced code block. `ready` is safe to deliver now
15 * because the markdown before it will not change shape as more text arrives.
16 * `rest` stays buffered until the next boundary or completion. Only fully
17 * terminated lines count, so a trailing partial line never leaks.
18 */
19export function splitBufferedAssistantText(text: string): { ready: string; rest: string } {
20 let openFence: { marker: string; indent: number } | null = null;
21 let boundary = -1;
22 let lineStart = 0;
23 for (;;) {
24 const newline = text.indexOf("\n", lineStart);
25 if (newline === -1) {
26 break;
27 }
28 const line = text.slice(lineStart, newline).replace(/[ \t\r]+$/, "");
29 const fenceMatch = MARKDOWN_FENCE_PATTERN.exec(line);
30 if (fenceMatch) {
31 const indent = fenceMatch[1]!.length;
32 const marker = fenceMatch[2]!;
33 if (openFence === null) {
34 openFence = { marker, indent };
35 } else if (
36 marker[0] === openFence.marker[0] &&
37 marker.length >= openFence.marker.length &&
38 indent <= openFence.indent + 3 &&
39 line.length === indent + marker.length
40 ) {
41 // CommonMark: a closing fence carries no info string.
42 openFence = null;
43 boundary = newline + 1;
44 }
45 } else if (openFence === null && BLANK_LINE_PATTERN.test(line) && lineStart > 0) {
46 boundary = newline + 1;
47 }
48 lineStart = newline + 1;
49 }
50 if (boundary === -1) {
51 return { ready: "", rest: text };
52 }
53 return { ready: text.slice(0, boundary), rest: text.slice(boundary) };
55​
56/** Each adapter publishes cumulative text. Keep unfinished markdown out of the read model. */
57export function makeAssistantStreamingFilter(mode: ResponseStreamingMode) {
58 const delivered = new Map<string, { text: string; at: number }>();
59 return (event: ProviderAdapterV2Event, now: number): ProviderAdapterV2Event | null => {
60 if (mode === "token") return event;
61 if (
62 event.type === "node.updated" &&
63 event.node.kind === "assistant_message" &&
64 event.node.status === "running"
65 )
66 return null;
67 const message =
68 event.type === "message.updated" && event.message.role === "assistant"
69 ? event.message
70 : event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
71 ? event.turnItem
72 : null;
73 if (!message) return event;
74 const key = `${event.type}:${message.id}`;
75 if (!message.streaming) {
76 delivered.delete(key);
77 return event;
78 }
79 if (mode === "turn") return null;
80 const previous = delivered.get(key);
81 if (previous && now - previous.at < 400) return null;
82 const { ready } = splitBufferedAssistantText(message.text);
83 if (!ready || ready === previous?.text) return null;
84 delivered.set(key, { text: ready, at: now });
85 if (event.type === "message.updated")
86 return { ...event, message: { ...event.message, text: ready } };
87 if (event.type === "turn_item.updated" && event.turnItem.type === "assistant_message")
88 return { ...event, turnItem: { ...event.turnItem, text: ready } };
89 return event;
90 };