channel-test.go 9.5 KB

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