chatgpt.go 2.2 KB

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