chat sends the conversation to the server, prints the assistant's reply to stdout (streaming if requested) and returns the final assembled content so the caller can append it to the history.
( ctx context.Context, client *openai.Client, model string, history []openai.ChatCompletionMessageParamUnion, stream bool, )
| 128 | // to stdout (streaming if requested) and returns the final assembled |
| 129 | // content so the caller can append it to the history. |
| 130 | func chat( |
| 131 | ctx context.Context, |
| 132 | client *openai.Client, |
| 133 | model string, |
| 134 | history []openai.ChatCompletionMessageParamUnion, |
| 135 | stream bool, |
| 136 | ) (string, error) { |
| 137 | params := openai.ChatCompletionNewParams{ |
| 138 | Model: model, |
| 139 | Messages: history, |
| 140 | } |
| 141 | |
| 142 | if !stream { |
| 143 | resp, err := client.Chat.Completions.New(ctx, params) |
| 144 | if err != nil { |
| 145 | return "", err |
| 146 | } |
| 147 | if len(resp.Choices) == 0 { |
| 148 | return "", errors.New("server returned no choices") |
| 149 | } |
| 150 | content := resp.Choices[0].Message.Content |
| 151 | fmt.Println(content) |
| 152 | return content, nil |
| 153 | } |
| 154 | |
| 155 | s := client.Chat.Completions.NewStreaming(ctx, params) |
| 156 | var b strings.Builder |
| 157 | for s.Next() { |
| 158 | chunk := s.Current() |
| 159 | if len(chunk.Choices) == 0 { |
| 160 | continue |
| 161 | } |
| 162 | delta := chunk.Choices[0].Delta.Content |
| 163 | if delta == "" { |
| 164 | continue |
| 165 | } |
| 166 | fmt.Print(delta) |
| 167 | b.WriteString(delta) |
| 168 | } |
| 169 | if err := s.Err(); err != nil && !errors.Is(err, io.EOF) { |
| 170 | return "", err |
| 171 | } |
| 172 | fmt.Println() |
| 173 | return b.String(), nil |
| 174 | } |