Skip to content

Commit

Permalink
refactor: simplify streaming code (#67)
Browse files Browse the repository at this point in the history
Co-authored-by: Eric Jizba <erijiz@microsoft.com>
  • Loading branch information
sinedied and ejizba authored May 8, 2024
1 parent 47f1894 commit b781d2c
Showing 1 changed file with 17 additions and 28 deletions.
45 changes: 17 additions & 28 deletions packages/api/src/functions/chat-post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,9 @@ export async function postChat(request: HttpRequest, context: InvocationContext)
const responseStream = await chain.stream({
input: lastUserMessage,
});
const jsonStream = Readable.from(createJsonStream(responseStream));

return data(createStream(responseStream), {
return data(jsonStream, {
'Content-Type': 'application/x-ndjson',
'Transfer-Encoding': 'chunked',
});
Expand All @@ -106,33 +107,21 @@ export async function postChat(request: HttpRequest, context: InvocationContext)
}

// Transform the response chunks into a JSON stream
function createStream(chunks: AsyncIterable<{ context: Document[]; answer: string }>) {
const buffer = new Readable({
read() {},
});

const stream = async () => {
for await (const chunk of chunks) {
if (!chunk.answer) continue;

const responseChunk: AIChatCompletionDelta = {
delta: {
content: chunk.answer,
role: 'assistant',
},
};

// Format response chunks in Newline delimited JSON
// see https://github.com/ndjson/ndjson-spec
buffer.push(JSON.stringify(responseChunk) + '\n');
}

buffer.push(null);
};

stream();

return buffer;
async function* createJsonStream(chunks: AsyncIterable<{ context: Document[]; answer: string }>) {
for await (const chunk of chunks) {
if (!chunk.answer) continue;

const responseChunk: AIChatCompletionDelta = {
delta: {
content: chunk.answer,
role: 'assistant',
},
};

// Format response chunks in Newline delimited JSON
// see https://github.com/ndjson/ndjson-spec
yield JSON.stringify(responseChunk) + '\n';
}
}

app.setup({ enableHttpStream: true });
Expand Down

0 comments on commit b781d2c

Please sign in to comment.