channel-test.go 9.0 KB

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