kimi.go 3.9 KB

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