channel-test.go 9.3 KB

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