channel-test.go 9.7 KB

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