channel-test.go 6.5 KB

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