@@ -14,6 +14,7 @@ import (
14
14
"strings"
15
15
"sydneyqt/sydney"
16
16
"sydneyqt/util"
17
+ "time"
17
18
)
18
19
19
20
const (
@@ -216,17 +217,18 @@ func (a *App) askOpenAI(options AskOptions) {
216
217
ErrType : "" ,
217
218
ErrMsg : "" ,
218
219
}
220
+ chatFinish := func () {
221
+ slog .Info ("invoke EventChatFinish" , "result" , chatFinishResult )
222
+ runtime .EventsEmit (a .ctx , EventChatFinish , chatFinishResult )
223
+ }
219
224
handleErr := func (err error ) {
220
225
chatFinishResult = ChatFinishResult {
221
226
Success : false ,
222
227
ErrType : ChatFinishResultErrTypeOthers ,
223
228
ErrMsg : err .Error (),
224
229
}
230
+ chatFinish ()
225
231
}
226
- defer func () {
227
- slog .Info ("invoke EventChatFinish" , "result" , chatFinishResult )
228
- runtime .EventsEmit (a .ctx , EventChatFinish , chatFinishResult )
229
- }()
230
232
stopCtx , cancel := context .WithCancel (context .Background ())
231
233
runtime .EventsOn (a .ctx , EventChatStop , func (optionalData ... interface {}) {
232
234
slog .Info ("Received EventChatStop" )
@@ -288,10 +290,30 @@ func (a *App) askOpenAI(options AskOptions) {
288
290
handleErr (err )
289
291
return
290
292
}
291
- runtime .EventsEmit (a .ctx , EventConversationCreated )
292
293
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 {}
294
298
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
+ }()
295
317
for {
296
318
select {
297
319
case <- stopCtx .Done ():
@@ -315,13 +337,12 @@ func (a *App) askOpenAI(options AskOptions) {
315
337
continue
316
338
}
317
339
textToAppend := response .Choices [0 ].Delta .Content
318
- fullMessage += textToAppend
319
- runtime .EventsEmit (a .ctx , EventChatToken , a .CountToken (fullMessage ))
340
+ fullMessage .WriteString (textToAppend )
320
341
if ! replied {
321
342
textToAppend = "[assistant](#message)\n " + textToAppend
322
343
replied = true
323
344
}
324
- runtime . EventsEmit ( a . ctx , EventChatAppend , textToAppend )
345
+ chatAppendBuffChan <- textToAppend
325
346
}
326
347
}
327
348
func (a * App ) AskAI (options AskOptions ) {
0 commit comments