channel-test.go 8.1 KB

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