kimi.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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, user *llm.UserContext) (llm.Chat, error) {
  82. c := &Chat{
  83. ai: k,
  84. userContext: user,
  85. Page: k.browser.Context(ctx).MustIncognito().MustPage(),
  86. qaSingle: make(chan bool),
  87. }
  88. wait := c.Page.MustWaitNavigation()
  89. // hook
  90. router := c.Page.HijackRequests()
  91. router.MustAdd("*.mp4", func(hijack *rod.Hijack) {
  92. if hijack.Request.Type() == proto.NetworkResourceTypeMedia {
  93. hijack.Response.Fail(proto.NetworkErrorReasonBlockedByClient)
  94. return
  95. }
  96. hijack.ContinueRequest(&proto.FetchContinueRequest{})
  97. })
  98. router.MustAdd("*/completion/stream", func(hijack *rod.Hijack) {
  99. hijack.MustLoadResponse()
  100. c.qaSingle <- true
  101. })
  102. go router.Run()
  103. err := c.Page.Navigate("https://kimi.moonshot.cn/")
  104. if err != nil {
  105. return nil, err
  106. }
  107. if c.userContext != nil {
  108. localStorage, ok := c.userContext.LocalStorage[k.GetName()]
  109. if ok {
  110. for key, val := range localStorage {
  111. c.Page.MustEval(fmt.Sprintf("() => {window.localStorage.setItem('%s','%s')}", key, val))
  112. }
  113. }
  114. }
  115. wait()
  116. return c, nil
  117. }
  118. func (k *Kimi) Close(ctx context.Context) error {
  119. k.launcher.Kill()
  120. return nil
  121. }
  122. func (k *Kimi) Init(ctx context.Context, debug bool) (llm.AI, error) {
  123. path, ok := launcher.LookPath()
  124. if !ok {
  125. return nil, errors.New("浏览器未找到")
  126. }
  127. launcherHandler := launcher.New().
  128. Bin(path).
  129. HeadlessNew(!debug).
  130. Set("disable-gpu").
  131. Devtools(debug)
  132. browser := rod.New().ControlURL(launcherHandler.MustLaunch()).MustConnect()
  133. return &Kimi{
  134. browser: browser,
  135. launcher: launcherHandler,
  136. }, nil
  137. }
  138. func NewKimi() llm.AI {
  139. return &Kimi{}
  140. }