Skip to content

Commit 2dc1162

Browse files
committed
add token buffer for openai api
1 parent 6bfea1b commit 2dc1162

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

app_chatbot.go

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"strings"
1515
"sydneyqt/sydney"
1616
"sydneyqt/util"
17+
"time"
1718
)
1819

1920
const (
@@ -216,17 +217,18 @@ func (a *App) askOpenAI(options AskOptions) {
216217
ErrType: "",
217218
ErrMsg: "",
218219
}
220+
chatFinish := func() {
221+
slog.Info("invoke EventChatFinish", "result", chatFinishResult)
222+
runtime.EventsEmit(a.ctx, EventChatFinish, chatFinishResult)
223+
}
219224
handleErr := func(err error) {
220225
chatFinishResult = ChatFinishResult{
221226
Success: false,
222227
ErrType: ChatFinishResultErrTypeOthers,
223228
ErrMsg: err.Error(),
224229
}
230+
chatFinish()
225231
}
226-
defer func() {
227-
slog.Info("invoke EventChatFinish", "result", chatFinishResult)
228-
runtime.EventsEmit(a.ctx, EventChatFinish, chatFinishResult)
229-
}()
230232
stopCtx, cancel := context.WithCancel(context.Background())
231233
runtime.EventsOn(a.ctx, EventChatStop, func(optionalData ...interface{}) {
232234
slog.Info("Received EventChatStop")
@@ -288,10 +290,30 @@ func (a *App) askOpenAI(options AskOptions) {
288290
handleErr(err)
289291
return
290292
}
291-
runtime.EventsEmit(a.ctx, EventConversationCreated)
292293
defer stream.Close()
293-
fullMessage := ""
294+
runtime.EventsEmit(a.ctx, EventConversationCreated)
295+
chatAppendBuffChan := make(chan string, 128)
296+
defer close(chatAppendBuffChan)
297+
fullMessage := bytes.Buffer{}
294298
replied := false
299+
go func() {
300+
lastFlushTime := time.Now()
301+
textBuf := bytes.Buffer{}
302+
flush := func() {
303+
runtime.EventsEmit(a.ctx, EventChatAppend, textBuf.String())
304+
runtime.EventsEmit(a.ctx, EventChatToken, a.CountToken(fullMessage.String()))
305+
lastFlushTime = time.Now()
306+
textBuf.Reset()
307+
}
308+
for text := range chatAppendBuffChan {
309+
textBuf.WriteString(text)
310+
if time.Since(lastFlushTime) >= 200*time.Millisecond {
311+
flush()
312+
}
313+
}
314+
flush()
315+
chatFinish()
316+
}()
295317
for {
296318
select {
297319
case <-stopCtx.Done():
@@ -315,13 +337,12 @@ func (a *App) askOpenAI(options AskOptions) {
315337
continue
316338
}
317339
textToAppend := response.Choices[0].Delta.Content
318-
fullMessage += textToAppend
319-
runtime.EventsEmit(a.ctx, EventChatToken, a.CountToken(fullMessage))
340+
fullMessage.WriteString(textToAppend)
320341
if !replied {
321342
textToAppend = "[assistant](#message)\n" + textToAppend
322343
replied = true
323344
}
324-
runtime.EventsEmit(a.ctx, EventChatAppend, textToAppend)
345+
chatAppendBuffChan <- textToAppend
325346
}
326347
}
327348
func (a *App) AskAI(options AskOptions) {

0 commit comments

Comments
 (0)