channel-test.go 8.5 KB

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