diff --git a/README.md b/README.md index 00cc9fe..e6e352e 100644 --- a/README.md +++ b/README.md @@ -271,3 +271,60 @@ c := openai.NewClientWithConfig(config) See also: https://pkg.go.dev/github.com/sashabaranov/go-openai#ClientConfig + +
+ChatGPT support context + +```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) + } +} +``` +
\ No newline at end of file