chatgpt.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package chatgpt
  2. import (
  3. "context"
  4. "net/http"
  5. "net/url"
  6. "time"
  7. "github.com/eryajf/chatgpt-dingtalk/public"
  8. openai "github.com/sashabaranov/go-openai"
  9. )
  10. type ChatGPT struct {
  11. client *openai.Client
  12. ctx context.Context
  13. userId string
  14. maxQuestionLen int
  15. maxText int
  16. maxAnswerLen int
  17. timeOut time.Duration // 超时时间, 0表示不超时
  18. doneChan chan struct{}
  19. cancel func()
  20. ChatContext *ChatContext
  21. }
  22. func New(userId string) *ChatGPT {
  23. var ctx context.Context
  24. var cancel func()
  25. // public.Config.BaseURL, public.Config.ApiKey, public.Config.HttpProxy
  26. if public.Config.SessionTimeout == 0 {
  27. ctx, cancel = context.WithCancel(context.Background())
  28. } else {
  29. ctx, cancel = context.WithTimeout(context.Background(), public.Config.SessionTimeout)
  30. }
  31. timeOutChan := make(chan struct{}, 1)
  32. go func() {
  33. <-ctx.Done()
  34. timeOutChan <- struct{}{} // 发送超时信号,或是提示结束,用于聊天机器人场景,配合GetTimeOutChan() 使用
  35. }()
  36. config := openai.DefaultConfig(public.Config.ApiKey)
  37. if public.Config.HttpProxy != "" {
  38. config.HTTPClient.Transport = &http.Transport{
  39. // 设置代理
  40. Proxy: func(req *http.Request) (*url.URL, error) {
  41. return url.Parse(public.Config.HttpProxy)
  42. }}
  43. }
  44. if public.Config.BaseURL != "" {
  45. config.BaseURL = public.Config.BaseURL + "/v1"
  46. }
  47. return &ChatGPT{
  48. client: openai.NewClientWithConfig(config),
  49. ctx: ctx,
  50. userId: userId,
  51. maxQuestionLen: 2048, // 最大问题长度
  52. maxAnswerLen: 2048, // 最大答案长度
  53. maxText: 4096, // 最大文本 = 问题 + 回答, 接口限制
  54. timeOut: public.Config.SessionTimeout,
  55. doneChan: timeOutChan,
  56. cancel: func() {
  57. cancel()
  58. },
  59. ChatContext: NewContext(),
  60. }
  61. }
  62. func (c *ChatGPT) Close() {
  63. c.cancel()
  64. }
  65. func (c *ChatGPT) GetDoneChan() chan struct{} {
  66. return c.doneChan
  67. }
  68. func (c *ChatGPT) SetMaxQuestionLen(maxQuestionLen int) int {
  69. if maxQuestionLen > c.maxText-c.maxAnswerLen {
  70. maxQuestionLen = c.maxText - c.maxAnswerLen
  71. }
  72. c.maxQuestionLen = maxQuestionLen
  73. return c.maxQuestionLen
  74. }