Skip to content

Commit 825d90d

Browse files
committed
perf(executor): stop re-parsing the whole structured output on every streamed token
When a chat selects a response-format field, StreamingResponseFormatProcessor re-ran JSON.parse on the whole buffer for every token delta, then scanned it twice more with brace-count regexes, so CPU per response grew with the square of the output length. Text can only parse to an object once it ends in `}` or `]`, so parse only then. The brace-count branch re-parsed the same `buffer.trim()` that had just failed or yielded a non-object, so it could never return a result and is removed.
1 parent 0ea25f4 commit 825d90d

1 file changed

Lines changed: 7 additions & 27 deletions

File tree

‎apps/sim/executor/utils.ts‎

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ export class StreamingResponseFormatProcessor {
5050
): ReadableStream {
5151
let buffer = ''
5252
let hasProcessedComplete = false
53+
let endsWithBracket = false
5354

5455
const self = this
5556

@@ -73,7 +74,12 @@ export class StreamingResponseFormatProcessor {
7374
const chunk = decoder.decode(value, { stream: true })
7475
buffer += chunk
7576

76-
if (!hasProcessedComplete) {
77+
// Only text ending in `}` or `]` can parse to an object, so skip re-parsing
78+
// the whole buffer on every other token: that made each stream quadratic.
79+
const trimmedChunk = chunk.trimEnd()
80+
if (trimmedChunk) endsWithBracket = /[}\]]$/.test(trimmedChunk)
81+
82+
if (!hasProcessedComplete && endsWithBracket) {
7783
const processedChunk = self.processStreamingChunk(buffer, selectedFields)
7884

7985
if (processedChunk) {
@@ -114,32 +120,6 @@ export class StreamingResponseFormatProcessor {
114120
}
115121
} catch {}
116122

117-
const openBraces = (buffer.match(/\{/g) || []).length
118-
const closeBraces = (buffer.match(/\}/g) || []).length
119-
120-
if (openBraces > 0 && openBraces === closeBraces) {
121-
try {
122-
const parsed = JSON.parse(buffer.trim())
123-
if (typeof parsed === 'object' && parsed !== null) {
124-
const results: string[] = []
125-
for (const field of selectedFields) {
126-
if (field in parsed) {
127-
const value = parsed[field]
128-
const formattedValue = typeof value === 'string' ? value : JSON.stringify(value)
129-
results.push(formattedValue)
130-
}
131-
}
132-
133-
if (results.length > 0) {
134-
const result = results.join('\n')
135-
return result
136-
}
137-
138-
return null
139-
}
140-
} catch {}
141-
}
142-
143123
return null
144124
}
145125

0 commit comments

Comments
 (0)