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