channel-test.go 9.9 KB

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