channel-test.go 7.2 KB

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