1
0

channel-test.go 13 KB

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