channel-test.go 12 KB

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