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

46
openai/chat.go Normal file
View file

@ -0,0 +1,46 @@
package openai
const ChatAPIPath = "/v1/chat/completions"
type ChatRole string
const (
ChatRoleSystem ChatRole = "system"
ChatRoleAssistant ChatRole = "assistant"
ChatRoleUser ChatRole = "user"
)
type ChatMessage struct {
Role ChatRole `json:"role"`
Content string `json:"content"`
}
type ChatRequest struct {
Model string `json:"model"`
Messages []ChatMessage `json:"messages"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
N int `json:"n,omitempty"`
Stream bool `json:"stream,omitempty"`
Stop []string `json:"stop,omitempty"`
MaxTokens int `json:"max_tokens,omitempty"`
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
LogitBias map[string]float64 `json:"logit_bias,omitempty"`
User string `json:"user,omitempty"`
}
type ChatResponseChoice struct {
Message ChatMessage `json:"message"`
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
}
type ChatResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Usage map[string]int `json:"usage"`
Choices []ChatResponseChoice `json:"choices"`
}

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
}

7
openai/models.go Normal file
View file

@ -0,0 +1,7 @@
package openai
const (
ModelTextDavinciEdit001 = "text-davinci-edit-001"
ModelGpt0305Turbo = "gpt-3.5-turbo"
ModelGpt0305Turbo0301 = "gpt-3.5-turbo-0301"
)

14
openai/prompts/prompts.go Normal file
View file

@ -0,0 +1,14 @@
package prompts
import "fmt"
func General() string {
return "You are a helpful assistant."
}
func Translate(targetLang string) string {
return fmt.Sprintf(
"You are a helpful assistant. Your task is to help translate the following text to %s. You should not interpret the text. You should structure the translated text to look natural in native %s, while keeping the meaning unchanged.",
targetLang, targetLang,
)
}