channel-test.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. requestPath := "/v1/chat/completions"
  41. // 先判断是否为 Embedding 模型
  42. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  43. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  44. strings.Contains(testModel, "bge-") || // bge 系列模型
  45. strings.Contains(testModel, "embed") ||
  46. channel.Type == common.ChannelTypeMokaAI { // 其他 embedding 模型
  47. requestPath = "/v1/embeddings" // 修改请求路径
  48. }
  49. c.Request = &http.Request{
  50. Method: "POST",
  51. URL: &url.URL{Path: requestPath}, // 使用动态路径
  52. Body: nil,
  53. Header: make(http.Header),
  54. }
  55. if testModel == "" {
  56. if channel.TestModel != nil && *channel.TestModel != "" {
  57. testModel = *channel.TestModel
  58. } else {
  59. if len(channel.GetModels()) > 0 {
  60. testModel = channel.GetModels()[0]
  61. } else {
  62. testModel = "gpt-4o-mini"
  63. }
  64. }
  65. }
  66. modelMapping := *channel.ModelMapping
  67. if modelMapping != "" && modelMapping != "{}" {
  68. modelMap := make(map[string]string)
  69. err := json.Unmarshal([]byte(modelMapping), &modelMap)
  70. if err != nil {
  71. return err, service.OpenAIErrorWrapperLocal(err, "unmarshal_model_mapping_failed", http.StatusInternalServerError)
  72. }
  73. if modelMap[testModel] != "" {
  74. testModel = modelMap[testModel]
  75. }
  76. }
  77. cache, err := model.GetUserCache(1)
  78. if err != nil {
  79. return err, nil
  80. }
  81. cache.WriteContext(c)
  82. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  83. c.Request.Header.Set("Content-Type", "application/json")
  84. c.Set("channel", channel.Type)
  85. c.Set("base_url", channel.GetBaseURL())
  86. middleware.SetupContextForSelectedChannel(c, channel, testModel)
  87. meta := relaycommon.GenRelayInfo(c)
  88. apiType, _ := constant.ChannelType2APIType(channel.Type)
  89. adaptor := relay.GetAdaptor(apiType)
  90. if adaptor == nil {
  91. return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil
  92. }
  93. request := buildTestRequest(testModel)
  94. meta.UpstreamModelName = testModel
  95. common.SysLog(fmt.Sprintf("testing channel %d with model %s , meta %v ", channel.Id, testModel, meta))
  96. adaptor.Init(meta)
  97. convertedRequest, err := adaptor.ConvertRequest(c, meta, request)
  98. if err != nil {
  99. return err, nil
  100. }
  101. jsonData, err := json.Marshal(convertedRequest)
  102. if err != nil {
  103. return err, nil
  104. }
  105. requestBody := bytes.NewBuffer(jsonData)
  106. c.Request.Body = io.NopCloser(requestBody)
  107. resp, err := adaptor.DoRequest(c, meta, requestBody)
  108. if err != nil {
  109. return err, nil
  110. }
  111. var httpResp *http.Response
  112. if resp != nil {
  113. httpResp = resp.(*http.Response)
  114. if httpResp.StatusCode != http.StatusOK {
  115. err := service.RelayErrorHandler(httpResp)
  116. return fmt.Errorf("status code %d: %s", httpResp.StatusCode, err.Error.Message), err
  117. }
  118. }
  119. usageA, respErr := adaptor.DoResponse(c, httpResp, meta)
  120. if respErr != nil {
  121. return fmt.Errorf("%s", respErr.Error.Message), respErr
  122. }
  123. if usageA == nil {
  124. return errors.New("usage is nil"), nil
  125. }
  126. usage := usageA.(*dto.Usage)
  127. result := w.Result()
  128. respBody, err := io.ReadAll(result.Body)
  129. if err != nil {
  130. return err, nil
  131. }
  132. modelPrice, usePrice := common.GetModelPrice(testModel, false)
  133. modelRatio := common.GetModelRatio(testModel)
  134. completionRatio := common.GetCompletionRatio(testModel)
  135. ratio := modelRatio
  136. quota := 0
  137. if !usePrice {
  138. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*completionRatio))
  139. quota = int(math.Round(float64(quota) * ratio))
  140. if ratio != 0 && quota <= 0 {
  141. quota = 1
  142. }
  143. } else {
  144. quota = int(modelPrice * common.QuotaPerUnit)
  145. }
  146. tok := time.Now()
  147. milliseconds := tok.Sub(tik).Milliseconds()
  148. consumedTime := float64(milliseconds) / 1000.0
  149. other := service.GenerateTextOtherInfo(c, meta, modelRatio, 1, completionRatio, modelPrice)
  150. model.RecordConsumeLog(c, 1, channel.Id, usage.PromptTokens, usage.CompletionTokens, testModel, "模型测试",
  151. quota, "模型测试", 0, quota, int(consumedTime), false, "default", other)
  152. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  153. return nil, nil
  154. }
  155. func buildTestRequest(model string) *dto.GeneralOpenAIRequest {
  156. testRequest := &dto.GeneralOpenAIRequest{
  157. Model: "", // this will be set later
  158. Stream: false,
  159. }
  160. // 先判断是否为 Embedding 模型
  161. if strings.Contains(strings.ToLower(model), "embedding") ||
  162. strings.HasPrefix(model, "m3e") || // m3e 系列模型
  163. strings.Contains(model, "bge-") || // bge 系列模型
  164. model == "text-embedding-v1" { // 其他 embedding 模型
  165. // Embedding 请求
  166. testRequest.Input = []string{"hello world"}
  167. return testRequest
  168. }
  169. // 并非Embedding 模型
  170. if strings.HasPrefix(model, "o1") || strings.HasPrefix(model, "o3") {
  171. testRequest.MaxCompletionTokens = 10
  172. } else {
  173. testRequest.MaxTokens = 10
  174. }
  175. content, _ := json.Marshal("hi")
  176. testMessage := dto.Message{
  177. Role: "user",
  178. Content: content,
  179. }
  180. testRequest.Model = model
  181. testRequest.Messages = append(testRequest.Messages, testMessage)
  182. return testRequest
  183. }
  184. func TestChannel(c *gin.Context) {
  185. channelId, err := strconv.Atoi(c.Param("id"))
  186. if err != nil {
  187. c.JSON(http.StatusOK, gin.H{
  188. "success": false,
  189. "message": err.Error(),
  190. })
  191. return
  192. }
  193. channel, err := model.GetChannelById(channelId, true)
  194. if err != nil {
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": false,
  197. "message": err.Error(),
  198. })
  199. return
  200. }
  201. testModel := c.Query("model")
  202. tik := time.Now()
  203. err, _ = testChannel(channel, testModel)
  204. tok := time.Now()
  205. milliseconds := tok.Sub(tik).Milliseconds()
  206. go channel.UpdateResponseTime(milliseconds)
  207. consumedTime := float64(milliseconds) / 1000.0
  208. if err != nil {
  209. c.JSON(http.StatusOK, gin.H{
  210. "success": false,
  211. "message": err.Error(),
  212. "time": consumedTime,
  213. })
  214. return
  215. }
  216. c.JSON(http.StatusOK, gin.H{
  217. "success": true,
  218. "message": "",
  219. "time": consumedTime,
  220. })
  221. return
  222. }
  223. var testAllChannelsLock sync.Mutex
  224. var testAllChannelsRunning bool = false
  225. func testAllChannels(notify bool) error {
  226. testAllChannelsLock.Lock()
  227. if testAllChannelsRunning {
  228. testAllChannelsLock.Unlock()
  229. return errors.New("测试已在运行中")
  230. }
  231. testAllChannelsRunning = true
  232. testAllChannelsLock.Unlock()
  233. channels, err := model.GetAllChannels(0, 0, true, false)
  234. if err != nil {
  235. return err
  236. }
  237. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  238. if disableThreshold == 0 {
  239. disableThreshold = 10000000 // a impossible value
  240. }
  241. gopool.Go(func() {
  242. for _, channel := range channels {
  243. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  244. tik := time.Now()
  245. err, openaiWithStatusErr := testChannel(channel, "")
  246. tok := time.Now()
  247. milliseconds := tok.Sub(tik).Milliseconds()
  248. shouldBanChannel := false
  249. // request error disables the channel
  250. if openaiWithStatusErr != nil {
  251. oaiErr := openaiWithStatusErr.Error
  252. err = errors.New(fmt.Sprintf("type %s, httpCode %d, code %v, message %s", oaiErr.Type, openaiWithStatusErr.StatusCode, oaiErr.Code, oaiErr.Message))
  253. shouldBanChannel = service.ShouldDisableChannel(channel.Type, openaiWithStatusErr)
  254. }
  255. if milliseconds > disableThreshold {
  256. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  257. shouldBanChannel = true
  258. }
  259. // disable channel
  260. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  261. service.DisableChannel(channel.Id, channel.Name, err.Error())
  262. }
  263. // enable channel
  264. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiWithStatusErr, channel.Status) {
  265. service.EnableChannel(channel.Id, channel.Name)
  266. }
  267. channel.UpdateResponseTime(milliseconds)
  268. time.Sleep(common.RequestInterval)
  269. }
  270. testAllChannelsLock.Lock()
  271. testAllChannelsRunning = false
  272. testAllChannelsLock.Unlock()
  273. if notify {
  274. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  275. }
  276. })
  277. return nil
  278. }
  279. func TestAllChannels(c *gin.Context) {
  280. err := testAllChannels(true)
  281. if err != nil {
  282. c.JSON(http.StatusOK, gin.H{
  283. "success": false,
  284. "message": err.Error(),
  285. })
  286. return
  287. }
  288. c.JSON(http.StatusOK, gin.H{
  289. "success": true,
  290. "message": "",
  291. })
  292. return
  293. }
  294. func AutomaticallyTestChannels(frequency int) {
  295. for {
  296. time.Sleep(time.Duration(frequency) * time.Minute)
  297. common.SysLog("testing all channels")
  298. _ = testAllChannels(false)
  299. common.SysLog("channel test finished")
  300. }
  301. }