Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions common/src/util/__tests__/stop-sequence.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { expect, test } from 'bun:test'

import { StopSequenceHandler } from '../stop-sequence'

test('stops at the earliest sequence regardless of configuration order or chunking', () => {
const text = 'answer<EARLY>hidden<LATE>tail'
for (const stops of [
['<LATE>', '<EARLY>'],
['<EARLY>', '<LATE>'],
]) {
for (let split = 0; split <= text.length; split++) {
const handler = new StopSequenceHandler(stops)
const first = handler.process(text.slice(0, split))
const second = handler.process(text.slice(split))
expect((first.text ?? '') + (second.text ?? '') + handler.flush()).toBe(
'answer',
)
expect(second.endOfStream).toBe(true)
expect(handler.process('more output')).toEqual({
text: null,
endOfStream: true,
})
}
}
})
16 changes: 10 additions & 6 deletions common/src/util/stop-sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ export class StopSequenceHandler {
this.buffer += text
let longestOverlap = ''

let stopIndex = -1
for (const stopSequence of this.stopSequences) {
const index = this.buffer.indexOf(stopSequence)
if (index !== -1) {
this.finished = true
return {
text: this.buffer.slice(0, index),
endOfStream: true,
}
if (index !== -1 && (stopIndex === -1 || index < stopIndex)) {
stopIndex = index
}
}
if (stopIndex !== -1) {
this.finished = true
return {
text: this.buffer.slice(0, stopIndex),
endOfStream: true,
}
}

Expand Down
Loading