-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathstream-summary.ts
More file actions
147 lines (130 loc) · 4.45 KB
/
Copy pathstream-summary.ts
File metadata and controls
147 lines (130 loc) · 4.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import { JSONPath } from 'jsonpath-plus';
const stringifyValue = (value: unknown): string | null => {
if (value === null || value === undefined) {
return null;
}
if (typeof value === 'string') {
return value;
}
if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
return String(value);
}
return JSON.stringify(value);
};
export const extractStreamValueAtPath = (payload: string, keyPath: string): string | null => {
try {
const parsed = JSON.parse(payload);
const path = keyPath.trim();
const result = JSONPath({ path, json: parsed });
if (Array.isArray(result)) {
// An empty array means the path matched nothing at all (as opposed to matching a
// field whose value happens to be an empty string), so it's treated the same as
// a null/undefined result rather than joined into an empty-but-present fragment.
if (result.length === 0) {
return null;
}
return result
.map(stringifyValue)
.filter((value): value is string => value !== null)
.join('');
}
return stringifyValue(result);
} catch {
return null;
}
};
export const computeStreamSummary = (
payloads: string[],
keyPath: string,
): { fragmentCount: number; summary: string } => {
const fragments = payloads
.map(payload => extractStreamValueAtPath(payload, keyPath))
.filter((value): value is string => value !== null);
return { fragmentCount: fragments.length, summary: fragments.join('') };
};
const STANDARD_SSE_FIELD = /^(event|id|retry):/i;
export function candidateJsonPayloadsFromSseText(text: string): string[] {
const normalized = text.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
const blocks = normalized.split(/\n{2,}/);
const candidates: string[] = [];
for (const block of blocks) {
const lines = block.split('\n');
const dataLines = lines
.map(line => /^data:(?: ?)(.*)$/.exec(line)?.[1])
.filter((line): line is string => line != null);
if (dataLines.length > 0) {
const payload = dataLines.join('\n').trim();
if (payload) {
candidates.push(payload);
}
continue;
}
const trimmedBlock = block.trim();
if (!trimmedBlock) {
continue;
}
if (isParsableJson(trimmedBlock)) {
candidates.push(trimmedBlock);
continue;
}
for (const line of lines) {
const trimmedLine = line.trim();
if (
!trimmedLine ||
trimmedLine.startsWith(':') ||
STANDARD_SSE_FIELD.test(trimmedLine) ||
!isParsableJson(trimmedLine)
) {
continue;
}
candidates.push(trimmedLine);
}
}
return candidates;
}
function isParsableJson(value: string): boolean {
try {
JSON.parse(value);
return true;
} catch {
return false;
}
}
export interface StreamMessageEvent {
type: string;
direction: string;
data: string;
}
export function getCandidatePayloadsFromEvents(events: StreamMessageEvent[], protocol: 'curl' | 'webSocket'): string[] {
// Both curl's and websocket's findMany() reverse the event log for "latest event
// first" display, so undo that exact reversal here (rather than sort by timestamp,
// which has only millisecond resolution and can't disambiguate SSE chunks that arrive
// within the same millisecond) to get back true chronological order.
const incoming = events.filter(event => event.type === 'message' && event.direction === 'INCOMING').reverse();
if (protocol === 'curl') {
return candidateJsonPayloadsFromSseText(incoming.map(event => event.data).join(''));
}
return incoming.map(event => event.data);
}
const PATH_TO_JSONPATH: { pathname: string; jsonPath: string }[] = [
// OpenAI: Chat Completions API
{ pathname: '/v1/chat/completions', jsonPath: '$.choices[0].delta.content' },
// OpenAI: Completions API, Legacy
{ pathname: '/v1/completions', jsonPath: '$.choices[0].text' },
// OpenAI Responses API
{ pathname: '/v1/responses', jsonPath: '$.delta' },
// Anthropic Claude Messages API
{ pathname: '/v1/messages', jsonPath: '$.delta.text' },
];
export const inferStreamSummaryPath = (url: string): string | null => {
try {
const { pathname } = new URL(url);
if (pathname.toLowerCase().includes(':streamgeneratecontent')) {
return '$.candidates[0].content.parts[0].text';
}
const match = PATH_TO_JSONPATH.find(entry => entry.pathname === pathname);
return match ? match.jsonPath : null;
} catch {
return null;
}
};