export.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package chatgpt
  2. import (
  3. "context"
  4. "time"
  5. "github.com/avast/retry-go"
  6. "github.com/eryajf/chatgpt-dingtalk/pkg/logger"
  7. "github.com/eryajf/chatgpt-dingtalk/public"
  8. )
  9. // SingleQa 单聊
  10. func SingleQa(question, userId string) (answer string, err error) {
  11. chat := New(userId)
  12. defer chat.Close()
  13. // 定义一个重试策略
  14. retryStrategy := []retry.Option{
  15. retry.Delay(100 * time.Millisecond),
  16. retry.Attempts(3),
  17. retry.LastErrorOnly(true),
  18. }
  19. // 使用重试策略进行重试
  20. err = retry.Do(
  21. func() error {
  22. answer, err = chat.ChatWithContext(question)
  23. if err != nil {
  24. return err
  25. }
  26. return nil
  27. },
  28. retryStrategy...)
  29. return
  30. }
  31. // ContextQa 串聊
  32. func ContextQa(question, userId string) (chat *ChatGPT, answer string, err error) {
  33. chat = New(userId)
  34. if public.UserService.GetUserSessionContext(userId) != "" {
  35. err := chat.ChatContext.LoadConversation(userId)
  36. if err != nil {
  37. logger.Warning("load station failed: %v\n", err)
  38. }
  39. }
  40. retryStrategy := []retry.Option{
  41. retry.Delay(100 * time.Millisecond),
  42. retry.Attempts(3),
  43. retry.LastErrorOnly(true)}
  44. // 使用重试策略进行重试
  45. err = retry.Do(
  46. func() error {
  47. answer, err = chat.ChatWithContext(question)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. },
  53. retryStrategy...)
  54. return
  55. }
  56. // ImageQa 生成图片
  57. func ImageQa(ctx context.Context, question, userId string) (answer string, err error) {
  58. chat := New(userId)
  59. defer chat.Close()
  60. // 定义一个重试策略
  61. retryStrategy := []retry.Option{
  62. retry.Delay(100 * time.Millisecond),
  63. retry.Attempts(3),
  64. retry.LastErrorOnly(true),
  65. }
  66. // 使用重试策略进行重试
  67. err = retry.Do(
  68. func() error {
  69. answer, err = chat.GenreateImage(ctx, question)
  70. if err != nil {
  71. return err
  72. }
  73. return nil
  74. },
  75. retryStrategy...)
  76. return
  77. }