channel-test.go 8.0 KB

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