channel-test.go 9.3 KB

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