channel-test.go 14 KB

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