channel-test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/QuantumNous/new-api/common"
  17. "github.com/QuantumNous/new-api/constant"
  18. "github.com/QuantumNous/new-api/dto"
  19. "github.com/QuantumNous/new-api/middleware"
  20. "github.com/QuantumNous/new-api/model"
  21. "github.com/QuantumNous/new-api/relay"
  22. relaycommon "github.com/QuantumNous/new-api/relay/common"
  23. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  24. "github.com/QuantumNous/new-api/relay/helper"
  25. "github.com/QuantumNous/new-api/service"
  26. "github.com/QuantumNous/new-api/setting/operation_setting"
  27. "github.com/QuantumNous/new-api/types"
  28. "github.com/bytedance/gopkg/util/gopool"
  29. "github.com/samber/lo"
  30. "github.com/gin-gonic/gin"
  31. )
  32. type testResult struct {
  33. context *gin.Context
  34. localErr error
  35. newAPIError *types.NewAPIError
  36. }
  37. func testChannel(channel *model.Channel, testModel string, endpointType string) testResult {
  38. tik := time.Now()
  39. var unsupportedTestChannelTypes = []int{
  40. constant.ChannelTypeMidjourney,
  41. constant.ChannelTypeMidjourneyPlus,
  42. constant.ChannelTypeSunoAPI,
  43. constant.ChannelTypeKling,
  44. constant.ChannelTypeJimeng,
  45. constant.ChannelTypeDoubaoVideo,
  46. constant.ChannelTypeVidu,
  47. }
  48. if lo.Contains(unsupportedTestChannelTypes, channel.Type) {
  49. channelTypeName := constant.GetChannelTypeName(channel.Type)
  50. return testResult{
  51. localErr: fmt.Errorf("%s channel test is not supported", channelTypeName),
  52. }
  53. }
  54. w := httptest.NewRecorder()
  55. c, _ := gin.CreateTestContext(w)
  56. testModel = strings.TrimSpace(testModel)
  57. if testModel == "" {
  58. if channel.TestModel != nil && *channel.TestModel != "" {
  59. testModel = strings.TrimSpace(*channel.TestModel)
  60. } else {
  61. models := channel.GetModels()
  62. if len(models) > 0 {
  63. testModel = strings.TrimSpace(models[0])
  64. }
  65. if testModel == "" {
  66. testModel = "gpt-4o-mini"
  67. }
  68. }
  69. }
  70. requestPath := "/v1/chat/completions"
  71. // 如果指定了端点类型,使用指定的端点类型
  72. if endpointType != "" {
  73. if endpointInfo, ok := common.GetDefaultEndpointInfo(constant.EndpointType(endpointType)); ok {
  74. requestPath = endpointInfo.Path
  75. }
  76. } else {
  77. // 如果没有指定端点类型,使用原有的自动检测逻辑
  78. // 先判断是否为 Embedding 模型
  79. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  80. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  81. strings.Contains(testModel, "bge-") || // bge 系列模型
  82. strings.Contains(testModel, "embed") ||
  83. channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
  84. requestPath = "/v1/embeddings" // 修改请求路径
  85. }
  86. // VolcEngine 图像生成模型
  87. if channel.Type == constant.ChannelTypeVolcEngine && strings.Contains(testModel, "seedream") {
  88. requestPath = "/v1/images/generations"
  89. }
  90. // responses-only models
  91. if strings.Contains(strings.ToLower(testModel), "codex") {
  92. requestPath = "/v1/responses"
  93. }
  94. }
  95. c.Request = &http.Request{
  96. Method: "POST",
  97. URL: &url.URL{Path: requestPath}, // 使用动态路径
  98. Body: nil,
  99. Header: make(http.Header),
  100. }
  101. cache, err := model.GetUserCache(1)
  102. if err != nil {
  103. return testResult{
  104. localErr: err,
  105. newAPIError: nil,
  106. }
  107. }
  108. cache.WriteContext(c)
  109. //c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  110. c.Request.Header.Set("Content-Type", "application/json")
  111. c.Set("channel", channel.Type)
  112. c.Set("base_url", channel.GetBaseURL())
  113. group, _ := model.GetUserGroup(1, false)
  114. c.Set("group", group)
  115. newAPIError := middleware.SetupContextForSelectedChannel(c, channel, testModel)
  116. if newAPIError != nil {
  117. return testResult{
  118. context: c,
  119. localErr: newAPIError,
  120. newAPIError: newAPIError,
  121. }
  122. }
  123. // Determine relay format based on endpoint type or request path
  124. var relayFormat types.RelayFormat
  125. if endpointType != "" {
  126. // 根据指定的端点类型设置 relayFormat
  127. switch constant.EndpointType(endpointType) {
  128. case constant.EndpointTypeOpenAI:
  129. relayFormat = types.RelayFormatOpenAI
  130. case constant.EndpointTypeOpenAIResponse:
  131. relayFormat = types.RelayFormatOpenAIResponses
  132. case constant.EndpointTypeAnthropic:
  133. relayFormat = types.RelayFormatClaude
  134. case constant.EndpointTypeGemini:
  135. relayFormat = types.RelayFormatGemini
  136. case constant.EndpointTypeJinaRerank:
  137. relayFormat = types.RelayFormatRerank
  138. case constant.EndpointTypeImageGeneration:
  139. relayFormat = types.RelayFormatOpenAIImage
  140. case constant.EndpointTypeEmbeddings:
  141. relayFormat = types.RelayFormatEmbedding
  142. default:
  143. relayFormat = types.RelayFormatOpenAI
  144. }
  145. } else {
  146. // 根据请求路径自动检测
  147. relayFormat = types.RelayFormatOpenAI
  148. if c.Request.URL.Path == "/v1/embeddings" {
  149. relayFormat = types.RelayFormatEmbedding
  150. }
  151. if c.Request.URL.Path == "/v1/images/generations" {
  152. relayFormat = types.RelayFormatOpenAIImage
  153. }
  154. if c.Request.URL.Path == "/v1/messages" {
  155. relayFormat = types.RelayFormatClaude
  156. }
  157. if strings.Contains(c.Request.URL.Path, "/v1beta/models") {
  158. relayFormat = types.RelayFormatGemini
  159. }
  160. if c.Request.URL.Path == "/v1/rerank" || c.Request.URL.Path == "/rerank" {
  161. relayFormat = types.RelayFormatRerank
  162. }
  163. if c.Request.URL.Path == "/v1/responses" {
  164. relayFormat = types.RelayFormatOpenAIResponses
  165. }
  166. }
  167. request := buildTestRequest(testModel, endpointType, channel)
  168. info, err := relaycommon.GenRelayInfo(c, relayFormat, request, nil)
  169. if err != nil {
  170. return testResult{
  171. context: c,
  172. localErr: err,
  173. newAPIError: types.NewError(err, types.ErrorCodeGenRelayInfoFailed),
  174. }
  175. }
  176. info.IsChannelTest = true
  177. info.InitChannelMeta(c)
  178. err = helper.ModelMappedHelper(c, info, request)
  179. if err != nil {
  180. return testResult{
  181. context: c,
  182. localErr: err,
  183. newAPIError: types.NewError(err, types.ErrorCodeChannelModelMappedError),
  184. }
  185. }
  186. testModel = info.UpstreamModelName
  187. // 更新请求中的模型名称
  188. request.SetModelName(testModel)
  189. apiType, _ := common.ChannelType2APIType(channel.Type)
  190. adaptor := relay.GetAdaptor(apiType)
  191. if adaptor == nil {
  192. return testResult{
  193. context: c,
  194. localErr: fmt.Errorf("invalid api type: %d, adaptor is nil", apiType),
  195. newAPIError: types.NewError(fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), types.ErrorCodeInvalidApiType),
  196. }
  197. }
  198. //// 创建一个用于日志的 info 副本,移除 ApiKey
  199. //logInfo := info
  200. //logInfo.ApiKey = ""
  201. common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %+v ", channel.Id, testModel, info.ToString()))
  202. priceData, err := helper.ModelPriceHelper(c, info, 0, request.GetTokenCountMeta())
  203. if err != nil {
  204. return testResult{
  205. context: c,
  206. localErr: err,
  207. newAPIError: types.NewError(err, types.ErrorCodeModelPriceError),
  208. }
  209. }
  210. adaptor.Init(info)
  211. var convertedRequest any
  212. // 根据 RelayMode 选择正确的转换函数
  213. switch info.RelayMode {
  214. case relayconstant.RelayModeEmbeddings:
  215. // Embedding 请求 - request 已经是正确的类型
  216. if embeddingReq, ok := request.(*dto.EmbeddingRequest); ok {
  217. convertedRequest, err = adaptor.ConvertEmbeddingRequest(c, info, *embeddingReq)
  218. } else {
  219. return testResult{
  220. context: c,
  221. localErr: errors.New("invalid embedding request type"),
  222. newAPIError: types.NewError(errors.New("invalid embedding request type"), types.ErrorCodeConvertRequestFailed),
  223. }
  224. }
  225. case relayconstant.RelayModeImagesGenerations:
  226. // 图像生成请求 - request 已经是正确的类型
  227. if imageReq, ok := request.(*dto.ImageRequest); ok {
  228. convertedRequest, err = adaptor.ConvertImageRequest(c, info, *imageReq)
  229. } else {
  230. return testResult{
  231. context: c,
  232. localErr: errors.New("invalid image request type"),
  233. newAPIError: types.NewError(errors.New("invalid image request type"), types.ErrorCodeConvertRequestFailed),
  234. }
  235. }
  236. case relayconstant.RelayModeRerank:
  237. // Rerank 请求 - request 已经是正确的类型
  238. if rerankReq, ok := request.(*dto.RerankRequest); ok {
  239. convertedRequest, err = adaptor.ConvertRerankRequest(c, info.RelayMode, *rerankReq)
  240. } else {
  241. return testResult{
  242. context: c,
  243. localErr: errors.New("invalid rerank request type"),
  244. newAPIError: types.NewError(errors.New("invalid rerank request type"), types.ErrorCodeConvertRequestFailed),
  245. }
  246. }
  247. case relayconstant.RelayModeResponses:
  248. // Response 请求 - request 已经是正确的类型
  249. if responseReq, ok := request.(*dto.OpenAIResponsesRequest); ok {
  250. convertedRequest, err = adaptor.ConvertOpenAIResponsesRequest(c, info, *responseReq)
  251. } else {
  252. return testResult{
  253. context: c,
  254. localErr: errors.New("invalid response request type"),
  255. newAPIError: types.NewError(errors.New("invalid response request type"), types.ErrorCodeConvertRequestFailed),
  256. }
  257. }
  258. default:
  259. // Chat/Completion 等其他请求类型
  260. if generalReq, ok := request.(*dto.GeneralOpenAIRequest); ok {
  261. convertedRequest, err = adaptor.ConvertOpenAIRequest(c, info, generalReq)
  262. } else {
  263. return testResult{
  264. context: c,
  265. localErr: errors.New("invalid general request type"),
  266. newAPIError: types.NewError(errors.New("invalid general request type"), types.ErrorCodeConvertRequestFailed),
  267. }
  268. }
  269. }
  270. if err != nil {
  271. return testResult{
  272. context: c,
  273. localErr: err,
  274. newAPIError: types.NewError(err, types.ErrorCodeConvertRequestFailed),
  275. }
  276. }
  277. jsonData, err := json.Marshal(convertedRequest)
  278. if err != nil {
  279. return testResult{
  280. context: c,
  281. localErr: err,
  282. newAPIError: types.NewError(err, types.ErrorCodeJsonMarshalFailed),
  283. }
  284. }
  285. //jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings)
  286. //if err != nil {
  287. // return testResult{
  288. // context: c,
  289. // localErr: err,
  290. // newAPIError: types.NewError(err, types.ErrorCodeConvertRequestFailed),
  291. // }
  292. //}
  293. if len(info.ParamOverride) > 0 {
  294. jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride, relaycommon.BuildParamOverrideContext(info))
  295. if err != nil {
  296. return testResult{
  297. context: c,
  298. localErr: err,
  299. newAPIError: types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid),
  300. }
  301. }
  302. }
  303. requestBody := bytes.NewBuffer(jsonData)
  304. c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonData))
  305. resp, err := adaptor.DoRequest(c, info, requestBody)
  306. if err != nil {
  307. return testResult{
  308. context: c,
  309. localErr: err,
  310. newAPIError: types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError),
  311. }
  312. }
  313. var httpResp *http.Response
  314. if resp != nil {
  315. httpResp = resp.(*http.Response)
  316. if httpResp.StatusCode != http.StatusOK {
  317. err := service.RelayErrorHandler(c.Request.Context(), httpResp, true)
  318. common.SysError(fmt.Sprintf(
  319. "channel test bad response: channel_id=%d name=%s type=%d model=%s endpoint_type=%s status=%d err=%v",
  320. channel.Id,
  321. channel.Name,
  322. channel.Type,
  323. testModel,
  324. endpointType,
  325. httpResp.StatusCode,
  326. err,
  327. ))
  328. return testResult{
  329. context: c,
  330. localErr: err,
  331. newAPIError: types.NewOpenAIError(err, types.ErrorCodeBadResponse, http.StatusInternalServerError),
  332. }
  333. }
  334. }
  335. usageA, respErr := adaptor.DoResponse(c, httpResp, info)
  336. if respErr != nil {
  337. return testResult{
  338. context: c,
  339. localErr: respErr,
  340. newAPIError: respErr,
  341. }
  342. }
  343. if usageA == nil {
  344. return testResult{
  345. context: c,
  346. localErr: errors.New("usage is nil"),
  347. newAPIError: types.NewOpenAIError(errors.New("usage is nil"), types.ErrorCodeBadResponseBody, http.StatusInternalServerError),
  348. }
  349. }
  350. usage := usageA.(*dto.Usage)
  351. result := w.Result()
  352. respBody, err := io.ReadAll(result.Body)
  353. if err != nil {
  354. return testResult{
  355. context: c,
  356. localErr: err,
  357. newAPIError: types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError),
  358. }
  359. }
  360. info.SetEstimatePromptTokens(usage.PromptTokens)
  361. quota := 0
  362. if !priceData.UsePrice {
  363. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
  364. quota = int(math.Round(float64(quota) * priceData.ModelRatio))
  365. if priceData.ModelRatio != 0 && quota <= 0 {
  366. quota = 1
  367. }
  368. } else {
  369. quota = int(priceData.ModelPrice * common.QuotaPerUnit)
  370. }
  371. tok := time.Now()
  372. milliseconds := tok.Sub(tik).Milliseconds()
  373. consumedTime := float64(milliseconds) / 1000.0
  374. other := service.GenerateTextOtherInfo(c, info, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.CompletionRatio,
  375. usage.PromptTokensDetails.CachedTokens, priceData.CacheRatio, priceData.ModelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  376. model.RecordConsumeLog(c, 1, model.RecordConsumeLogParams{
  377. ChannelId: channel.Id,
  378. PromptTokens: usage.PromptTokens,
  379. CompletionTokens: usage.CompletionTokens,
  380. ModelName: info.OriginModelName,
  381. TokenName: "模型测试",
  382. Quota: quota,
  383. Content: "模型测试",
  384. UseTimeSeconds: int(consumedTime),
  385. IsStream: info.IsStream,
  386. Group: info.UsingGroup,
  387. Other: other,
  388. })
  389. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  390. return testResult{
  391. context: c,
  392. localErr: nil,
  393. newAPIError: nil,
  394. }
  395. }
  396. func buildTestRequest(model string, endpointType string, channel *model.Channel) dto.Request {
  397. // 根据端点类型构建不同的测试请求
  398. if endpointType != "" {
  399. switch constant.EndpointType(endpointType) {
  400. case constant.EndpointTypeEmbeddings:
  401. // 返回 EmbeddingRequest
  402. return &dto.EmbeddingRequest{
  403. Model: model,
  404. Input: []any{"hello world"},
  405. }
  406. case constant.EndpointTypeImageGeneration:
  407. // 返回 ImageRequest
  408. return &dto.ImageRequest{
  409. Model: model,
  410. Prompt: "a cute cat",
  411. N: 1,
  412. Size: "1024x1024",
  413. }
  414. case constant.EndpointTypeJinaRerank:
  415. // 返回 RerankRequest
  416. return &dto.RerankRequest{
  417. Model: model,
  418. Query: "What is Deep Learning?",
  419. Documents: []any{"Deep Learning is a subset of machine learning.", "Machine learning is a field of artificial intelligence."},
  420. TopN: 2,
  421. }
  422. case constant.EndpointTypeOpenAIResponse:
  423. // 返回 OpenAIResponsesRequest
  424. return &dto.OpenAIResponsesRequest{
  425. Model: model,
  426. Input: json.RawMessage("\"hi\""),
  427. }
  428. case constant.EndpointTypeAnthropic, constant.EndpointTypeGemini, constant.EndpointTypeOpenAI:
  429. // 返回 GeneralOpenAIRequest
  430. maxTokens := uint(16)
  431. if constant.EndpointType(endpointType) == constant.EndpointTypeGemini {
  432. maxTokens = 3000
  433. }
  434. return &dto.GeneralOpenAIRequest{
  435. Model: model,
  436. Stream: false,
  437. Messages: []dto.Message{
  438. {
  439. Role: "user",
  440. Content: "hi",
  441. },
  442. },
  443. MaxTokens: maxTokens,
  444. }
  445. }
  446. }
  447. // 自动检测逻辑(保持原有行为)
  448. // 先判断是否为 Embedding 模型
  449. if strings.Contains(strings.ToLower(model), "embedding") ||
  450. strings.HasPrefix(model, "m3e") ||
  451. strings.Contains(model, "bge-") {
  452. // 返回 EmbeddingRequest
  453. return &dto.EmbeddingRequest{
  454. Model: model,
  455. Input: []any{"hello world"},
  456. }
  457. }
  458. // Responses-only models (e.g. codex series)
  459. if strings.Contains(strings.ToLower(model), "codex") {
  460. return &dto.OpenAIResponsesRequest{
  461. Model: model,
  462. Input: json.RawMessage("\"hi\""),
  463. }
  464. }
  465. // Chat/Completion 请求 - 返回 GeneralOpenAIRequest
  466. testRequest := &dto.GeneralOpenAIRequest{
  467. Model: model,
  468. Stream: false,
  469. Messages: []dto.Message{
  470. {
  471. Role: "user",
  472. Content: "hi",
  473. },
  474. },
  475. }
  476. if strings.HasPrefix(model, "o") {
  477. testRequest.MaxCompletionTokens = 16
  478. } else if strings.Contains(model, "thinking") {
  479. if !strings.Contains(model, "claude") {
  480. testRequest.MaxTokens = 50
  481. }
  482. } else if strings.Contains(model, "gemini") {
  483. testRequest.MaxTokens = 3000
  484. } else {
  485. testRequest.MaxTokens = 16
  486. }
  487. return testRequest
  488. }
  489. func TestChannel(c *gin.Context) {
  490. channelId, err := strconv.Atoi(c.Param("id"))
  491. if err != nil {
  492. common.ApiError(c, err)
  493. return
  494. }
  495. channel, err := model.CacheGetChannel(channelId)
  496. if err != nil {
  497. channel, err = model.GetChannelById(channelId, true)
  498. if err != nil {
  499. common.ApiError(c, err)
  500. return
  501. }
  502. }
  503. //defer func() {
  504. // if channel.ChannelInfo.IsMultiKey {
  505. // go func() { _ = channel.SaveChannelInfo() }()
  506. // }
  507. //}()
  508. testModel := c.Query("model")
  509. endpointType := c.Query("endpoint_type")
  510. tik := time.Now()
  511. result := testChannel(channel, testModel, endpointType)
  512. if result.localErr != nil {
  513. c.JSON(http.StatusOK, gin.H{
  514. "success": false,
  515. "message": result.localErr.Error(),
  516. "time": 0.0,
  517. })
  518. return
  519. }
  520. tok := time.Now()
  521. milliseconds := tok.Sub(tik).Milliseconds()
  522. go channel.UpdateResponseTime(milliseconds)
  523. consumedTime := float64(milliseconds) / 1000.0
  524. if result.newAPIError != nil {
  525. c.JSON(http.StatusOK, gin.H{
  526. "success": false,
  527. "message": result.newAPIError.Error(),
  528. "time": consumedTime,
  529. })
  530. return
  531. }
  532. c.JSON(http.StatusOK, gin.H{
  533. "success": true,
  534. "message": "",
  535. "time": consumedTime,
  536. })
  537. }
  538. var testAllChannelsLock sync.Mutex
  539. var testAllChannelsRunning bool = false
  540. func testAllChannels(notify bool) error {
  541. testAllChannelsLock.Lock()
  542. if testAllChannelsRunning {
  543. testAllChannelsLock.Unlock()
  544. return errors.New("测试已在运行中")
  545. }
  546. testAllChannelsRunning = true
  547. testAllChannelsLock.Unlock()
  548. channels, getChannelErr := model.GetAllChannels(0, 0, true, false)
  549. if getChannelErr != nil {
  550. return getChannelErr
  551. }
  552. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  553. if disableThreshold == 0 {
  554. disableThreshold = 10000000 // a impossible value
  555. }
  556. gopool.Go(func() {
  557. // 使用 defer 确保无论如何都会重置运行状态,防止死锁
  558. defer func() {
  559. testAllChannelsLock.Lock()
  560. testAllChannelsRunning = false
  561. testAllChannelsLock.Unlock()
  562. }()
  563. for _, channel := range channels {
  564. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  565. tik := time.Now()
  566. result := testChannel(channel, "", "")
  567. tok := time.Now()
  568. milliseconds := tok.Sub(tik).Milliseconds()
  569. shouldBanChannel := false
  570. newAPIError := result.newAPIError
  571. // request error disables the channel
  572. if newAPIError != nil {
  573. shouldBanChannel = service.ShouldDisableChannel(channel.Type, result.newAPIError)
  574. }
  575. // 当错误检查通过,才检查响应时间
  576. if common.AutomaticDisableChannelEnabled && !shouldBanChannel {
  577. if milliseconds > disableThreshold {
  578. err := fmt.Errorf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0)
  579. newAPIError = types.NewOpenAIError(err, types.ErrorCodeChannelResponseTimeExceeded, http.StatusRequestTimeout)
  580. shouldBanChannel = true
  581. }
  582. }
  583. // disable channel
  584. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  585. processChannelError(result.context, *types.NewChannelError(channel.Id, channel.Type, channel.Name, channel.ChannelInfo.IsMultiKey, common.GetContextKeyString(result.context, constant.ContextKeyChannelKey), channel.GetAutoBan()), newAPIError)
  586. }
  587. // enable channel
  588. if !isChannelEnabled && service.ShouldEnableChannel(newAPIError, channel.Status) {
  589. service.EnableChannel(channel.Id, common.GetContextKeyString(result.context, constant.ContextKeyChannelKey), channel.Name)
  590. }
  591. channel.UpdateResponseTime(milliseconds)
  592. time.Sleep(common.RequestInterval)
  593. }
  594. if notify {
  595. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  596. }
  597. })
  598. return nil
  599. }
  600. func TestAllChannels(c *gin.Context) {
  601. err := testAllChannels(true)
  602. if err != nil {
  603. common.ApiError(c, err)
  604. return
  605. }
  606. c.JSON(http.StatusOK, gin.H{
  607. "success": true,
  608. "message": "",
  609. })
  610. }
  611. var autoTestChannelsOnce sync.Once
  612. func AutomaticallyTestChannels() {
  613. // 只在Master节点定时测试渠道
  614. if !common.IsMasterNode {
  615. return
  616. }
  617. autoTestChannelsOnce.Do(func() {
  618. for {
  619. if !operation_setting.GetMonitorSetting().AutoTestChannelEnabled {
  620. time.Sleep(1 * time.Minute)
  621. continue
  622. }
  623. for {
  624. frequency := operation_setting.GetMonitorSetting().AutoTestChannelMinutes
  625. time.Sleep(time.Duration(int(math.Round(frequency))) * time.Minute)
  626. common.SysLog(fmt.Sprintf("automatically test channels with interval %f minutes", frequency))
  627. common.SysLog("automatically testing all channels")
  628. _ = testAllChannels(false)
  629. common.SysLog("automatically channel test finished")
  630. if !operation_setting.GetMonitorSetting().AutoTestChannelEnabled {
  631. break
  632. }
  633. }
  634. }
  635. })
  636. }