channel-test.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package controller
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/model"
  11. "strconv"
  12. "sync"
  13. "time"
  14. )
  15. func testChannel(channel *model.Channel, request *ChatRequest) error {
  16. if request.Model == "" {
  17. request.Model = "gpt-3.5-turbo"
  18. if channel.Type == common.ChannelTypeAzure {
  19. request.Model = "gpt-35-turbo"
  20. }
  21. }
  22. requestURL := common.ChannelBaseURLs[channel.Type]
  23. if channel.Type == common.ChannelTypeAzure {
  24. requestURL = fmt.Sprintf("%s/openai/deployments/%s/chat/completions?api-version=2023-03-15-preview", channel.BaseURL, request.Model)
  25. } else {
  26. if channel.Type == common.ChannelTypeCustom {
  27. requestURL = channel.BaseURL
  28. }
  29. requestURL += "/v1/chat/completions"
  30. }
  31. jsonData, err := json.Marshal(request)
  32. if err != nil {
  33. return err
  34. }
  35. req, err := http.NewRequest("POST", requestURL, bytes.NewBuffer(jsonData))
  36. if err != nil {
  37. return err
  38. }
  39. if channel.Type == common.ChannelTypeAzure {
  40. req.Header.Set("api-key", channel.Key)
  41. } else {
  42. req.Header.Set("Authorization", "Bearer "+channel.Key)
  43. }
  44. req.Header.Set("Content-Type", "application/json")
  45. client := &http.Client{}
  46. resp, err := client.Do(req)
  47. if err != nil {
  48. return err
  49. }
  50. defer resp.Body.Close()
  51. var response TextResponse
  52. err = json.NewDecoder(resp.Body).Decode(&response)
  53. if err != nil {
  54. return err
  55. }
  56. if response.Error.Message != "" || response.Error.Code != "" {
  57. return errors.New(fmt.Sprintf("type %s, code %s, message %s", response.Error.Type, response.Error.Code, response.Error.Message))
  58. }
  59. return nil
  60. }
  61. func buildTestRequest(c *gin.Context) *ChatRequest {
  62. model_ := c.Query("model")
  63. testRequest := &ChatRequest{
  64. Model: model_,
  65. MaxTokens: 1,
  66. }
  67. testMessage := Message{
  68. Role: "user",
  69. Content: "hi",
  70. }
  71. testRequest.Messages = append(testRequest.Messages, testMessage)
  72. return testRequest
  73. }
  74. func TestChannel(c *gin.Context) {
  75. id, err := strconv.Atoi(c.Param("id"))
  76. if err != nil {
  77. c.JSON(http.StatusOK, gin.H{
  78. "success": false,
  79. "message": err.Error(),
  80. })
  81. return
  82. }
  83. channel, err := model.GetChannelById(id, true)
  84. if err != nil {
  85. c.JSON(http.StatusOK, gin.H{
  86. "success": false,
  87. "message": err.Error(),
  88. })
  89. return
  90. }
  91. testRequest := buildTestRequest(c)
  92. tik := time.Now()
  93. err = testChannel(channel, testRequest)
  94. tok := time.Now()
  95. milliseconds := tok.Sub(tik).Milliseconds()
  96. go channel.UpdateResponseTime(milliseconds)
  97. consumedTime := float64(milliseconds) / 1000.0
  98. if err != nil {
  99. c.JSON(http.StatusOK, gin.H{
  100. "success": false,
  101. "message": err.Error(),
  102. "time": consumedTime,
  103. })
  104. return
  105. }
  106. c.JSON(http.StatusOK, gin.H{
  107. "success": true,
  108. "message": "",
  109. "time": consumedTime,
  110. })
  111. return
  112. }
  113. var testAllChannelsLock sync.Mutex
  114. var testAllChannelsRunning bool = false
  115. // disable & notify
  116. func disableChannel(channelId int, channelName string, reason string) {
  117. if common.RootUserEmail == "" {
  118. common.RootUserEmail = model.GetRootUserEmail()
  119. }
  120. model.UpdateChannelStatusById(channelId, common.ChannelStatusDisabled)
  121. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  122. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  123. err := common.SendEmail(subject, common.RootUserEmail, content)
  124. if err != nil {
  125. common.SysError(fmt.Sprintf("发送邮件失败:%s", err.Error()))
  126. }
  127. }
  128. func testAllChannels(c *gin.Context) error {
  129. testAllChannelsLock.Lock()
  130. if testAllChannelsRunning {
  131. testAllChannelsLock.Unlock()
  132. return errors.New("测试已在运行中")
  133. }
  134. testAllChannelsRunning = true
  135. testAllChannelsLock.Unlock()
  136. channels, err := model.GetAllChannels(0, 0, true)
  137. if err != nil {
  138. c.JSON(http.StatusOK, gin.H{
  139. "success": false,
  140. "message": err.Error(),
  141. })
  142. return err
  143. }
  144. testRequest := buildTestRequest(c)
  145. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  146. if disableThreshold == 0 {
  147. disableThreshold = 10000000 // a impossible value
  148. }
  149. go func() {
  150. for _, channel := range channels {
  151. if channel.Status != common.ChannelStatusEnabled {
  152. continue
  153. }
  154. tik := time.Now()
  155. err := testChannel(channel, testRequest)
  156. tok := time.Now()
  157. milliseconds := tok.Sub(tik).Milliseconds()
  158. if err != nil || milliseconds > disableThreshold {
  159. if milliseconds > disableThreshold {
  160. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  161. }
  162. disableChannel(channel.Id, channel.Name, err.Error())
  163. }
  164. channel.UpdateResponseTime(milliseconds)
  165. }
  166. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  167. if err != nil {
  168. common.SysError(fmt.Sprintf("发送邮件失败:%s", err.Error()))
  169. }
  170. testAllChannelsLock.Lock()
  171. testAllChannelsRunning = false
  172. testAllChannelsLock.Unlock()
  173. }()
  174. return nil
  175. }
  176. func TestAllChannels(c *gin.Context) {
  177. err := testAllChannels(c)
  178. if err != nil {
  179. c.JSON(http.StatusOK, gin.H{
  180. "success": false,
  181. "message": err.Error(),
  182. })
  183. return
  184. }
  185. c.JSON(http.StatusOK, gin.H{
  186. "success": true,
  187. "message": "",
  188. })
  189. return
  190. }