channel-test.go 9.1 KB

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