chatgpt.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. if public.Config.SessionTimeout == 0 {
  26. ctx, cancel = context.WithCancel(context.Background())
  27. } else {
  28. ctx, cancel = context.WithTimeout(context.Background(), public.Config.SessionTimeout)
  29. }
  30. timeOutChan := make(chan struct{}, 1)
  31. go func() {
  32. <-ctx.Done()
  33. timeOutChan <- struct{}{} // 发送超时信号,或是提示结束,用于聊天机器人场景,配合GetTimeOutChan() 使用
  34. }()
  35. config := openai.DefaultConfig(public.Config.ApiKey)
  36. if public.Config.HttpProxy != "" {
  37. config.HTTPClient.Transport = &http.Transport{
  38. // 设置代理
  39. Proxy: func(req *http.Request) (*url.URL, error) {
  40. return url.Parse(public.Config.HttpProxy)
  41. }}
  42. }
  43. if public.Config.BaseURL != "" {
  44. config.BaseURL = public.Config.BaseURL + "/v1"
  45. }
  46. return &ChatGPT{
  47. client: openai.NewClientWithConfig(config),
  48. ctx: ctx,
  49. userId: userId,
  50. maxQuestionLen: 2048, // 最大问题长度
  51. maxAnswerLen: 2048, // 最大答案长度
  52. maxText: 4096, // 最大文本 = 问题 + 回答, 接口限制
  53. timeOut: public.Config.SessionTimeout,
  54. doneChan: timeOutChan,
  55. cancel: func() {
  56. cancel()
  57. },
  58. ChatContext: NewContext(),
  59. }
  60. }
  61. func (c *ChatGPT) Close() {
  62. c.cancel()
  63. }
  64. func (c *ChatGPT) GetDoneChan() chan struct{} {
  65. return c.doneChan
  66. }
  67. func (c *ChatGPT) SetMaxQuestionLen(maxQuestionLen int) int {
  68. if maxQuestionLen > c.maxText-c.maxAnswerLen {
  69. maxQuestionLen = c.maxText - c.maxAnswerLen
  70. }
  71. c.maxQuestionLen = maxQuestionLen
  72. return c.maxQuestionLen
  73. }