channel-test.go 9.0 KB

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