channel-test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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/relay/helper"
  20. "one-api/service"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/bytedance/gopkg/util/gopool"
  26. "github.com/gin-gonic/gin"
  27. )
  28. func testChannel(channel *model.Channel, testModel string) (err error, openAIErrorWithStatusCode *dto.OpenAIErrorWithStatusCode) {
  29. tik := time.Now()
  30. if channel.Type == common.ChannelTypeMidjourney {
  31. return errors.New("midjourney channel test is not supported"), nil
  32. }
  33. if channel.Type == common.ChannelTypeMidjourneyPlus {
  34. return errors.New("midjourney plus channel test is not supported!!!"), nil
  35. }
  36. if channel.Type == common.ChannelTypeSunoAPI {
  37. return errors.New("suno channel test is not supported"), nil
  38. }
  39. if channel.Type == common.ChannelTypeKling {
  40. return errors.New("kling channel test is not supported"), nil
  41. }
  42. w := httptest.NewRecorder()
  43. c, _ := gin.CreateTestContext(w)
  44. requestPath := "/v1/chat/completions"
  45. // 先判断是否为 Embedding 模型
  46. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  47. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  48. strings.Contains(testModel, "bge-") || // bge 系列模型
  49. strings.Contains(testModel, "embed") ||
  50. channel.Type == common.ChannelTypeMokaAI { // 其他 embedding 模型
  51. requestPath = "/v1/embeddings" // 修改请求路径
  52. }
  53. c.Request = &http.Request{
  54. Method: "POST",
  55. URL: &url.URL{Path: requestPath}, // 使用动态路径
  56. Body: nil,
  57. Header: make(http.Header),
  58. }
  59. if testModel == "" {
  60. if channel.TestModel != nil && *channel.TestModel != "" {
  61. testModel = *channel.TestModel
  62. } else {
  63. if len(channel.GetModels()) > 0 {
  64. testModel = channel.GetModels()[0]
  65. } else {
  66. testModel = "gpt-4o-mini"
  67. }
  68. }
  69. }
  70. cache, err := model.GetUserCache(1)
  71. if err != nil {
  72. return err, nil
  73. }
  74. cache.WriteContext(c)
  75. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  76. c.Request.Header.Set("Content-Type", "application/json")
  77. c.Set("channel", channel.Type)
  78. c.Set("base_url", channel.GetBaseURL())
  79. group, _ := model.GetUserGroup(1, false)
  80. c.Set("group", group)
  81. middleware.SetupContextForSelectedChannel(c, channel, testModel)
  82. info := relaycommon.GenRelayInfo(c)
  83. err = helper.ModelMappedHelper(c, info, nil)
  84. if err != nil {
  85. return err, nil
  86. }
  87. testModel = info.UpstreamModelName
  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. // 创建一个用于日志的 info 副本,移除 ApiKey
  95. logInfo := *info
  96. logInfo.ApiKey = ""
  97. common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %+v ", channel.Id, testModel, logInfo))
  98. priceData, err := helper.ModelPriceHelper(c, info, 0, int(request.MaxTokens))
  99. if err != nil {
  100. return err, nil
  101. }
  102. adaptor.Init(info)
  103. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
  104. if err != nil {
  105. return err, nil
  106. }
  107. jsonData, err := json.Marshal(convertedRequest)
  108. if err != nil {
  109. return err, nil
  110. }
  111. requestBody := bytes.NewBuffer(jsonData)
  112. c.Request.Body = io.NopCloser(requestBody)
  113. resp, err := adaptor.DoRequest(c, info, requestBody)
  114. if err != nil {
  115. return err, nil
  116. }
  117. var httpResp *http.Response
  118. if resp != nil {
  119. httpResp = resp.(*http.Response)
  120. if httpResp.StatusCode != http.StatusOK {
  121. err := service.RelayErrorHandler(httpResp, true)
  122. return fmt.Errorf("status code %d: %s", httpResp.StatusCode, err.Error.Message), err
  123. }
  124. }
  125. usageA, respErr := adaptor.DoResponse(c, httpResp, info)
  126. if respErr != nil {
  127. return fmt.Errorf("%s", respErr.Error.Message), respErr
  128. }
  129. if usageA == nil {
  130. return errors.New("usage is nil"), nil
  131. }
  132. usage := usageA.(*dto.Usage)
  133. result := w.Result()
  134. respBody, err := io.ReadAll(result.Body)
  135. if err != nil {
  136. return err, nil
  137. }
  138. info.PromptTokens = usage.PromptTokens
  139. quota := 0
  140. if !priceData.UsePrice {
  141. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
  142. quota = int(math.Round(float64(quota) * priceData.ModelRatio))
  143. if priceData.ModelRatio != 0 && quota <= 0 {
  144. quota = 1
  145. }
  146. } else {
  147. quota = int(priceData.ModelPrice * common.QuotaPerUnit)
  148. }
  149. tok := time.Now()
  150. milliseconds := tok.Sub(tik).Milliseconds()
  151. consumedTime := float64(milliseconds) / 1000.0
  152. other := service.GenerateTextOtherInfo(c, info, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.CompletionRatio,
  153. usage.PromptTokensDetails.CachedTokens, priceData.CacheRatio, priceData.ModelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  154. model.RecordConsumeLog(c, 1, channel.Id, usage.PromptTokens, usage.CompletionTokens, info.OriginModelName, "模型测试",
  155. quota, "模型测试", 0, quota, int(consumedTime), false, info.UsingGroup, other)
  156. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  157. return nil, nil
  158. }
  159. func buildTestRequest(model string) *dto.GeneralOpenAIRequest {
  160. testRequest := &dto.GeneralOpenAIRequest{
  161. Model: "", // this will be set later
  162. Stream: false,
  163. }
  164. // 先判断是否为 Embedding 模型
  165. if strings.Contains(strings.ToLower(model), "embedding") || // 其他 embedding 模型
  166. strings.HasPrefix(model, "m3e") || // m3e 系列模型
  167. strings.Contains(model, "bge-") {
  168. testRequest.Model = model
  169. // Embedding 请求
  170. testRequest.Input = []string{"hello world"}
  171. return testRequest
  172. }
  173. // 并非Embedding 模型
  174. if strings.HasPrefix(model, "o") {
  175. testRequest.MaxCompletionTokens = 10
  176. } else if strings.Contains(model, "thinking") {
  177. if !strings.Contains(model, "claude") {
  178. testRequest.MaxTokens = 50
  179. }
  180. } else if strings.Contains(model, "gemini") {
  181. testRequest.MaxTokens = 300
  182. } else {
  183. testRequest.MaxTokens = 10
  184. }
  185. testMessage := dto.Message{
  186. Role: "user",
  187. Content: "hi",
  188. }
  189. testRequest.Model = model
  190. testRequest.Messages = append(testRequest.Messages, testMessage)
  191. return testRequest
  192. }
  193. func TestChannel(c *gin.Context) {
  194. channelId, err := strconv.Atoi(c.Param("id"))
  195. if err != nil {
  196. c.JSON(http.StatusOK, gin.H{
  197. "success": false,
  198. "message": err.Error(),
  199. })
  200. return
  201. }
  202. channel, err := model.GetChannelById(channelId, true)
  203. if err != nil {
  204. c.JSON(http.StatusOK, gin.H{
  205. "success": false,
  206. "message": err.Error(),
  207. })
  208. return
  209. }
  210. testModel := c.Query("model")
  211. tik := time.Now()
  212. err, _ = testChannel(channel, testModel)
  213. tok := time.Now()
  214. milliseconds := tok.Sub(tik).Milliseconds()
  215. go channel.UpdateResponseTime(milliseconds)
  216. consumedTime := float64(milliseconds) / 1000.0
  217. if err != nil {
  218. c.JSON(http.StatusOK, gin.H{
  219. "success": false,
  220. "message": err.Error(),
  221. "time": consumedTime,
  222. })
  223. return
  224. }
  225. c.JSON(http.StatusOK, gin.H{
  226. "success": true,
  227. "message": "",
  228. "time": consumedTime,
  229. })
  230. return
  231. }
  232. var testAllChannelsLock sync.Mutex
  233. var testAllChannelsRunning bool = false
  234. func testAllChannels(notify bool) error {
  235. testAllChannelsLock.Lock()
  236. if testAllChannelsRunning {
  237. testAllChannelsLock.Unlock()
  238. return errors.New("测试已在运行中")
  239. }
  240. testAllChannelsRunning = true
  241. testAllChannelsLock.Unlock()
  242. channels, err := model.GetAllChannels(0, 0, true, false)
  243. if err != nil {
  244. return err
  245. }
  246. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  247. if disableThreshold == 0 {
  248. disableThreshold = 10000000 // a impossible value
  249. }
  250. gopool.Go(func() {
  251. // 使用 defer 确保无论如何都会重置运行状态,防止死锁
  252. defer func() {
  253. testAllChannelsLock.Lock()
  254. testAllChannelsRunning = false
  255. testAllChannelsLock.Unlock()
  256. }()
  257. for _, channel := range channels {
  258. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  259. tik := time.Now()
  260. err, openaiWithStatusErr := testChannel(channel, "")
  261. tok := time.Now()
  262. milliseconds := tok.Sub(tik).Milliseconds()
  263. shouldBanChannel := false
  264. // request error disables the channel
  265. if openaiWithStatusErr != nil {
  266. oaiErr := openaiWithStatusErr.Error
  267. err = errors.New(fmt.Sprintf("type %s, httpCode %d, code %v, message %s", oaiErr.Type, openaiWithStatusErr.StatusCode, oaiErr.Code, oaiErr.Message))
  268. shouldBanChannel = service.ShouldDisableChannel(channel.Type, openaiWithStatusErr)
  269. }
  270. if milliseconds > disableThreshold {
  271. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  272. shouldBanChannel = true
  273. }
  274. // disable channel
  275. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  276. service.DisableChannel(channel.Id, channel.Name, err.Error())
  277. }
  278. // enable channel
  279. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiWithStatusErr, channel.Status) {
  280. service.EnableChannel(channel.Id, channel.Name)
  281. }
  282. channel.UpdateResponseTime(milliseconds)
  283. time.Sleep(common.RequestInterval)
  284. }
  285. if notify {
  286. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  287. }
  288. })
  289. return nil
  290. }
  291. func TestAllChannels(c *gin.Context) {
  292. err := testAllChannels(true)
  293. if err != nil {
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": false,
  296. "message": err.Error(),
  297. })
  298. return
  299. }
  300. c.JSON(http.StatusOK, gin.H{
  301. "success": true,
  302. "message": "",
  303. })
  304. return
  305. }
  306. func AutomaticallyTestChannels(frequency int) {
  307. for {
  308. time.Sleep(time.Duration(frequency) * time.Minute)
  309. common.SysLog("testing all channels")
  310. _ = testAllChannels(false)
  311. common.SysLog("channel test finished")
  312. }
  313. }