channel-test.go 6.1 KB

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