channel-test.go 13 KB

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