chatgpt.go 2.1 KB

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