Skip to content
Merged
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
23 changes: 23 additions & 0 deletions sdks/nodejs-client/src/http/sse.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,29 @@ describe('sse parsing', () => {
expect(text).toBe('hello')
})

it('toText collects text_chunk events from workflow streams', async () => {
const stream = Readable.from([
'data: {"event":"workflow_started","data":{"id":"run"}}\n\n',
'data: {"event":"text_chunk","data":{"text":"Hello","from_variable_selector":["llm","text"]}}\n\n',
'data: {"event":"reasoning_chunk","data":{"text":"thinking"}}\n\n',
'data: {"event":"text_chunk","data":{"text":" world"}}\n\n',
'data: {"event":"workflow_finished","data":{"outputs":{"text":"Hello world"}}}\n\n',
])
const text = await createSseStream(stream, { status: 200, headers: {} }).toText()
expect(text).toBe('Hello world')
})

it('toText replaces streamed text on message_replace', async () => {
const stream = Readable.from([
'data: {"event":"message","answer":"unsafe "}\n\n',
'data: {"event":"message","answer":"output"}\n\n',
'data: {"event":"message_replace","answer":"Sorry, I cannot answer that.","reason":"output_moderation"}\n\n',
'data: {"event":"message_end","id":"msg"}\n\n',
])
const text = await createSseStream(stream, { status: 200, headers: {} }).toText()
expect(text).toBe('Sorry, I cannot answer that.')
})

it('toText returns empty for invalid data', async () => {
const stream = Readable.from(['data: null\n\n', 'data: 123\n\n'])
const sseStream = createSseStream(stream, { status: 200, headers: {} })
Expand Down
9 changes: 9 additions & 0 deletions sdks/nodejs-client/src/http/sse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ const extractTextFromEvent = (data: unknown): string => {
if (!isRecord(data)) {
return ''
}
// Workflow apps stream their text output as `text_chunk` events, which nest it under `data`.
if (data.event === 'text_chunk') {
return isRecord(data.data) && typeof data.data.text === 'string' ? data.data.text : ''
}
if (typeof data.answer === 'string') {
return data.answer
}
Expand Down Expand Up @@ -120,6 +124,11 @@ export const createSseStream = <T>(
toText: async () => {
let text = ''
for await (const event of iterable) {
// Output moderation sends `message_replace` with the full answer that replaces everything streamed so far.
if (isRecord(event.data) && event.data.event === 'message_replace') {
text = typeof event.data.answer === 'string' ? event.data.answer : ''
continue
}
text += extractTextFromEvent(event.data)
}
return text
Expand Down
Loading