-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.go
49 lines (42 loc) · 1.17 KB
/
chat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"context"
"time"
"github.com/PullRequestInc/go-gpt3"
)
type aiStreamInput struct {
Messages []gpt3.ChatCompletionRequestMessage
MaxTokens int
Temperature *float32
Model string
Timeout time.Duration
}
type chatCompletionStreamer interface {
// ChatCompletion creates a completion with the Chat completion endpoint which
// is what powers the ChatGPT experience.
ChatCompletionStream(ctx context.Context, request gpt3.ChatCompletionRequest, onData func(*gpt3.ChatCompletionStreamResponse) error) error
}
func aiStream(
ctx context.Context,
streamer chatCompletionStreamer,
input aiStreamInput,
handler func(message string) error,
) error {
timeout := 2 * time.Minute
if input.Timeout != 0 {
timeout = input.Timeout
}
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
err := streamer.ChatCompletionStream(ctx, gpt3.ChatCompletionRequest{
Messages: input.Messages,
MaxTokens: input.MaxTokens,
Temperature: input.Temperature,
Stream: true,
Model: input.Model,
}, func(cr *gpt3.ChatCompletionStreamResponse) error {
message := cr.Choices[0].Delta.Content
return handler(message)
})
return err
}