channel-test.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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. testModel == "text-embedding-v1" ||
  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. common.SysLog(fmt.Sprintf("testModel 为空, channel 的 TestModel 是 %s", string(*channel.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-3.5-turbo"
  64. }
  65. common.SysLog(fmt.Sprintf("testModel 为空, channel 的 TestModel 为空:", string(testModel)))
  66. }
  67. } else {
  68. modelMapping := *channel.ModelMapping
  69. if modelMapping != "" && modelMapping != "{}" {
  70. modelMap := make(map[string]string)
  71. err := json.Unmarshal([]byte(modelMapping), &modelMap)
  72. if err != nil {
  73. return err, service.OpenAIErrorWrapperLocal(err, "unmarshal_model_mapping_failed", http.StatusInternalServerError)
  74. }
  75. if modelMap[testModel] != "" {
  76. testModel = modelMap[testModel]
  77. }
  78. }
  79. }
  80. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  81. c.Request.Header.Set("Content-Type", "application/json")
  82. c.Set("channel", channel.Type)
  83. c.Set("base_url", channel.GetBaseURL())
  84. middleware.SetupContextForSelectedChannel(c, channel, testModel)
  85. meta := relaycommon.GenRelayInfo(c)
  86. apiType, _ := constant.ChannelType2APIType(channel.Type)
  87. adaptor := relay.GetAdaptor(apiType)
  88. if adaptor == nil {
  89. return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil
  90. }
  91. request := buildTestRequest(testModel)
  92. meta.UpstreamModelName = testModel
  93. common.SysLog(fmt.Sprintf("testing channel %d with model %s , meta %s ", channel.Id, testModel, meta))
  94. adaptor.Init(meta)
  95. convertedRequest, err := adaptor.ConvertRequest(c, meta, request)
  96. if err != nil {
  97. return err, nil
  98. }
  99. jsonData, err := json.Marshal(convertedRequest)
  100. if err != nil {
  101. return err, nil
  102. }
  103. requestBody := bytes.NewBuffer(jsonData)
  104. c.Request.Body = io.NopCloser(requestBody)
  105. resp, err := adaptor.DoRequest(c, meta, requestBody)
  106. if err != nil {
  107. return err, nil
  108. }
  109. var httpResp *http.Response
  110. if resp != nil {
  111. httpResp = resp.(*http.Response)
  112. if httpResp.StatusCode != http.StatusOK {
  113. err := service.RelayErrorHandler(httpResp)
  114. return fmt.Errorf("status code %d: %s", httpResp.StatusCode, err.Error.Message), err
  115. }
  116. }
  117. usageA, respErr := adaptor.DoResponse(c, httpResp, meta)
  118. if respErr != nil {
  119. return fmt.Errorf("%s", respErr.Error.Message), respErr
  120. }
  121. if usageA == nil {
  122. return errors.New("usage is nil"), nil
  123. }
  124. usage := usageA.(*dto.Usage)
  125. result := w.Result()
  126. respBody, err := io.ReadAll(result.Body)
  127. if err != nil {
  128. return err, nil
  129. }
  130. modelPrice, usePrice := common.GetModelPrice(testModel, false)
  131. modelRatio := common.GetModelRatio(testModel)
  132. completionRatio := common.GetCompletionRatio(testModel)
  133. ratio := modelRatio
  134. quota := 0
  135. if !usePrice {
  136. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*completionRatio))
  137. quota = int(math.Round(float64(quota) * ratio))
  138. if ratio != 0 && quota <= 0 {
  139. quota = 1
  140. }
  141. } else {
  142. quota = int(modelPrice * common.QuotaPerUnit)
  143. }
  144. tok := time.Now()
  145. milliseconds := tok.Sub(tik).Milliseconds()
  146. consumedTime := float64(milliseconds) / 1000.0
  147. other := service.GenerateTextOtherInfo(c, meta, modelRatio, 1, completionRatio, modelPrice)
  148. model.RecordConsumeLog(c, 1, channel.Id, usage.PromptTokens, usage.CompletionTokens, testModel, "模型测试",
  149. quota, "模型测试", 0, quota, int(consumedTime), false, "default", 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") {
  169. testRequest.MaxCompletionTokens = 10
  170. } else if strings.HasPrefix(model, "gemini-2.0-flash-thinking") {
  171. testRequest.MaxTokens = 2
  172. } else {
  173. testRequest.MaxTokens = 1
  174. }
  175. content, _ := json.Marshal("hi")
  176. testMessage := dto.Message{
  177. Role: "user",
  178. Content: content,
  179. }
  180. testRequest.Model = model
  181. testRequest.Messages = append(testRequest.Messages, testMessage)
  182. return testRequest
  183. }
  184. func TestChannel(c *gin.Context) {
  185. channelId, err := strconv.Atoi(c.Param("id"))
  186. if err != nil {
  187. c.JSON(http.StatusOK, gin.H{
  188. "success": false,
  189. "message": err.Error(),
  190. })
  191. return
  192. }
  193. channel, err := model.GetChannelById(channelId, true)
  194. if err != nil {
  195. c.JSON(http.StatusOK, gin.H{
  196. "success": false,
  197. "message": err.Error(),
  198. })
  199. return
  200. }
  201. testModel := c.Query("model")
  202. tik := time.Now()
  203. err, _ = testChannel(channel, testModel)
  204. tok := time.Now()
  205. milliseconds := tok.Sub(tik).Milliseconds()
  206. go channel.UpdateResponseTime(milliseconds)
  207. consumedTime := float64(milliseconds) / 1000.0
  208. if err != nil {
  209. c.JSON(http.StatusOK, gin.H{
  210. "success": false,
  211. "message": err.Error(),
  212. "time": consumedTime,
  213. })
  214. return
  215. }
  216. c.JSON(http.StatusOK, gin.H{
  217. "success": true,
  218. "message": "",
  219. "time": consumedTime,
  220. })
  221. return
  222. }
  223. var testAllChannelsLock sync.Mutex
  224. var testAllChannelsRunning bool = false
  225. func testAllChannels(notify bool) error {
  226. if common.RootUserEmail == "" {
  227. common.RootUserEmail = model.GetRootUserEmail()
  228. }
  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. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  278. if err != nil {
  279. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  280. }
  281. }
  282. })
  283. return nil
  284. }
  285. func TestAllChannels(c *gin.Context) {
  286. err := testAllChannels(true)
  287. if err != nil {
  288. c.JSON(http.StatusOK, gin.H{
  289. "success": false,
  290. "message": err.Error(),
  291. })
  292. return
  293. }
  294. c.JSON(http.StatusOK, gin.H{
  295. "success": true,
  296. "message": "",
  297. })
  298. return
  299. }
  300. func AutomaticallyTestChannels(frequency int) {
  301. for {
  302. time.Sleep(time.Duration(frequency) * time.Minute)
  303. common.SysLog("testing all channels")
  304. _ = testAllChannels(false)
  305. common.SysLog("channel test finished")
  306. }
  307. }