channel-test.go 15 KB

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