channel-test.go 8.1 KB

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