channel-test.go 6.6 KB

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