Add readme example of ChatGPT streaming completion (#177)
This commit is contained in:
57
README.md
57
README.md
@@ -58,6 +58,61 @@ func main() {
|
|||||||
|
|
||||||
Other examples:
|
Other examples:
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>ChatGPT streaming completion</summary>
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
openai "github.com/sashabaranov/go-openai"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
c := openai.NewClient("your token")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
req := openai.ChatCompletionRequest{
|
||||||
|
Model: openai.GPT3Dot5Turbo,
|
||||||
|
MaxTokens: 20,
|
||||||
|
Messages: []openai.ChatCompletionMessage{
|
||||||
|
{
|
||||||
|
Role: openai.ChatMessageRoleUser,
|
||||||
|
Content: "Lorem ipsum",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Stream: true,
|
||||||
|
}
|
||||||
|
stream, err := c.CreateChatCompletionStream(ctx, req)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("ChatCompletionStream error: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer stream.Close()
|
||||||
|
|
||||||
|
fmt.Printf("Stream response: ")
|
||||||
|
for {
|
||||||
|
response, err := stream.Recv()
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
fmt.Println("\nStream finished")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("\nStream error: %v\n", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf(response.Choices[0].Delta.Content)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>GPT-3 completion</summary>
|
<summary>GPT-3 completion</summary>
|
||||||
|
|
||||||
@@ -327,4 +382,4 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
</details>
|
</details>
|
||||||
|
|||||||
Reference in New Issue
Block a user