tgbot_misaka_5882f7/openai/client.go

40 lines
791 B
Go

package openai
import (
"time"
"github.com/go-errors/errors"
"github.com/go-resty/resty/v2"
)
type Client struct {
rest *resty.Client
}
func NewClient(apiKey string) *Client {
cli := resty.New().
SetBaseURL("https://api.openai.com").
SetHeader("Authorization", "Bearer "+apiKey).
SetTimeout(30 * time.Second)
return &Client{rest: cli}
}
func (c *Client) ChatCompletion(request ChatRequest) (*ChatResponse, error) {
resp, err := c.rest.R().
SetBody(request).
SetHeader("Content-Type", "application/json").
SetResult(&ChatResponse{}).
Post(ChatAPIPath)
if err != nil {
return nil, errors.Wrap(err, 0)
}
if resp.StatusCode() != 200 {
return nil, errors.Errorf("unexpected status code: %d", resp.StatusCode())
}
return resp.Result().(*ChatResponse), nil
}