gpt.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package gpt
  2. import (
  3. "crypto/tls"
  4. "encoding/json"
  5. "fmt"
  6. "time"
  7. "github.com/eryajf/chatgpt-dingtalk/config"
  8. "github.com/eryajf/chatgpt-dingtalk/public/logger"
  9. "github.com/go-resty/resty/v2"
  10. )
  11. const BASEURL = "https://api.openai.com/v1/"
  12. // ChatGPTRequestBody 请求体
  13. type ChatGPTRequestBody struct {
  14. Model string `json:"model"`
  15. Prompt string `json:"prompt"`
  16. MaxTokens uint `json:"max_tokens"`
  17. Temperature float64 `json:"temperature"`
  18. }
  19. // ChatGPTResponseBody 响应体
  20. type ChatGPTResponseBody struct {
  21. ID string `json:"id"`
  22. Object string `json:"object"`
  23. Created int `json:"created"`
  24. Model string `json:"model"`
  25. Choices []ChoiceItem `json:"choices"`
  26. Usage map[string]interface{} `json:"usage"`
  27. }
  28. type ChoiceItem struct {
  29. Text string `json:"text"`
  30. Index int `json:"index"`
  31. Logprobs int `json:"logprobs"`
  32. FinishReason string `json:"finish_reason"`
  33. }
  34. // Completions gtp文本模型回复
  35. //curl https://api.openai.com/v1/completions
  36. //-H "Content-Type: application/json"
  37. //-H "Authorization: Bearer your chatGPT key"
  38. //-d '{"model": "text-davinci-003", "prompt": "give me good song", "temperature": 0, "max_tokens": 7}'
  39. func Completions(msg string) (string, error) {
  40. cfg := config.LoadConfig()
  41. requestBody := ChatGPTRequestBody{
  42. Model: cfg.Model,
  43. Prompt: msg,
  44. MaxTokens: cfg.MaxTokens,
  45. Temperature: cfg.Temperature,
  46. }
  47. client := resty.New().
  48. SetRetryCount(2).
  49. SetRetryWaitTime(1*time.Second).
  50. SetTimeout(cfg.SessionTimeout).
  51. SetHeader("Content-Type", "application/json").
  52. SetHeader("Authorization", "Bearer "+cfg.ApiKey).
  53. SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
  54. rsp, err := client.R().SetBody(requestBody).Post(BASEURL + "completions")
  55. if err != nil {
  56. return "", fmt.Errorf("request openai failed, err : %v", err)
  57. }
  58. if rsp.StatusCode() != 200 {
  59. return "", fmt.Errorf("gtp api status code not equals 200, code is %d ,details: %v ", rsp.StatusCode(), string(rsp.Body()))
  60. } else {
  61. logger.Info(fmt.Sprintf("response gtp json string : %v", string(rsp.Body())))
  62. }
  63. gptResponseBody := &ChatGPTResponseBody{}
  64. err = json.Unmarshal(rsp.Body(), gptResponseBody)
  65. if err != nil {
  66. return "", err
  67. }
  68. var reply string
  69. if len(gptResponseBody.Choices) > 0 {
  70. reply = gptResponseBody.Choices[0].Text
  71. }
  72. return reply, nil
  73. }