channel-test.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "one-api/common"
  12. "one-api/dto"
  13. "one-api/model"
  14. "one-api/relay"
  15. relaycommon "one-api/relay/common"
  16. "one-api/relay/constant"
  17. "one-api/service"
  18. "strconv"
  19. "sync"
  20. "time"
  21. "github.com/gin-gonic/gin"
  22. )
  23. func testChannel(channel *model.Channel, testModel string) (err error, openaiErr *dto.OpenAIError) {
  24. common.SysLog(fmt.Sprintf("testing channel %d with model %s", channel.Id, testModel))
  25. w := httptest.NewRecorder()
  26. c, _ := gin.CreateTestContext(w)
  27. c.Request = &http.Request{
  28. Method: "POST",
  29. URL: &url.URL{Path: "/v1/chat/completions"},
  30. Body: nil,
  31. Header: make(http.Header),
  32. }
  33. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  34. c.Request.Header.Set("Content-Type", "application/json")
  35. c.Set("channel", channel.Type)
  36. c.Set("base_url", channel.GetBaseURL())
  37. meta := relaycommon.GenRelayInfo(c)
  38. apiType := constant.ChannelType2APIType(channel.Type)
  39. adaptor := relay.GetAdaptor(apiType)
  40. if adaptor == nil {
  41. return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil
  42. }
  43. if testModel == "" {
  44. testModel = adaptor.GetModelList()[0]
  45. }
  46. request := buildTestRequest()
  47. adaptor.Init(meta, *request)
  48. request.Model = testModel
  49. meta.UpstreamModelName = testModel
  50. convertedRequest, err := adaptor.ConvertRequest(c, constant.RelayModeChatCompletions, request)
  51. if err != nil {
  52. return err, nil
  53. }
  54. jsonData, err := json.Marshal(convertedRequest)
  55. if err != nil {
  56. return err, nil
  57. }
  58. requestBody := bytes.NewBuffer(jsonData)
  59. c.Request.Body = io.NopCloser(requestBody)
  60. resp, err := adaptor.DoRequest(c, meta, requestBody)
  61. if err != nil {
  62. return err, nil
  63. }
  64. if resp.StatusCode != http.StatusOK {
  65. err := relaycommon.RelayErrorHandler(resp)
  66. return fmt.Errorf("status code %d: %s", resp.StatusCode, err.OpenAIError.Message), &err.OpenAIError
  67. }
  68. usage, respErr := adaptor.DoResponse(c, resp, meta)
  69. if respErr != nil {
  70. return fmt.Errorf("%s", respErr.OpenAIError.Message), &respErr.OpenAIError
  71. }
  72. if usage == nil {
  73. return errors.New("usage is nil"), nil
  74. }
  75. result := w.Result()
  76. // print result.Body
  77. respBody, err := io.ReadAll(result.Body)
  78. if err != nil {
  79. return err, nil
  80. }
  81. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  82. return nil, nil
  83. }
  84. func buildTestRequest() *dto.GeneralOpenAIRequest {
  85. testRequest := &dto.GeneralOpenAIRequest{
  86. Model: "", // this will be set later
  87. MaxTokens: 1,
  88. }
  89. content, _ := json.Marshal("hi")
  90. testMessage := dto.Message{
  91. Role: "user",
  92. Content: content,
  93. }
  94. testRequest.Messages = append(testRequest.Messages, testMessage)
  95. return testRequest
  96. }
  97. func TestChannel(c *gin.Context) {
  98. id, err := strconv.Atoi(c.Param("id"))
  99. if err != nil {
  100. c.JSON(http.StatusOK, gin.H{
  101. "success": false,
  102. "message": err.Error(),
  103. })
  104. return
  105. }
  106. channel, err := model.GetChannelById(id, true)
  107. if err != nil {
  108. c.JSON(http.StatusOK, gin.H{
  109. "success": false,
  110. "message": err.Error(),
  111. })
  112. return
  113. }
  114. testModel := c.Query("model")
  115. tik := time.Now()
  116. err, _ = testChannel(channel, testModel)
  117. tok := time.Now()
  118. milliseconds := tok.Sub(tik).Milliseconds()
  119. go channel.UpdateResponseTime(milliseconds)
  120. consumedTime := float64(milliseconds) / 1000.0
  121. if err != nil {
  122. c.JSON(http.StatusOK, gin.H{
  123. "success": false,
  124. "message": err.Error(),
  125. "time": consumedTime,
  126. })
  127. return
  128. }
  129. c.JSON(http.StatusOK, gin.H{
  130. "success": true,
  131. "message": "",
  132. "time": consumedTime,
  133. })
  134. return
  135. }
  136. var testAllChannelsLock sync.Mutex
  137. var testAllChannelsRunning bool = false
  138. func testAllChannels(notify bool) error {
  139. if common.RootUserEmail == "" {
  140. common.RootUserEmail = model.GetRootUserEmail()
  141. }
  142. testAllChannelsLock.Lock()
  143. if testAllChannelsRunning {
  144. testAllChannelsLock.Unlock()
  145. return errors.New("测试已在运行中")
  146. }
  147. testAllChannelsRunning = true
  148. testAllChannelsLock.Unlock()
  149. channels, err := model.GetAllChannels(0, 0, true, false)
  150. if err != nil {
  151. return err
  152. }
  153. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  154. if disableThreshold == 0 {
  155. disableThreshold = 10000000 // a impossible value
  156. }
  157. go func() {
  158. for _, channel := range channels {
  159. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  160. tik := time.Now()
  161. err, openaiErr := testChannel(channel, "")
  162. tok := time.Now()
  163. milliseconds := tok.Sub(tik).Milliseconds()
  164. ban := false
  165. if milliseconds > disableThreshold {
  166. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  167. ban = true
  168. }
  169. if openaiErr != nil {
  170. err = errors.New(fmt.Sprintf("type %s, code %v, message %s", openaiErr.Type, openaiErr.Code, openaiErr.Message))
  171. ban = true
  172. }
  173. // parse *int to bool
  174. if channel.AutoBan != nil && *channel.AutoBan == 0 {
  175. ban = false
  176. }
  177. if isChannelEnabled && service.ShouldDisableChannel(openaiErr, -1) && ban {
  178. service.DisableChannel(channel.Id, channel.Name, err.Error())
  179. }
  180. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiErr) {
  181. service.EnableChannel(channel.Id, channel.Name)
  182. }
  183. channel.UpdateResponseTime(milliseconds)
  184. time.Sleep(common.RequestInterval)
  185. }
  186. testAllChannelsLock.Lock()
  187. testAllChannelsRunning = false
  188. testAllChannelsLock.Unlock()
  189. if notify {
  190. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  191. if err != nil {
  192. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  193. }
  194. }
  195. }()
  196. return nil
  197. }
  198. func TestAllChannels(c *gin.Context) {
  199. err := testAllChannels(true)
  200. if err != nil {
  201. c.JSON(http.StatusOK, gin.H{
  202. "success": false,
  203. "message": err.Error(),
  204. })
  205. return
  206. }
  207. c.JSON(http.StatusOK, gin.H{
  208. "success": true,
  209. "message": "",
  210. })
  211. return
  212. }
  213. func AutomaticallyTestChannels(frequency int) {
  214. for {
  215. time.Sleep(time.Duration(frequency) * time.Minute)
  216. common.SysLog("testing all channels")
  217. _ = testAllChannels(false)
  218. common.SysLog("channel test finished")
  219. }
  220. }