channel-test.go 8.2 KB

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