2023-03-04 13:22:10 +03:00
|
|
|
package openai
|
|
|
|
|
|
|
|
import (
|
2023-03-08 14:37:50 +03:00
|
|
|
"bytes"
|
2023-03-04 13:22:10 +03:00
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"io"
|
|
|
|
"net/http"
|
2023-03-06 15:10:53 +03:00
|
|
|
"net/url"
|
2023-03-04 13:22:10 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type ChatCompletionMessage struct {
|
|
|
|
Role string `json:"role"`
|
|
|
|
Content string `json:"content"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type ChatCompletionChoice struct {
|
|
|
|
Message *ChatCompletionMessage `json:"message"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type ChatCompletionResponse struct {
|
2023-03-18 17:34:22 +03:00
|
|
|
Error any `json:"error"`
|
2023-03-04 13:22:10 +03:00
|
|
|
Model string `json:"model"`
|
|
|
|
Choices []ChatCompletionChoice `json:"choices"`
|
|
|
|
}
|
|
|
|
|
2023-03-18 17:07:14 +03:00
|
|
|
func PostChatCompletion(messages []ChatCompletionMessage, apiKey string, apiHost string) (string, error) {
|
2023-03-06 15:10:53 +03:00
|
|
|
if apiHost == "" {
|
|
|
|
apiHost = "https://api.openai.com"
|
|
|
|
}
|
|
|
|
url, err := url.JoinPath(apiHost, "/v1/chat/completions")
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
2023-03-18 17:34:22 +03:00
|
|
|
values := map[string]any{
|
2023-03-18 17:07:14 +03:00
|
|
|
"model": "gpt-3.5-turbo",
|
|
|
|
"messages": messages,
|
|
|
|
"max_tokens": 2000,
|
|
|
|
"temperature": 0,
|
|
|
|
"frequency_penalty": 0.0,
|
|
|
|
"presence_penalty": 0.0,
|
2023-03-08 14:37:50 +03:00
|
|
|
}
|
|
|
|
jsonValue, err := json.Marshal(values)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonValue))
|
2023-03-04 13:22:10 +03:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Set the API key in the request header
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
req.Header.Set("Authorization", "Bearer "+apiKey)
|
|
|
|
|
|
|
|
// Send the request to OpenAI's API
|
|
|
|
client := http.Client{}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
// Read the response body
|
|
|
|
responseBody, err := io.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
chatCompletionResponse := ChatCompletionResponse{}
|
|
|
|
err = json.Unmarshal(responseBody, &chatCompletionResponse)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
if chatCompletionResponse.Error != nil {
|
|
|
|
errorBytes, err := json.Marshal(chatCompletionResponse.Error)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return "", errors.New(string(errorBytes))
|
|
|
|
}
|
|
|
|
if len(chatCompletionResponse.Choices) == 0 {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
return chatCompletionResponse.Choices[0].Message.Content, nil
|
|
|
|
}
|