Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve handling of streamed data in chat #64

Merged
merged 1 commit into from
Jun 30, 2024
Merged
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
18 changes: 11 additions & 7 deletions frontend/src/components/Teams/ChatTeam.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -299,17 +299,21 @@ const ChatTeam = () => {
const reader = res.body.getReader()
let done = false
let buffer = "" // Buffer to accumulate chunks
const textDecoder = new TextDecoder()

while (!done) {
const { done: streamDone, value } = await reader.read()
done = streamDone
if (!done) {
buffer = new TextDecoder().decode(value)
const chunks = buffer.split("\n\n")
for (const chunk of chunks) {
if (chunk === "") continue
// Extract and parse the complete JSON string
const jsonStr = chunk.trim().slice(6) // Remove 'data: ' prefix
if (done) continue

buffer += textDecoder.decode(value, { stream: true })

const lines = buffer.split("\n")
buffer = lines.pop() || "" // Keep the last incomplete line in the buffer

for (const line of lines) {
if (line.startsWith("data: ")) {
const jsonStr = line.slice(6).trim() // Remove 'data: ' prefix
try {
const parsed = JSON.parse(jsonStr)
const newMessages: Message[] = []
Expand Down