channel-test.go 8.3 KB

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