channel-test.go 8.9 KB

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