feat: add translate command

This commit is contained in:
Yiyang Kang 2023-03-08 02:28:26 +08:00
parent eecbaf18b3
commit 899491e867
Signed by: kkyy
GPG key ID: 80FD317ECAF06CC3
9 changed files with 236 additions and 9 deletions

39
openai/client.go Normal file
View file

@ -0,0 +1,39 @@
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
}