kimi.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. package kimi
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "git.ttmylife.com/zeuszhao/llm"
  7. "github.com/go-rod/rod"
  8. "github.com/go-rod/rod/lib/launcher"
  9. "github.com/go-rod/rod/lib/proto"
  10. "time"
  11. )
  12. type Kimi struct {
  13. userContext *llm.UserContext
  14. browser *rod.Browser
  15. launcher *launcher.Launcher
  16. loginEvent func(ctx context.Context, bytes []byte) error
  17. loginCallback func(ctx context.Context, user *llm.UserContext) error
  18. }
  19. func (k *Kimi) WithLoginEvent(f func(ctx context.Context, bytes []byte) error) llm.UserBrowserAgent {
  20. k.loginEvent = f
  21. return k
  22. }
  23. func (k *Kimi) WithLoginCallback(f func(ctx context.Context, user *llm.UserContext) error) llm.UserBrowserAgent {
  24. k.loginCallback = f
  25. return k
  26. }
  27. func (k *Kimi) WithUserContext(user *llm.UserContext) llm.UserBrowserAgent {
  28. k.userContext = user
  29. return k
  30. }
  31. func (k *Kimi) IsLogin(ctx context.Context, page *rod.Page) (bool, error) {
  32. _, err := page.Timeout(3 * time.Second).Element("div[data-testid='msh-header-user-avatar']")
  33. if err != nil && !errors.Is(err, context.DeadlineExceeded) {
  34. return false, err
  35. }
  36. if errors.Is(err, context.DeadlineExceeded) {
  37. return false, nil
  38. }
  39. return true, nil
  40. }
  41. func (k *Kimi) Login(ctx context.Context, page *rod.Page) error {
  42. loginEle, err := page.Element("div[data-testid='msh-sidebar-user']")
  43. if err != nil {
  44. return err
  45. }
  46. err = loginEle.Click(proto.InputMouseButtonLeft, 1)
  47. if err != nil {
  48. return err
  49. }
  50. qrcodePreEle, err := page.ElementR("div p", "微信扫码登录")
  51. if err != nil {
  52. return err
  53. }
  54. qrcodeBox, err := qrcodePreEle.Parent()
  55. if err != nil {
  56. return err
  57. }
  58. screenshot, err := qrcodeBox.Screenshot(proto.PageCaptureScreenshotFormatPng, 10)
  59. if err != nil {
  60. return err
  61. }
  62. err = k.loginEvent(ctx, screenshot)
  63. if err != nil {
  64. return err
  65. }
  66. _, err = page.Element("div[data-testid='msh-header-user-avatar']")
  67. if err != nil {
  68. return err
  69. }
  70. localStorage := page.MustEval(`k => Object.assign({}, window.localStorage)`).Map()
  71. localStorageMap := make(map[string]string)
  72. for k, v := range localStorage {
  73. localStorageMap[k] = v.String()
  74. }
  75. err = k.loginCallback(ctx, llm.NewUserContext().WithLocalStorage(k.GetName(), localStorageMap).WithCookies(k.GetName(), proto.CookiesToParams(page.MustCookies())))
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. func (k *Kimi) GetName() string {
  82. return "kimi"
  83. }
  84. func (k *Kimi) NewChat(ctx context.Context) (llm.Chat, error) {
  85. c := &Chat{
  86. ai: k,
  87. Page: k.browser.Context(ctx).MustIncognito().MustPage(),
  88. qaSingle: make(chan bool),
  89. }
  90. wait := c.Page.MustWaitNavigation()
  91. // hook
  92. router := c.Page.HijackRequests()
  93. router.MustAdd("*.mp4", func(hijack *rod.Hijack) {
  94. if hijack.Request.Type() == proto.NetworkResourceTypeMedia {
  95. hijack.Response.Fail(proto.NetworkErrorReasonBlockedByClient)
  96. return
  97. }
  98. hijack.ContinueRequest(&proto.FetchContinueRequest{})
  99. })
  100. router.MustAdd("*/completion/stream", func(hijack *rod.Hijack) {
  101. hijack.MustLoadResponse()
  102. c.qaSingle <- true
  103. })
  104. go router.Run()
  105. err := c.Page.Navigate("https://kimi.moonshot.cn/")
  106. if err != nil {
  107. return nil, err
  108. }
  109. if k.userContext != nil {
  110. localStorage, ok := k.userContext.LocalStorage[k.GetName()]
  111. if ok {
  112. for key, val := range localStorage {
  113. c.Page.MustEval(fmt.Sprintf("() => {window.localStorage.setItem('%s','%s')}", key, val))
  114. }
  115. }
  116. }
  117. wait()
  118. return c, nil
  119. }
  120. func (k *Kimi) Close(ctx context.Context) error {
  121. k.launcher.Kill()
  122. return nil
  123. }
  124. func (k *Kimi) Init(ctx context.Context, debug bool) (llm.AI, error) {
  125. path, ok := launcher.LookPath()
  126. if !ok {
  127. return nil, errors.New("浏览器未找到")
  128. }
  129. launcherHandler := launcher.New().
  130. Bin(path).
  131. HeadlessNew(!debug).
  132. Set("disable-gpu").
  133. Devtools(debug)
  134. browser := rod.New().ControlURL(launcherHandler.MustLaunch()).MustConnect()
  135. return &Kimi{
  136. browser: browser,
  137. launcher: launcherHandler,
  138. }, nil
  139. }
  140. func NewKimi() llm.AI {
  141. return &Kimi{}
  142. }