Skip to content

Commit 6758ec4

Browse files
Streaming support (#61)
* Add streaming support feature (#54) * Add streaming support feature removes golangci linting deprecation warnings See: [Issue #49](#49) * remove dead token * Remove the goroutines from previous implementation Set up separate test and file for streaming support Add client code under cmd dir * Supress CI errors Need to update import path to test under feature/streaming-support branch * suppress linting errors --------- Co-authored-by: sashabaranov <[email protected]> * remove main.go * remove code duplication * use int64 * finalize streaming support * lint * fix tests --------- Co-authored-by: e. alvarez <[email protected]>
1 parent 3695eb3 commit 6758ec4

File tree

4 files changed

+296
-1
lines changed

4 files changed

+296
-1
lines changed

README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,51 @@ func main() {
3838
fmt.Println(resp.Choices[0].Text)
3939
}
4040
```
41+
42+
Streaming response example:
43+
44+
```go
45+
package main
46+
47+
import (
48+
"errors"
49+
"context"
50+
"fmt"
51+
"io"
52+
gogpt "github.com/sashabaranov/go-gpt3"
53+
)
54+
55+
func main() {
56+
c := gogpt.NewClient("your token")
57+
ctx := context.Background()
58+
59+
req := gogpt.CompletionRequest{
60+
Model: gogpt.GPT3Ada,
61+
MaxTokens: 5,
62+
Prompt: "Lorem ipsum",
63+
Stream: true,
64+
}
65+
stream, err := c.CreateCompletionStream(ctx, req)
66+
if err != nil {
67+
return
68+
}
69+
defer stream.Close()
70+
71+
for {
72+
response, err := stream.Recv()
73+
if errors.Is(err, io.EOF) {
74+
fmt.Println("Stream finished")
75+
return
76+
}
77+
78+
if err != nil {
79+
fmt.Printf("Stream error: %v\n", err)
80+
return
81+
}
82+
83+
84+
fmt.Printf("Stream response: %v\n", response)
85+
86+
}
87+
}
88+
```

api_test.go

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"context"
66
"encoding/json"
7+
"errors"
78
"fmt"
89
"io"
910
"log"
@@ -19,7 +20,7 @@ import (
1920
)
2021

2122
const (
22-
testAPIToken = "this-is-my-secure-token-do-not-steal!!"
23+
testAPIToken = "this-is-my-secure-token-do-not-steal!"
2324
)
2425

2526
func TestAPI(t *testing.T) {
@@ -64,6 +65,33 @@ func TestAPI(t *testing.T) {
6465
if err != nil {
6566
t.Fatalf("Embedding error: %v", err)
6667
}
68+
69+
stream, err := c.CreateCompletionStream(ctx, CompletionRequest{
70+
Prompt: "Ex falso quodlibet",
71+
Model: GPT3Ada,
72+
MaxTokens: 5,
73+
Stream: true,
74+
})
75+
if err != nil {
76+
t.Errorf("CreateCompletionStream returned error: %v", err)
77+
}
78+
defer stream.Close()
79+
80+
counter := 0
81+
for {
82+
_, err = stream.Recv()
83+
if err != nil {
84+
if errors.Is(err, io.EOF) {
85+
break
86+
}
87+
t.Errorf("Stream error: %v", err)
88+
} else {
89+
counter++
90+
}
91+
}
92+
if counter == 0 {
93+
t.Error("Stream did not return any responses")
94+
}
6795
}
6896

6997
// TestCompletions Tests the completions endpoint of the API using the mocked server.
@@ -272,6 +300,7 @@ func handleCompletionEndpoint(w http.ResponseWriter, r *http.Request) {
272300
http.Error(w, "could not read request", http.StatusInternalServerError)
273301
return
274302
}
303+
275304
res := CompletionResponse{
276305
ID: strconv.Itoa(int(time.Now().Unix())),
277306
Object: "test-object",
@@ -281,6 +310,7 @@ func handleCompletionEndpoint(w http.ResponseWriter, r *http.Request) {
281310
// would be required / wouldn't make much sense
282311
Model: completionReq.Model,
283312
}
313+
284314
// create completions
285315
for i := 0; i < completionReq.N; i++ {
286316
// generate a random string of length completionReq.Length

stream.go

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
package gogpt
2+
3+
import (
4+
"bufio"
5+
"bytes"
6+
"context"
7+
"encoding/json"
8+
"errors"
9+
"fmt"
10+
"io"
11+
"net/http"
12+
)
13+
14+
type CompletionStream struct {
15+
reader *bufio.Reader
16+
response *http.Response
17+
}
18+
19+
func (stream *CompletionStream) Recv() (response CompletionResponse, err error) {
20+
waitForData:
21+
line, err := stream.reader.ReadBytes('\n')
22+
if err != nil {
23+
if errors.Is(err, io.EOF) {
24+
return
25+
}
26+
}
27+
28+
var headerData = []byte("data: ")
29+
line = bytes.TrimSpace(line)
30+
if !bytes.HasPrefix(line, headerData) {
31+
goto waitForData
32+
}
33+
34+
line = bytes.TrimPrefix(line, headerData)
35+
if string(line) == "[DONE]" {
36+
return
37+
}
38+
39+
err = json.Unmarshal(line, &response)
40+
return
41+
}
42+
43+
func (stream *CompletionStream) Close() {
44+
stream.response.Body.Close()
45+
}
46+
47+
// CreateCompletionStream — API call to create a completion w/ streaming
48+
// support. It sets whether to stream back partial progress. If set, tokens will be
49+
// sent as data-only server-sent events as they become available, with the
50+
// stream terminated by a data: [DONE] message.
51+
func (c *Client) CreateCompletionStream(
52+
ctx context.Context,
53+
request CompletionRequest,
54+
) (stream *CompletionStream, err error) {
55+
request.Stream = true
56+
reqBytes, err := json.Marshal(request)
57+
if err != nil {
58+
return
59+
}
60+
61+
urlSuffix := "/completions"
62+
req, err := http.NewRequest("POST", c.fullURL(urlSuffix), bytes.NewBuffer(reqBytes))
63+
req.Header.Set("Content-Type", "application/json")
64+
req.Header.Set("Accept", "text/event-stream")
65+
req.Header.Set("Cache-Control", "no-cache")
66+
req.Header.Set("Connection", "keep-alive")
67+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.authToken))
68+
if err != nil {
69+
return
70+
}
71+
72+
req = req.WithContext(ctx)
73+
resp, err := c.HTTPClient.Do(req) //nolint:bodyclose // body is closed in stream.Close()
74+
if err != nil {
75+
return
76+
}
77+
78+
stream = &CompletionStream{
79+
reader: bufio.NewReader(resp.Body),
80+
response: resp,
81+
}
82+
return
83+
}

stream_test.go

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
package gogpt_test
2+
3+
import (
4+
"context"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
9+
. "github.com/sashabaranov/go-gpt3"
10+
)
11+
12+
func TestCreateCompletionStream(t *testing.T) {
13+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14+
w.Header().Set("Content-Type", "text/event-stream")
15+
16+
// Send test responses
17+
dataBytes := []byte{}
18+
dataBytes = append(dataBytes, []byte("event: message\n")...)
19+
//nolint:lll
20+
data := `{"id":"1","object":"completion","created":1598069254,"model":"text-davinci-002","choices":[{"text":"response1","finish_reason":"max_tokens"}]}`
21+
dataBytes = append(dataBytes, []byte("data: "+data+"\n\n")...)
22+
23+
dataBytes = append(dataBytes, []byte("event: message\n")...)
24+
//nolint:lll
25+
data = `{"id":"2","object":"completion","created":1598069255,"model":"text-davinci-002","choices":[{"text":"response2","finish_reason":"max_tokens"}]}`
26+
dataBytes = append(dataBytes, []byte("data: "+data+"\n\n")...)
27+
28+
dataBytes = append(dataBytes, []byte("event: done\n")...)
29+
dataBytes = append(dataBytes, []byte("data: [DONE]\n\n")...)
30+
31+
_, err := w.Write(dataBytes)
32+
if err != nil {
33+
t.Errorf("Write error: %s", err)
34+
}
35+
}))
36+
defer server.Close()
37+
38+
// Client portion of the test
39+
client := NewClient(testAPIToken)
40+
ctx := context.Background()
41+
client.BaseURL = server.URL + "/v1"
42+
43+
request := CompletionRequest{
44+
Prompt: "Ex falso quodlibet",
45+
Model: "text-davinci-002",
46+
MaxTokens: 10,
47+
Stream: true,
48+
}
49+
50+
client.HTTPClient.Transport = &tokenRoundTripper{
51+
testAPIToken,
52+
http.DefaultTransport,
53+
}
54+
55+
stream, err := client.CreateCompletionStream(ctx, request)
56+
if err != nil {
57+
t.Errorf("CreateCompletionStream returned error: %v", err)
58+
}
59+
defer stream.Close()
60+
61+
expectedResponses := []CompletionResponse{
62+
{
63+
ID: "1",
64+
Object: "completion",
65+
Created: 1598069254,
66+
Model: "text-davinci-002",
67+
Choices: []CompletionChoice{{Text: "response1", FinishReason: "max_tokens"}},
68+
},
69+
{
70+
ID: "2",
71+
Object: "completion",
72+
Created: 1598069255,
73+
Model: "text-davinci-002",
74+
Choices: []CompletionChoice{{Text: "response2", FinishReason: "max_tokens"}},
75+
},
76+
{},
77+
}
78+
79+
for ix, expectedResponse := range expectedResponses {
80+
receivedResponse, streamErr := stream.Recv()
81+
if streamErr != nil {
82+
t.Errorf("stream.Recv() failed: %v", streamErr)
83+
}
84+
if !compareResponses(expectedResponse, receivedResponse) {
85+
t.Errorf("Stream response %v is %v, expected %v", ix, receivedResponse, expectedResponse)
86+
}
87+
}
88+
}
89+
90+
// A "tokenRoundTripper" is a struct that implements the RoundTripper
91+
// interface, specifically to handle the authentication token by adding a token
92+
// to the request header. We need this because the API requires that each
93+
// request include a valid API token in the headers for authentication and
94+
// authorization.
95+
type tokenRoundTripper struct {
96+
token string
97+
fallback http.RoundTripper
98+
}
99+
100+
// RoundTrip takes an *http.Request as input and returns an
101+
// *http.Response and an error.
102+
//
103+
// It is expected to use the provided request to create a connection to an HTTP
104+
// server and return the response, or an error if one occurred. The returned
105+
// Response should have its Body closed. If the RoundTrip method returns an
106+
// error, the Client's Get, Head, Post, and PostForm methods return the same
107+
// error.
108+
func (t *tokenRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
109+
req.Header.Set("Authorization", "Bearer "+t.token)
110+
return t.fallback.RoundTrip(req)
111+
}
112+
113+
// Helper funcs.
114+
func compareResponses(r1, r2 CompletionResponse) bool {
115+
if r1.ID != r2.ID || r1.Object != r2.Object || r1.Created != r2.Created || r1.Model != r2.Model {
116+
return false
117+
}
118+
if len(r1.Choices) != len(r2.Choices) {
119+
return false
120+
}
121+
for i := range r1.Choices {
122+
if !compareResponseChoices(r1.Choices[i], r2.Choices[i]) {
123+
return false
124+
}
125+
}
126+
return true
127+
}
128+
129+
func compareResponseChoices(c1, c2 CompletionChoice) bool {
130+
if c1.Text != c2.Text || c1.FinishReason != c2.FinishReason {
131+
return false
132+
}
133+
return true
134+
}

0 commit comments

Comments
 (0)