channel-test.go 8.4 KB

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