lmcli/pkg/cli/openai.go

68 lines
1.6 KiB
Go
Raw Normal View History

package cli
2023-10-30 15:23:07 -06:00
import (
"context"
2023-10-30 15:45:21 -06:00
"errors"
"io"
2023-11-04 16:56:22 -06:00
2023-10-30 15:23:07 -06:00
openai "github.com/sashabaranov/go-openai"
)
2023-11-05 11:29:57 -07:00
func CreateChatCompletionRequest(messages []Message, maxTokens int) openai.ChatCompletionRequest {
chatCompletionMessages := []openai.ChatCompletionMessage{}
2023-11-04 16:56:22 -06:00
for _, m := range messages {
chatCompletionMessages = append(chatCompletionMessages, openai.ChatCompletionMessage{
2023-11-04 16:56:22 -06:00
Role: m.Role,
2023-10-30 15:23:07 -06:00
Content: m.OriginalContent,
})
}
2023-11-05 11:29:57 -07:00
return openai.ChatCompletionRequest{
Model: openai.GPT3Dot5Turbo,
2023-11-04 16:56:22 -06:00
Messages: chatCompletionMessages,
2023-11-05 11:29:57 -07:00
MaxTokens: maxTokens,
}
}
2023-11-05 11:19:30 -07:00
// CreateChatCompletion submits a Chat Completion API request and returns the
// response.
2023-11-05 11:29:57 -07:00
func CreateChatCompletion(messages []Message, maxTokens int) (string, error) {
client := openai.NewClient(config.OpenAI.APIKey)
2023-11-05 11:29:57 -07:00
req := CreateChatCompletionRequest(messages, maxTokens)
resp, err := client.CreateChatCompletion(context.Background(), req)
2023-10-30 15:23:07 -06:00
if err != nil {
return "", err
2023-10-30 15:23:07 -06:00
}
return resp.Choices[0].Message.Content, nil
}
2023-10-30 15:45:21 -06:00
2023-11-05 11:19:30 -07:00
// CreateChatCompletionStream submits a streaming Chat Completion API request
// and streams the received response to the provided output channel.
2023-11-05 11:29:57 -07:00
func CreateChatCompletionStream(messages []Message, maxTokens int, output chan string) error {
client := openai.NewClient(config.OpenAI.APIKey)
2023-11-05 11:29:57 -07:00
req := CreateChatCompletionRequest(messages, maxTokens)
2023-10-30 15:45:21 -06:00
defer close(output)
2023-11-05 11:29:57 -07:00
stream, err := client.CreateChatCompletionStream(context.Background(), req)
2023-10-30 15:45:21 -06:00
if err != nil {
return err
}
defer stream.Close()
for {
response, err := stream.Recv()
if errors.Is(err, io.EOF) {
return nil
}
if err != nil {
return err
}
output <- response.Choices[0].Delta.Content
2023-10-30 15:45:21 -06:00
}
}