channel-test.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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() *ChatRequest {
  62. testRequest := &ChatRequest{
  63. Model: "", // this will be set later
  64. MaxTokens: 1,
  65. }
  66. testMessage := Message{
  67. Role: "user",
  68. Content: "hi",
  69. }
  70. testRequest.Messages = append(testRequest.Messages, testMessage)
  71. return testRequest
  72. }
  73. func TestChannel(c *gin.Context) {
  74. id, err := strconv.Atoi(c.Param("id"))
  75. if err != nil {
  76. c.JSON(http.StatusOK, gin.H{
  77. "success": false,
  78. "message": err.Error(),
  79. })
  80. return
  81. }
  82. channel, err := model.GetChannelById(id, true)
  83. if err != nil {
  84. c.JSON(http.StatusOK, gin.H{
  85. "success": false,
  86. "message": err.Error(),
  87. })
  88. return
  89. }
  90. testRequest := buildTestRequest()
  91. tik := time.Now()
  92. err = testChannel(channel, *testRequest)
  93. tok := time.Now()
  94. milliseconds := tok.Sub(tik).Milliseconds()
  95. go channel.UpdateResponseTime(milliseconds)
  96. consumedTime := float64(milliseconds) / 1000.0
  97. if err != nil {
  98. c.JSON(http.StatusOK, gin.H{
  99. "success": false,
  100. "message": err.Error(),
  101. "time": consumedTime,
  102. })
  103. return
  104. }
  105. c.JSON(http.StatusOK, gin.H{
  106. "success": true,
  107. "message": "",
  108. "time": consumedTime,
  109. })
  110. return
  111. }
  112. var testAllChannelsLock sync.Mutex
  113. var testAllChannelsRunning bool = false
  114. // disable & notify
  115. func disableChannel(channelId int, channelName string, reason string) {
  116. if common.RootUserEmail == "" {
  117. common.RootUserEmail = model.GetRootUserEmail()
  118. }
  119. model.UpdateChannelStatusById(channelId, common.ChannelStatusDisabled)
  120. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  121. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  122. err := common.SendEmail(subject, common.RootUserEmail, content)
  123. if err != nil {
  124. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  125. }
  126. }
  127. func testAllChannels(notify bool) error {
  128. if common.RootUserEmail == "" {
  129. common.RootUserEmail = model.GetRootUserEmail()
  130. }
  131. testAllChannelsLock.Lock()
  132. if testAllChannelsRunning {
  133. testAllChannelsLock.Unlock()
  134. return errors.New("测试已在运行中")
  135. }
  136. testAllChannelsRunning = true
  137. testAllChannelsLock.Unlock()
  138. channels, err := model.GetAllChannels(0, 0, true)
  139. if err != nil {
  140. return err
  141. }
  142. testRequest := buildTestRequest()
  143. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  144. if disableThreshold == 0 {
  145. disableThreshold = 10000000 // a impossible value
  146. }
  147. go func() {
  148. for _, channel := range channels {
  149. if channel.Status != common.ChannelStatusEnabled {
  150. continue
  151. }
  152. tik := time.Now()
  153. err := testChannel(channel, *testRequest)
  154. tok := time.Now()
  155. milliseconds := tok.Sub(tik).Milliseconds()
  156. if err != nil || milliseconds > disableThreshold {
  157. if milliseconds > disableThreshold {
  158. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  159. }
  160. disableChannel(channel.Id, channel.Name, err.Error())
  161. }
  162. channel.UpdateResponseTime(milliseconds)
  163. time.Sleep(common.RequestInterval)
  164. }
  165. testAllChannelsLock.Lock()
  166. testAllChannelsRunning = false
  167. testAllChannelsLock.Unlock()
  168. if notify {
  169. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  170. if err != nil {
  171. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  172. }
  173. }
  174. }()
  175. return nil
  176. }
  177. func TestAllChannels(c *gin.Context) {
  178. err := testAllChannels(true)
  179. if err != nil {
  180. c.JSON(http.StatusOK, gin.H{
  181. "success": false,
  182. "message": err.Error(),
  183. })
  184. return
  185. }
  186. c.JSON(http.StatusOK, gin.H{
  187. "success": true,
  188. "message": "",
  189. })
  190. return
  191. }
  192. func AutomaticallyTestChannels(frequency int) {
  193. for {
  194. time.Sleep(time.Duration(frequency) * time.Minute)
  195. common.SysLog("testing all channels")
  196. _ = testAllChannels(false)
  197. common.SysLog("channel test finished")
  198. }
  199. }