channel-test.go 13 KB

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