channel-test.go 7.3 KB

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