channel-test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. Stream: false,
  105. }
  106. content, _ := json.Marshal("hi")
  107. testMessage := dto.Message{
  108. Role: "user",
  109. Content: content,
  110. }
  111. testRequest.Messages = append(testRequest.Messages, testMessage)
  112. return testRequest
  113. }
  114. func TestChannel(c *gin.Context) {
  115. id, err := strconv.Atoi(c.Param("id"))
  116. if err != nil {
  117. c.JSON(http.StatusOK, gin.H{
  118. "success": false,
  119. "message": err.Error(),
  120. })
  121. return
  122. }
  123. channel, err := model.GetChannelById(id, true)
  124. if err != nil {
  125. c.JSON(http.StatusOK, gin.H{
  126. "success": false,
  127. "message": err.Error(),
  128. })
  129. return
  130. }
  131. testModel := c.Query("model")
  132. tik := time.Now()
  133. err, _ = testChannel(channel, testModel)
  134. tok := time.Now()
  135. milliseconds := tok.Sub(tik).Milliseconds()
  136. go channel.UpdateResponseTime(milliseconds)
  137. consumedTime := float64(milliseconds) / 1000.0
  138. if err != nil {
  139. c.JSON(http.StatusOK, gin.H{
  140. "success": false,
  141. "message": err.Error(),
  142. "time": consumedTime,
  143. })
  144. return
  145. }
  146. c.JSON(http.StatusOK, gin.H{
  147. "success": true,
  148. "message": "",
  149. "time": consumedTime,
  150. })
  151. return
  152. }
  153. var testAllChannelsLock sync.Mutex
  154. var testAllChannelsRunning bool = false
  155. func testAllChannels(notify bool) error {
  156. if common.RootUserEmail == "" {
  157. common.RootUserEmail = model.GetRootUserEmail()
  158. }
  159. testAllChannelsLock.Lock()
  160. if testAllChannelsRunning {
  161. testAllChannelsLock.Unlock()
  162. return errors.New("测试已在运行中")
  163. }
  164. testAllChannelsRunning = true
  165. testAllChannelsLock.Unlock()
  166. channels, err := model.GetAllChannels(0, 0, true, false)
  167. if err != nil {
  168. return err
  169. }
  170. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  171. if disableThreshold == 0 {
  172. disableThreshold = 10000000 // a impossible value
  173. }
  174. go func() {
  175. for _, channel := range channels {
  176. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  177. tik := time.Now()
  178. err, openaiErr := testChannel(channel, "")
  179. tok := time.Now()
  180. milliseconds := tok.Sub(tik).Milliseconds()
  181. ban := false
  182. if milliseconds > disableThreshold {
  183. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  184. ban = true
  185. }
  186. if openaiErr != nil {
  187. err = errors.New(fmt.Sprintf("type %s, code %v, message %s", openaiErr.Type, openaiErr.Code, openaiErr.Message))
  188. ban = true
  189. }
  190. // parse *int to bool
  191. if channel.AutoBan != nil && *channel.AutoBan == 0 {
  192. ban = false
  193. }
  194. if isChannelEnabled && service.ShouldDisableChannel(openaiErr, -1) && ban {
  195. service.DisableChannel(channel.Id, channel.Name, err.Error())
  196. }
  197. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiErr) {
  198. service.EnableChannel(channel.Id, channel.Name)
  199. }
  200. channel.UpdateResponseTime(milliseconds)
  201. time.Sleep(common.RequestInterval)
  202. }
  203. testAllChannelsLock.Lock()
  204. testAllChannelsRunning = false
  205. testAllChannelsLock.Unlock()
  206. if notify {
  207. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  208. if err != nil {
  209. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  210. }
  211. }
  212. }()
  213. return nil
  214. }
  215. func TestAllChannels(c *gin.Context) {
  216. err := testAllChannels(true)
  217. if err != nil {
  218. c.JSON(http.StatusOK, gin.H{
  219. "success": false,
  220. "message": err.Error(),
  221. })
  222. return
  223. }
  224. c.JSON(http.StatusOK, gin.H{
  225. "success": true,
  226. "message": "",
  227. })
  228. return
  229. }
  230. func AutomaticallyTestChannels(frequency int) {
  231. for {
  232. time.Sleep(time.Duration(frequency) * time.Minute)
  233. common.SysLog("testing all channels")
  234. _ = testAllChannels(false)
  235. common.SysLog("channel test finished")
  236. }
  237. }