channel-test.go 14 KB

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