channel-test.go 9.3 KB

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