channel-test.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. switch channel.Type {
  17. case common.ChannelTypeAzure:
  18. request.Model = "gpt-35-turbo"
  19. default:
  20. request.Model = "gpt-3.5-turbo"
  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.BaseURL != "" {
  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.Usage.CompletionTokens == 0 {
  57. return errors.New(fmt.Sprintf("type %s, code %v, 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("failed to send email: %s", err.Error()))
  126. }
  127. }
  128. func testAllChannels(c *gin.Context) error {
  129. if common.RootUserEmail == "" {
  130. common.RootUserEmail = model.GetRootUserEmail()
  131. }
  132. testAllChannelsLock.Lock()
  133. if testAllChannelsRunning {
  134. testAllChannelsLock.Unlock()
  135. return errors.New("测试已在运行中")
  136. }
  137. testAllChannelsRunning = true
  138. testAllChannelsLock.Unlock()
  139. channels, err := model.GetAllChannels(0, 0, true)
  140. if err != nil {
  141. c.JSON(http.StatusOK, gin.H{
  142. "success": false,
  143. "message": err.Error(),
  144. })
  145. return err
  146. }
  147. testRequest := buildTestRequest(c)
  148. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  149. if disableThreshold == 0 {
  150. disableThreshold = 10000000 // a impossible value
  151. }
  152. go func() {
  153. for _, channel := range channels {
  154. if channel.Status != common.ChannelStatusEnabled {
  155. continue
  156. }
  157. tik := time.Now()
  158. err := testChannel(channel, *testRequest)
  159. tok := time.Now()
  160. milliseconds := tok.Sub(tik).Milliseconds()
  161. if err != nil || milliseconds > disableThreshold {
  162. if milliseconds > disableThreshold {
  163. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  164. }
  165. disableChannel(channel.Id, channel.Name, err.Error())
  166. }
  167. channel.UpdateResponseTime(milliseconds)
  168. }
  169. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  170. if err != nil {
  171. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  172. }
  173. testAllChannelsLock.Lock()
  174. testAllChannelsRunning = false
  175. testAllChannelsLock.Unlock()
  176. }()
  177. return nil
  178. }
  179. func TestAllChannels(c *gin.Context) {
  180. err := testAllChannels(c)
  181. if err != nil {
  182. c.JSON(http.StatusOK, gin.H{
  183. "success": false,
  184. "message": err.Error(),
  185. })
  186. return
  187. }
  188. c.JSON(http.StatusOK, gin.H{
  189. "success": true,
  190. "message": "",
  191. })
  192. return
  193. }