chatgpt.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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.AzureOn {
  37. config = openai.DefaultAzureConfig(
  38. public.Config.AzureOpenAIToken,
  39. "https://"+public.Config.AzureResourceName+".openai."+
  40. "azure.com/",
  41. public.Config.AzureDeploymentName,
  42. )
  43. } else {
  44. if public.Config.HttpProxy != "" {
  45. config.HTTPClient.Transport = &http.Transport{
  46. // 设置代理
  47. Proxy: func(req *http.Request) (*url.URL, error) {
  48. return url.Parse(public.Config.HttpProxy)
  49. }}
  50. }
  51. if public.Config.BaseURL != "" {
  52. config.BaseURL = public.Config.BaseURL + "/v1"
  53. }
  54. }
  55. return &ChatGPT{
  56. client: openai.NewClientWithConfig(config),
  57. ctx: ctx,
  58. userId: userId,
  59. maxQuestionLen: 2048, // 最大问题长度
  60. maxAnswerLen: 2048, // 最大答案长度
  61. maxText: 4096, // 最大文本 = 问题 + 回答, 接口限制
  62. timeOut: public.Config.SessionTimeout,
  63. doneChan: timeOutChan,
  64. cancel: func() {
  65. cancel()
  66. },
  67. ChatContext: NewContext(),
  68. }
  69. }
  70. func (c *ChatGPT) Close() {
  71. c.cancel()
  72. }
  73. func (c *ChatGPT) GetDoneChan() chan struct{} {
  74. return c.doneChan
  75. }
  76. func (c *ChatGPT) SetMaxQuestionLen(maxQuestionLen int) int {
  77. if maxQuestionLen > c.maxText-c.maxAnswerLen {
  78. maxQuestionLen = c.maxText - c.maxAnswerLen
  79. }
  80. c.maxQuestionLen = maxQuestionLen
  81. return c.maxQuestionLen
  82. }