channel-test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 if strings.HasPrefix(model, "gemini-2.0-flash-thinking") {
  146. testRequest.MaxTokens = 2
  147. } else {
  148. testRequest.MaxTokens = 1
  149. }
  150. content, _ := json.Marshal("hi")
  151. testMessage := dto.Message{
  152. Role: "user",
  153. Content: content,
  154. }
  155. testRequest.Model = model
  156. testRequest.Messages = append(testRequest.Messages, testMessage)
  157. return testRequest
  158. }
  159. func TestChannel(c *gin.Context) {
  160. channelId, err := strconv.Atoi(c.Param("id"))
  161. if err != nil {
  162. c.JSON(http.StatusOK, gin.H{
  163. "success": false,
  164. "message": err.Error(),
  165. })
  166. return
  167. }
  168. channel, err := model.GetChannelById(channelId, true)
  169. if err != nil {
  170. c.JSON(http.StatusOK, gin.H{
  171. "success": false,
  172. "message": err.Error(),
  173. })
  174. return
  175. }
  176. testModel := c.Query("model")
  177. tik := time.Now()
  178. err, _ = testChannel(channel, testModel)
  179. tok := time.Now()
  180. milliseconds := tok.Sub(tik).Milliseconds()
  181. go channel.UpdateResponseTime(milliseconds)
  182. consumedTime := float64(milliseconds) / 1000.0
  183. if err != nil {
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": false,
  186. "message": err.Error(),
  187. "time": consumedTime,
  188. })
  189. return
  190. }
  191. c.JSON(http.StatusOK, gin.H{
  192. "success": true,
  193. "message": "",
  194. "time": consumedTime,
  195. })
  196. return
  197. }
  198. var testAllChannelsLock sync.Mutex
  199. var testAllChannelsRunning bool = false
  200. func testAllChannels(notify bool) error {
  201. if common.RootUserEmail == "" {
  202. common.RootUserEmail = model.GetRootUserEmail()
  203. }
  204. testAllChannelsLock.Lock()
  205. if testAllChannelsRunning {
  206. testAllChannelsLock.Unlock()
  207. return errors.New("测试已在运行中")
  208. }
  209. testAllChannelsRunning = true
  210. testAllChannelsLock.Unlock()
  211. channels, err := model.GetAllChannels(0, 0, true, false)
  212. if err != nil {
  213. return err
  214. }
  215. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  216. if disableThreshold == 0 {
  217. disableThreshold = 10000000 // a impossible value
  218. }
  219. gopool.Go(func() {
  220. for _, channel := range channels {
  221. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  222. tik := time.Now()
  223. err, openaiWithStatusErr := testChannel(channel, "")
  224. tok := time.Now()
  225. milliseconds := tok.Sub(tik).Milliseconds()
  226. shouldBanChannel := false
  227. // request error disables the channel
  228. if openaiWithStatusErr != nil {
  229. oaiErr := openaiWithStatusErr.Error
  230. err = errors.New(fmt.Sprintf("type %s, httpCode %d, code %v, message %s", oaiErr.Type, openaiWithStatusErr.StatusCode, oaiErr.Code, oaiErr.Message))
  231. shouldBanChannel = service.ShouldDisableChannel(channel.Type, openaiWithStatusErr)
  232. }
  233. if milliseconds > disableThreshold {
  234. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  235. shouldBanChannel = true
  236. }
  237. // disable channel
  238. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  239. service.DisableChannel(channel.Id, channel.Name, err.Error())
  240. }
  241. // enable channel
  242. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiWithStatusErr, channel.Status) {
  243. service.EnableChannel(channel.Id, channel.Name)
  244. }
  245. channel.UpdateResponseTime(milliseconds)
  246. time.Sleep(common.RequestInterval)
  247. }
  248. testAllChannelsLock.Lock()
  249. testAllChannelsRunning = false
  250. testAllChannelsLock.Unlock()
  251. if notify {
  252. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  253. if err != nil {
  254. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  255. }
  256. }
  257. })
  258. return nil
  259. }
  260. func TestAllChannels(c *gin.Context) {
  261. err := testAllChannels(true)
  262. if err != nil {
  263. c.JSON(http.StatusOK, gin.H{
  264. "success": false,
  265. "message": err.Error(),
  266. })
  267. return
  268. }
  269. c.JSON(http.StatusOK, gin.H{
  270. "success": true,
  271. "message": "",
  272. })
  273. return
  274. }
  275. func AutomaticallyTestChannels(frequency int) {
  276. for {
  277. time.Sleep(time.Duration(frequency) * time.Minute)
  278. common.SysLog("testing all channels")
  279. _ = testAllChannels(false)
  280. common.SysLog("channel test finished")
  281. }
  282. }