Quellcode durchsuchen

add Reverse: for v0.0.3

tags/v0.0.3
DengBiao vor 1 Jahr
Ursprung
Commit
0a73929a2e
2 geänderte Dateien mit 61 neuen und 1 gelöschten Zeilen
  1. +24
    -1
      go-gpt3/chat.go
  2. +37
    -0
      go-gpt3/stream.go

+ 24
- 1
go-gpt3/chat.go Datei anzeigen

@@ -41,6 +41,24 @@ type ChatCompletionChoice struct {
FinishReason string `json:"finish_reason"`
}

type ChatCompletionChoiceForStream struct {
Index int `json:"index"`
Delta struct {
Content string `json:"content"`
} `json:"delta"`
FinishReason string `json:"finish_reason"`
}

// ChatCompletionResponseForStream represents a response structure for chat completion API.
type ChatCompletionResponseForStream struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []ChatCompletionChoiceForStream `json:"choices"`
Usage Usage `json:"usage"`
}

// ChatCompletionResponse represents a response structure for chat completion API.
type ChatCompletionResponse struct {
ID string `json:"id"`
@@ -81,8 +99,13 @@ func (c *Client) CreateChatCompletion(
// CreateChatCompletionStream — API call to create a completion w/ streaming
func (c *Client) CreateChatCompletionStream(
ctx context.Context,
request CompletionRequest,
request ChatCompletionRequest,
) (stream *CompletionStream, err error) {
model := request.Model
if model != GPT3Dot5Turbo0301 && model != GPT3Dot5Turbo {
err = ErrChatCompletionInvalidModel
return
}
request.Stream = true
reqBytes, err := json.Marshal(request)
if err != nil {


+ 37
- 0
go-gpt3/stream.go Datei anzeigen

@@ -60,6 +60,43 @@ waitForData:
return
}

func (stream *CompletionStream) ChatRecv() (response ChatCompletionResponseForStream, err error) {
if stream.isFinished {
err = io.EOF
return
}

var emptyMessagesCount uint

waitForData:
line, err := stream.reader.ReadBytes('\n')
if err != nil {
return
}

var headerData = []byte("data: ")
line = bytes.TrimSpace(line)
if !bytes.HasPrefix(line, headerData) {
emptyMessagesCount++
if emptyMessagesCount > stream.emptyMessagesLimit {
err = ErrTooManyEmptyStreamMessages
return
}

goto waitForData
}

line = bytes.TrimPrefix(line, headerData)
if string(line) == "[DONE]" {
stream.isFinished = true
err = io.EOF
return
}

err = json.Unmarshal(line, &response)
return
}

func (stream *CompletionStream) Close() {
stream.response.Body.Close()
}


Laden…
Abbrechen
Speichern