add readme exmaple: chatgpt support context (#166)
This commit is contained in:
57
README.md
57
README.md
@@ -271,3 +271,60 @@ c := openai.NewClientWithConfig(config)
|
||||
|
||||
See also: https://pkg.go.dev/github.com/sashabaranov/go-openai#ClientConfig
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>ChatGPT support context</summary>
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
func main() {
|
||||
client := openai.NewClient("your token")
|
||||
messages := make([]openai.ChatCompletionMessage, 0)
|
||||
reader := bufio.NewReader(os.Stdin)
|
||||
fmt.Println("Conversation")
|
||||
fmt.Println("---------------------")
|
||||
|
||||
for {
|
||||
fmt.Print("-> ")
|
||||
text, _ := reader.ReadString('\n')
|
||||
// convert CRLF to LF
|
||||
text = strings.Replace(text, "\n", "", -1)
|
||||
messages = append(messages, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleUser,
|
||||
Content: text,
|
||||
})
|
||||
|
||||
resp, err := client.CreateChatCompletion(
|
||||
context.Background(),
|
||||
openai.ChatCompletionRequest{
|
||||
Model: openai.GPT3Dot5Turbo,
|
||||
Messages: messages,
|
||||
},
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("ChatCompletion error: %v\n", err)
|
||||
continue
|
||||
}
|
||||
|
||||
content := resp.Choices[0].Message.Content
|
||||
messages = append(messages, openai.ChatCompletionMessage{
|
||||
Role: openai.ChatMessageRoleAssistant,
|
||||
Content: content,
|
||||
})
|
||||
fmt.Println(content)
|
||||
}
|
||||
}
|
||||
```
|
||||
</details>
|
||||
Reference in New Issue
Block a user