channel-test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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/constant"
  14. "one-api/dto"
  15. "one-api/middleware"
  16. "one-api/model"
  17. "one-api/relay"
  18. relaycommon "one-api/relay/common"
  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 == constant.ChannelTypeMidjourney {
  31. return errors.New("midjourney channel test is not supported"), nil
  32. }
  33. if channel.Type == constant.ChannelTypeMidjourneyPlus {
  34. return errors.New("midjourney plus channel test is not supported"), nil
  35. }
  36. if channel.Type == constant.ChannelTypeSunoAPI {
  37. return errors.New("suno channel test is not supported"), nil
  38. }
  39. if channel.Type == constant.ChannelTypeKling {
  40. return errors.New("kling channel test is not supported"), nil
  41. }
  42. if channel.Type == constant.ChannelTypeJimeng {
  43. return errors.New("jimeng channel test is not supported"), nil
  44. }
  45. w := httptest.NewRecorder()
  46. c, _ := gin.CreateTestContext(w)
  47. requestPath := "/v1/chat/completions"
  48. // 先判断是否为 Embedding 模型
  49. if strings.Contains(strings.ToLower(testModel), "embedding") ||
  50. strings.HasPrefix(testModel, "m3e") || // m3e 系列模型
  51. strings.Contains(testModel, "bge-") || // bge 系列模型
  52. strings.Contains(testModel, "embed") ||
  53. channel.Type == constant.ChannelTypeMokaAI { // 其他 embedding 模型
  54. requestPath = "/v1/embeddings" // 修改请求路径
  55. }
  56. c.Request = &http.Request{
  57. Method: "POST",
  58. URL: &url.URL{Path: requestPath}, // 使用动态路径
  59. Body: nil,
  60. Header: make(http.Header),
  61. }
  62. if testModel == "" {
  63. if channel.TestModel != nil && *channel.TestModel != "" {
  64. testModel = *channel.TestModel
  65. } else {
  66. if len(channel.GetModels()) > 0 {
  67. testModel = channel.GetModels()[0]
  68. } else {
  69. testModel = "gpt-4o-mini"
  70. }
  71. }
  72. }
  73. cache, err := model.GetUserCache(1)
  74. if err != nil {
  75. return err, nil
  76. }
  77. cache.WriteContext(c)
  78. c.Request.Header.Set("Authorization", "Bearer "+channel.Key)
  79. c.Request.Header.Set("Content-Type", "application/json")
  80. c.Set("channel", channel.Type)
  81. c.Set("base_url", channel.GetBaseURL())
  82. group, _ := model.GetUserGroup(1, false)
  83. c.Set("group", group)
  84. middleware.SetupContextForSelectedChannel(c, channel, testModel)
  85. info := relaycommon.GenRelayInfo(c)
  86. err = helper.ModelMappedHelper(c, info, nil)
  87. if err != nil {
  88. return err, nil
  89. }
  90. testModel = info.UpstreamModelName
  91. apiType, _ := common.ChannelType2APIType(channel.Type)
  92. adaptor := relay.GetAdaptor(apiType)
  93. if adaptor == nil {
  94. return fmt.Errorf("invalid api type: %d, adaptor is nil", apiType), nil
  95. }
  96. request := buildTestRequest(testModel)
  97. // 创建一个用于日志的 info 副本,移除 ApiKey
  98. logInfo := *info
  99. logInfo.ApiKey = ""
  100. common.SysLog(fmt.Sprintf("testing channel %d with model %s , info %+v ", channel.Id, testModel, logInfo))
  101. priceData, err := helper.ModelPriceHelper(c, info, 0, int(request.MaxTokens))
  102. if err != nil {
  103. return err, nil
  104. }
  105. adaptor.Init(info)
  106. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
  107. if err != nil {
  108. return err, nil
  109. }
  110. jsonData, err := json.Marshal(convertedRequest)
  111. if err != nil {
  112. return err, nil
  113. }
  114. requestBody := bytes.NewBuffer(jsonData)
  115. c.Request.Body = io.NopCloser(requestBody)
  116. resp, err := adaptor.DoRequest(c, info, requestBody)
  117. if err != nil {
  118. return err, nil
  119. }
  120. var httpResp *http.Response
  121. if resp != nil {
  122. httpResp = resp.(*http.Response)
  123. if httpResp.StatusCode != http.StatusOK {
  124. err := service.RelayErrorHandler(httpResp, true)
  125. return fmt.Errorf("status code %d: %s", httpResp.StatusCode, err.Error.Message), err
  126. }
  127. }
  128. usageA, respErr := adaptor.DoResponse(c, httpResp, info)
  129. if respErr != nil {
  130. return fmt.Errorf("%s", respErr.Error.Message), respErr
  131. }
  132. if usageA == nil {
  133. return errors.New("usage is nil"), nil
  134. }
  135. usage := usageA.(*dto.Usage)
  136. result := w.Result()
  137. respBody, err := io.ReadAll(result.Body)
  138. if err != nil {
  139. return err, nil
  140. }
  141. info.PromptTokens = usage.PromptTokens
  142. quota := 0
  143. if !priceData.UsePrice {
  144. quota = usage.PromptTokens + int(math.Round(float64(usage.CompletionTokens)*priceData.CompletionRatio))
  145. quota = int(math.Round(float64(quota) * priceData.ModelRatio))
  146. if priceData.ModelRatio != 0 && quota <= 0 {
  147. quota = 1
  148. }
  149. } else {
  150. quota = int(priceData.ModelPrice * common.QuotaPerUnit)
  151. }
  152. tok := time.Now()
  153. milliseconds := tok.Sub(tik).Milliseconds()
  154. consumedTime := float64(milliseconds) / 1000.0
  155. other := service.GenerateTextOtherInfo(c, info, priceData.ModelRatio, priceData.GroupRatioInfo.GroupRatio, priceData.CompletionRatio,
  156. usage.PromptTokensDetails.CachedTokens, priceData.CacheRatio, priceData.ModelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  157. model.RecordConsumeLog(c, 1, model.RecordConsumeLogParams{
  158. ChannelId: channel.Id,
  159. PromptTokens: usage.PromptTokens,
  160. CompletionTokens: usage.CompletionTokens,
  161. ModelName: info.OriginModelName,
  162. TokenName: "模型测试",
  163. Quota: quota,
  164. Content: "模型测试",
  165. UseTimeSeconds: int(consumedTime),
  166. IsStream: false,
  167. Group: info.UsingGroup,
  168. Other: other,
  169. })
  170. common.SysLog(fmt.Sprintf("testing channel #%d, response: \n%s", channel.Id, string(respBody)))
  171. return nil, nil
  172. }
  173. func buildTestRequest(model string) *dto.GeneralOpenAIRequest {
  174. testRequest := &dto.GeneralOpenAIRequest{
  175. Model: "", // this will be set later
  176. Stream: false,
  177. }
  178. // 先判断是否为 Embedding 模型
  179. if strings.Contains(strings.ToLower(model), "embedding") || // 其他 embedding 模型
  180. strings.HasPrefix(model, "m3e") || // m3e 系列模型
  181. strings.Contains(model, "bge-") {
  182. testRequest.Model = model
  183. // Embedding 请求
  184. testRequest.Input = []string{"hello world"}
  185. return testRequest
  186. }
  187. // 并非Embedding 模型
  188. if strings.HasPrefix(model, "o") {
  189. testRequest.MaxCompletionTokens = 10
  190. } else if strings.Contains(model, "thinking") {
  191. if !strings.Contains(model, "claude") {
  192. testRequest.MaxTokens = 50
  193. }
  194. } else if strings.Contains(model, "gemini") {
  195. testRequest.MaxTokens = 3000
  196. } else {
  197. testRequest.MaxTokens = 10
  198. }
  199. testMessage := dto.Message{
  200. Role: "user",
  201. Content: "hi",
  202. }
  203. testRequest.Model = model
  204. testRequest.Messages = append(testRequest.Messages, testMessage)
  205. return testRequest
  206. }
  207. func TestChannel(c *gin.Context) {
  208. channelId, err := strconv.Atoi(c.Param("id"))
  209. if err != nil {
  210. c.JSON(http.StatusOK, gin.H{
  211. "success": false,
  212. "message": err.Error(),
  213. })
  214. return
  215. }
  216. channel, err := model.GetChannelById(channelId, true)
  217. if err != nil {
  218. c.JSON(http.StatusOK, gin.H{
  219. "success": false,
  220. "message": err.Error(),
  221. })
  222. return
  223. }
  224. testModel := c.Query("model")
  225. tik := time.Now()
  226. err, _ = testChannel(channel, testModel)
  227. tok := time.Now()
  228. milliseconds := tok.Sub(tik).Milliseconds()
  229. go channel.UpdateResponseTime(milliseconds)
  230. consumedTime := float64(milliseconds) / 1000.0
  231. if err != nil {
  232. c.JSON(http.StatusOK, gin.H{
  233. "success": false,
  234. "message": err.Error(),
  235. "time": consumedTime,
  236. })
  237. return
  238. }
  239. c.JSON(http.StatusOK, gin.H{
  240. "success": true,
  241. "message": "",
  242. "time": consumedTime,
  243. })
  244. return
  245. }
  246. var testAllChannelsLock sync.Mutex
  247. var testAllChannelsRunning bool = false
  248. func testAllChannels(notify bool) error {
  249. testAllChannelsLock.Lock()
  250. if testAllChannelsRunning {
  251. testAllChannelsLock.Unlock()
  252. return errors.New("测试已在运行中")
  253. }
  254. testAllChannelsRunning = true
  255. testAllChannelsLock.Unlock()
  256. channels, err := model.GetAllChannels(0, 0, true, false)
  257. if err != nil {
  258. return err
  259. }
  260. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  261. if disableThreshold == 0 {
  262. disableThreshold = 10000000 // a impossible value
  263. }
  264. gopool.Go(func() {
  265. // 使用 defer 确保无论如何都会重置运行状态,防止死锁
  266. defer func() {
  267. testAllChannelsLock.Lock()
  268. testAllChannelsRunning = false
  269. testAllChannelsLock.Unlock()
  270. }()
  271. for _, channel := range channels {
  272. isChannelEnabled := channel.Status == common.ChannelStatusEnabled
  273. tik := time.Now()
  274. err, openaiWithStatusErr := testChannel(channel, "")
  275. tok := time.Now()
  276. milliseconds := tok.Sub(tik).Milliseconds()
  277. shouldBanChannel := false
  278. // request error disables the channel
  279. if openaiWithStatusErr != nil {
  280. oaiErr := openaiWithStatusErr.Error
  281. err = errors.New(fmt.Sprintf("type %s, httpCode %d, code %v, message %s", oaiErr.Type, openaiWithStatusErr.StatusCode, oaiErr.Code, oaiErr.Message))
  282. shouldBanChannel = service.ShouldDisableChannel(channel.Type, openaiWithStatusErr)
  283. }
  284. if milliseconds > disableThreshold {
  285. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  286. shouldBanChannel = true
  287. }
  288. // disable channel
  289. if isChannelEnabled && shouldBanChannel && channel.GetAutoBan() {
  290. service.DisableChannel(channel.Id, channel.Name, err.Error())
  291. }
  292. // enable channel
  293. if !isChannelEnabled && service.ShouldEnableChannel(err, openaiWithStatusErr, channel.Status) {
  294. service.EnableChannel(channel.Id, channel.Name)
  295. }
  296. channel.UpdateResponseTime(milliseconds)
  297. time.Sleep(common.RequestInterval)
  298. }
  299. if notify {
  300. service.NotifyRootUser(dto.NotifyTypeChannelTest, "通道测试完成", "所有通道测试已完成")
  301. }
  302. })
  303. return nil
  304. }
  305. func TestAllChannels(c *gin.Context) {
  306. err := testAllChannels(true)
  307. if err != nil {
  308. c.JSON(http.StatusOK, gin.H{
  309. "success": false,
  310. "message": err.Error(),
  311. })
  312. return
  313. }
  314. c.JSON(http.StatusOK, gin.H{
  315. "success": true,
  316. "message": "",
  317. })
  318. return
  319. }
  320. func AutomaticallyTestChannels(frequency int) {
  321. for {
  322. time.Sleep(time.Duration(frequency) * time.Minute)
  323. common.SysLog("testing all channels")
  324. _ = testAllChannels(false)
  325. common.SysLog("channel test finished")
  326. }
  327. }