channel-test.go 9.1 KB

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