channel-test.go 6.7 KB

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