channel-test.go 5.4 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, *OpenAIError) {
  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, nil
  34. }
  35. req, err := http.NewRequest("POST", requestURL, bytes.NewBuffer(jsonData))
  36. if err != nil {
  37. return err, nil
  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. resp, err := httpClient.Do(req)
  46. if err != nil {
  47. return err, nil
  48. }
  49. defer resp.Body.Close()
  50. var response TextResponse
  51. err = json.NewDecoder(resp.Body).Decode(&response)
  52. if err != nil {
  53. return err, nil
  54. }
  55. if response.Usage.CompletionTokens == 0 {
  56. return errors.New(fmt.Sprintf("type %s, code %v, message %s", response.Error.Type, response.Error.Code, response.Error.Message)), &response.Error
  57. }
  58. return nil, nil
  59. }
  60. func buildTestRequest() *ChatRequest {
  61. testRequest := &ChatRequest{
  62. Model: "", // this will be set later
  63. MaxTokens: 1,
  64. }
  65. testMessage := Message{
  66. Role: "user",
  67. Content: "hi",
  68. }
  69. testRequest.Messages = append(testRequest.Messages, testMessage)
  70. return testRequest
  71. }
  72. func TestChannel(c *gin.Context) {
  73. id, err := strconv.Atoi(c.Param("id"))
  74. if err != nil {
  75. c.JSON(http.StatusOK, gin.H{
  76. "success": false,
  77. "message": err.Error(),
  78. })
  79. return
  80. }
  81. channel, err := model.GetChannelById(id, true)
  82. if err != nil {
  83. c.JSON(http.StatusOK, gin.H{
  84. "success": false,
  85. "message": err.Error(),
  86. })
  87. return
  88. }
  89. testRequest := buildTestRequest()
  90. tik := time.Now()
  91. err, _ = testChannel(channel, *testRequest)
  92. tok := time.Now()
  93. milliseconds := tok.Sub(tik).Milliseconds()
  94. go channel.UpdateResponseTime(milliseconds)
  95. consumedTime := float64(milliseconds) / 1000.0
  96. if err != nil {
  97. c.JSON(http.StatusOK, gin.H{
  98. "success": false,
  99. "message": err.Error(),
  100. "time": consumedTime,
  101. })
  102. return
  103. }
  104. c.JSON(http.StatusOK, gin.H{
  105. "success": true,
  106. "message": "",
  107. "time": consumedTime,
  108. })
  109. return
  110. }
  111. var testAllChannelsLock sync.Mutex
  112. var testAllChannelsRunning bool = false
  113. // disable & notify
  114. func disableChannel(channelId int, channelName string, reason string) {
  115. if common.RootUserEmail == "" {
  116. common.RootUserEmail = model.GetRootUserEmail()
  117. }
  118. model.UpdateChannelStatusById(channelId, common.ChannelStatusDisabled)
  119. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  120. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  121. err := common.SendEmail(subject, common.RootUserEmail, content)
  122. if err != nil {
  123. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  124. }
  125. }
  126. func testAllChannels(notify bool) error {
  127. if common.RootUserEmail == "" {
  128. common.RootUserEmail = model.GetRootUserEmail()
  129. }
  130. testAllChannelsLock.Lock()
  131. if testAllChannelsRunning {
  132. testAllChannelsLock.Unlock()
  133. return errors.New("测试已在运行中")
  134. }
  135. testAllChannelsRunning = true
  136. testAllChannelsLock.Unlock()
  137. channels, err := model.GetAllChannels(0, 0, true)
  138. if err != nil {
  139. return err
  140. }
  141. testRequest := buildTestRequest()
  142. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  143. if disableThreshold == 0 {
  144. disableThreshold = 10000000 // a impossible value
  145. }
  146. go func() {
  147. for _, channel := range channels {
  148. if channel.Status != common.ChannelStatusEnabled {
  149. continue
  150. }
  151. tik := time.Now()
  152. err, openaiErr := testChannel(channel, *testRequest)
  153. tok := time.Now()
  154. milliseconds := tok.Sub(tik).Milliseconds()
  155. if milliseconds > disableThreshold {
  156. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  157. disableChannel(channel.Id, channel.Name, err.Error())
  158. }
  159. if shouldDisableChannel(openaiErr) {
  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. }