channel-test.go 8.3 KB

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