channel-test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. "one-api/relay/helper"
  20. "one-api/service"
  21. "one-api/types"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. "github.com/bytedance/gopkg/util/gopool"
  27. "github.com/gin-gonic/gin"
  28. )
  29. func testChannel(channel *model.Channel, testModel string) (err error, newAPIError *types.NewAPIError) {
  30. tik := time.Now()
  31. if channel.Type == constant.ChannelTypeMidjourney {
  32. return errors.New("midjourney channel test is not supported"), nil
  33. }
  34. if channel.Type == constant.ChannelTypeMidjourneyPlus {
  35. return errors.New("midjourney plus channel test is not supported"), nil
  36. }
  37. if channel.Type == constant.ChannelTypeSunoAPI {
  38. return errors.New("suno channel test is not supported"), nil
  39. }
  40. if channel.Type == constant.ChannelTypeKling {
  41. return errors.New("kling channel test is not supported"), nil
  42. }
  43. if channel.Type == constant.ChannelTypeJimeng {
  44. return errors.New("jimeng channel test is not supported"), nil
  45. }
  46. w := httptest.NewRecorder()
  47. c, _ := gin.CreateTestContext(w)
  48. requestPath := "/v1/chat/completions"
  49. // 先判断是否为 Embedding 模型
  50. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  51. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  52. strings.Contains(testModel, "bge-") || // bge 系列模型
  53. strings.Contains(testModel, "embed") ||
  54. channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
  55. requestPath = "/v1/embeddings" // 修改请求路径
  56. }
  57. c.Request = &http.Request{
  58. Method: "POST",
  59. URL: &url.URL{Path: requestPath}, // 使用动态路径
  60. Body: nil,
  61. Header: make(http.Header),
  62. }
  63. if testModel == "" {
  64. if channel.TestModel != nil && *channel.TestModel != "" {
  65. testModel = *channel.TestModel
  66. } else {
  67. if len(channel.GetModels()) > 0 {
  68. testModel = channel.GetModels()[0]
  69. } else {
  70. testModel = "gpt-4o-mini"
  71. }
  72. }
  73. }
  74. cache, err := model.GetUserCache(1)
  75. if err != nil {
  76. return err, nil
  77. }
  78. cache.WriteContext(c)
  79. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  80. c.Request.Header.Set("Content-Type", "application/json")
  81. c.Set("channel", channel.Type)
  82. c.Set("base_url", channel.GetBaseURL())
  83. group, _ := model.GetUserGroup(1, false)
  84. c.Set("group", group)
  85. middleware.SetupContextForSelectedChannel(c, channel, testModel)
  86. info := relaycommon.GenRelayInfo(c)
  87. err = helper.ModelMappedHelper(c, info, nil)
  88. if err != nil {
  89. return err, types.NewError(err, types.ErrorCodeChannelModelMappedError)
  90. }
  91. testModel = info.UpstreamModelName
  92. apiType, _ := common.ChannelType2APIType(channel.Type)
  93. adaptor := relay.GetAdaptor(apiType)
  94. if adaptor == nil {
  95. return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), types.NewError(fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), types.ErrorCodeInvalidApiType)
  96. }
  97. request := buildTestRequest(testModel)
  98. // 创建一个用于日志的 info 副本,移除 ApiKey
  99. logInfo := *info
  100. logInfo.ApiKey = ""
  101. common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %+v ", channel.Id, testModel, logInfo))
  102. priceData, err := helper.ModelPriceHelper(c, info, 0, int(request.MaxTokens))
  103. if err != nil {
  104. return err, types.NewError(err, types.ErrorCodeModelPriceError)
  105. }
  106. adaptor.Init(info)
  107. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
  108. if err != nil {
  109. return err, types.NewError(err, types.ErrorCodeConvertRequestFailed)
  110. }
  111. jsonData, err := json.Marshal(convertedRequest)
  112. if err != nil {
  113. return err, types.NewError(err, types.ErrorCodeJsonMarshalFailed)
  114. }
  115. requestBody := bytes.NewBuffer(jsonData)
  116. c.Request.Body = io.NopCloser(requestBody)
  117. resp, err := adaptor.DoRequest(c, info, requestBody)
  118. if err != nil {
  119. return err, types.NewError(err, types.ErrorCodeDoRequestFailed)
  120. }
  121. var httpResp *http.Response
  122. if resp != nil {
  123. httpResp = resp.(*http.Response)
  124. if httpResp.StatusCode != http.StatusOK {
  125. err := service.RelayErrorHandler(httpResp, true)
  126. return err, types.NewError(err, types.ErrorCodeBadResponse)
  127. }
  128. }
  129. usageA, respErr := adaptor.DoResponse(c, httpResp, info)
  130. if respErr != nil {
  131. return respErr, respErr
  132. }
  133. if usageA == nil {
  134. return errors.New("usage is nil"), types.NewError(errors.New("usage is nil"), types.ErrorCodeBadResponseBody)
  135. }
  136. usage := usageA.(*dto.Usage)
  137. result := w.Result()
  138. respBody, err := io.ReadAll(result.Body)
  139. if err != nil {
  140. return err, types.NewError(err, types.ErrorCodeReadResponseBodyFailed)
  141. }
  142. info.PromptTokens = usage.PromptTokens
  143. quota := 0
  144. if !priceData.UsePrice {
  145. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
  146. quota = int(math.Round(float64(quota) * priceData.ModelRatio))
  147. if priceData.ModelRatio != 0 && quota <= 0 {
  148. quota = 1
  149. }
  150. } else {
  151. quota = int(priceData.ModelPrice * common.QuotaPerUnit)
  152. }
  153. tok := time.Now()
  154. milliseconds := tok.Sub(tik).Milliseconds()
  155. consumedTime := float64(milliseconds) / 1000.0
  156. other := service.GenerateTextOtherInfo(c, info, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.CompletionRatio,
  157. usage.PromptTokensDetails.CachedTokens, priceData.CacheRatio, priceData.ModelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  158. model.RecordConsumeLog(c, 1, model.RecordConsumeLogParams{
  159. ChannelId: channel.Id,
  160. PromptTokens: usage.PromptTokens,
  161. CompletionTokens: usage.CompletionTokens,
  162. ModelName: info.OriginModelName,
  163. TokenName: "模型测试",
  164. Quota: quota,
  165. Content: "模型测试",
  166. UseTimeSeconds: int(consumedTime),
  167. IsStream: false,
  168. Group: info.UsingGroup,
  169. Other: other,
  170. })
  171. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  172. return nil, nil
  173. }
  174. func buildTestRequest(model string) *dto.GeneralOpenAIRequest {
  175. testRequest := &dto.GeneralOpenAIRequest{
  176. Model: "", // this will be set later
  177. Stream: false,
  178. }
  179. // 先判断是否为 Embedding 模型
  180. if strings.Contains(strings.ToLower(model), "embedding") || // 其他 embedding 模型
  181. strings.HasPrefix(model, "m3e") || // m3e 系列模型
  182. strings.Contains(model, "bge-") {
  183. testRequest.Model = model
  184. // Embedding 请求
  185. testRequest.Input = []string{"hello world"}
  186. return testRequest
  187. }
  188. // 并非Embedding 模型
  189. if strings.HasPrefix(model, "o") {
  190. testRequest.MaxCompletionTokens = 10
  191. } else if strings.Contains(model, "thinking") {
  192. if !strings.Contains(model, "claude") {
  193. testRequest.MaxTokens = 50
  194. }
  195. } else if strings.Contains(model, "gemini") {
  196. testRequest.MaxTokens = 3000
  197. } else {
  198. testRequest.MaxTokens = 10
  199. }
  200. testMessage := dto.Message{
  201. Role: "user",
  202. Content: "hi",
  203. }
  204. testRequest.Model = model
  205. testRequest.Messages = append(testRequest.Messages, testMessage)
  206. return testRequest
  207. }
  208. func TestChannel(c *gin.Context) {
  209. channelId, err := strconv.Atoi(c.Param("id"))
  210. if err != nil {
  211. c.JSON(http.StatusOK, gin.H{
  212. "success": false,
  213. "message": err.Error(),
  214. })
  215. return
  216. }
  217. channel, err := model.GetChannelById(channelId, true)
  218. if err != nil {
  219. c.JSON(http.StatusOK, gin.H{
  220. "success": false,
  221. "message": err.Error(),
  222. })
  223. return
  224. }
  225. testModel := c.Query("model")
  226. tik := time.Now()
  227. _, newAPIError := testChannel(channel, testModel)
  228. tok := time.Now()
  229. milliseconds := tok.Sub(tik).Milliseconds()
  230. go channel.UpdateResponseTime(milliseconds)
  231. consumedTime := float64(milliseconds) / 1000.0
  232. if newAPIError != nil {
  233. c.JSON(http.StatusOK, gin.H{
  234. "success": false,
  235. "message": newAPIError.Error(),
  236. "time": consumedTime,
  237. })
  238. return
  239. }
  240. c.JSON(http.StatusOK, gin.H{
  241. "success": true,
  242. "message": "",
  243. "time": consumedTime,
  244. })
  245. return
  246. }
  247. var testAllChannelsLock sync.Mutex
  248. var testAllChannelsRunning bool = false
  249. func testAllChannels(notify bool) error {
  250. testAllChannelsLock.Lock()
  251. if testAllChannelsRunning {
  252. testAllChannelsLock.Unlock()
  253. return errors.New("测试已在运行中")
  254. }
  255. testAllChannelsRunning = true
  256. testAllChannelsLock.Unlock()
  257. channels, err := model.GetAllChannels(0, 0, true, false)
  258. if err != nil {
  259. return err
  260. }
  261. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  262. if disableThreshold == 0 {
  263. disableThreshold = 10000000 // a impossible value
  264. }
  265. gopool.Go(func() {
  266. // 使用 defer 确保无论如何都会重置运行状态,防止死锁
  267. defer func() {
  268. testAllChannelsLock.Lock()
  269. testAllChannelsRunning = false
  270. testAllChannelsLock.Unlock()
  271. }()
  272. for _, channel := range channels {
  273. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  274. tik := time.Now()
  275. err, newAPIError := testChannel(channel, "")
  276. tok := time.Now()
  277. milliseconds := tok.Sub(tik).Milliseconds()
  278. shouldBanChannel := false
  279. // request error disables the channel
  280. if err != nil {
  281. shouldBanChannel = service.ShouldDisableChannel(channel.Type, newAPIError)
  282. }
  283. if milliseconds > disableThreshold {
  284. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  285. shouldBanChannel = true
  286. }
  287. // disable channel
  288. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  289. service.DisableChannel(channel.Id, channel.Name, err.Error())
  290. }
  291. // enable channel
  292. if !isChannelEnabled && service.ShouldEnableChannel(err, newAPIError, channel.Status) {
  293. service.EnableChannel(channel.Id, channel.Name)
  294. }
  295. channel.UpdateResponseTime(milliseconds)
  296. time.Sleep(common.RequestInterval)
  297. }
  298. if notify {
  299. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  300. }
  301. })
  302. return nil
  303. }
  304. func TestAllChannels(c *gin.Context) {
  305. err := testAllChannels(true)
  306. if err != nil {
  307. c.JSON(http.StatusOK, gin.H{
  308. "success": false,
  309. "message": err.Error(),
  310. })
  311. return
  312. }
  313. c.JSON(http.StatusOK, gin.H{
  314. "success": true,
  315. "message": "",
  316. })
  317. return
  318. }
  319. func AutomaticallyTestChannels(frequency int) {
  320. if frequency <= 0 {
  321. common.SysLog("CHANNEL_TEST_FREQUENCY is not set or invalid, skipping automatic channel test")
  322. return
  323. }
  324. for {
  325. time.Sleep(time.Duration(frequency) * time.Minute)
  326. common.SysLog("testing all channels")
  327. _ = testAllChannels(false)
  328. common.SysLog("channel test finished")
  329. }
  330. }