channel-test.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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.ChannelTypePaLM:
  18. fallthrough
  19. case common.ChannelTypeAnthropic:
  20. fallthrough
  21. case common.ChannelTypeBaidu:
  22. fallthrough
  23. case common.ChannelTypeZhipu:
  24. return errors.New("该渠道类型当前版本不支持测试,请手动测试"), nil
  25. case common.ChannelTypeAzure:
  26. request.Model = "gpt-35-turbo"
  27. default:
  28. request.Model = "gpt-3.5-turbo"
  29. }
  30. requestURL := common.ChannelBaseURLs[channel.Type]
  31. if channel.Type == common.ChannelTypeAzure {
  32. requestURL = fmt.Sprintf("%s/openai/deployments/%s/chat/completions?api-version=2023-03-15-preview", channel.BaseURL, request.Model)
  33. } else {
  34. if channel.BaseURL != "" {
  35. requestURL = channel.BaseURL
  36. }
  37. requestURL += "/v1/chat/completions"
  38. }
  39. jsonData, err := json.Marshal(request)
  40. if err != nil {
  41. return err, nil
  42. }
  43. req, err := http.NewRequest("POST", requestURL, bytes.NewBuffer(jsonData))
  44. if err != nil {
  45. return err, nil
  46. }
  47. if channel.Type == common.ChannelTypeAzure {
  48. req.Header.Set("api-key", channel.Key)
  49. } else {
  50. req.Header.Set("Authorization", "Bearer "+channel.Key)
  51. }
  52. req.Header.Set("Content-Type", "application/json")
  53. resp, err := httpClient.Do(req)
  54. if err != nil {
  55. return err, nil
  56. }
  57. defer resp.Body.Close()
  58. var response TextResponse
  59. err = json.NewDecoder(resp.Body).Decode(&response)
  60. if err != nil {
  61. return err, nil
  62. }
  63. if response.Usage.CompletionTokens == 0 {
  64. return errors.New(fmt.Sprintf("type %s, code %v, message %s", response.Error.Type, response.Error.Code, response.Error.Message)), &response.Error
  65. }
  66. return nil, nil
  67. }
  68. func buildTestRequest() *ChatRequest {
  69. testRequest := &ChatRequest{
  70. Model: "", // this will be set later
  71. MaxTokens: 1,
  72. }
  73. testMessage := Message{
  74. Role: "user",
  75. Content: "hi",
  76. }
  77. testRequest.Messages = append(testRequest.Messages, testMessage)
  78. return testRequest
  79. }
  80. func TestChannel(c *gin.Context) {
  81. id, err := strconv.Atoi(c.Param("id"))
  82. if err != nil {
  83. c.JSON(http.StatusOK, gin.H{
  84. "success": false,
  85. "message": err.Error(),
  86. })
  87. return
  88. }
  89. channel, err := model.GetChannelById(id, true)
  90. if err != nil {
  91. c.JSON(http.StatusOK, gin.H{
  92. "success": false,
  93. "message": err.Error(),
  94. })
  95. return
  96. }
  97. testRequest := buildTestRequest()
  98. tik := time.Now()
  99. err, _ = testChannel(channel, *testRequest)
  100. tok := time.Now()
  101. milliseconds := tok.Sub(tik).Milliseconds()
  102. go channel.UpdateResponseTime(milliseconds)
  103. consumedTime := float64(milliseconds) / 1000.0
  104. if err != nil {
  105. c.JSON(http.StatusOK, gin.H{
  106. "success": false,
  107. "message": err.Error(),
  108. "time": consumedTime,
  109. })
  110. return
  111. }
  112. c.JSON(http.StatusOK, gin.H{
  113. "success": true,
  114. "message": "",
  115. "time": consumedTime,
  116. })
  117. return
  118. }
  119. var testAllChannelsLock sync.Mutex
  120. var testAllChannelsRunning bool = false
  121. // disable & notify
  122. func disableChannel(channelId int, channelName string, reason string) {
  123. if common.RootUserEmail == "" {
  124. common.RootUserEmail = model.GetRootUserEmail()
  125. }
  126. model.UpdateChannelStatusById(channelId, common.ChannelStatusDisabled)
  127. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  128. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  129. err := common.SendEmail(subject, common.RootUserEmail, content)
  130. if err != nil {
  131. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  132. }
  133. }
  134. func testAllChannels(notify bool) error {
  135. if common.RootUserEmail == "" {
  136. common.RootUserEmail = model.GetRootUserEmail()
  137. }
  138. testAllChannelsLock.Lock()
  139. if testAllChannelsRunning {
  140. testAllChannelsLock.Unlock()
  141. return errors.New("测试已在运行中")
  142. }
  143. testAllChannelsRunning = true
  144. testAllChannelsLock.Unlock()
  145. channels, err := model.GetAllChannels(0, 0, true)
  146. if err != nil {
  147. return err
  148. }
  149. testRequest := buildTestRequest()
  150. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  151. if disableThreshold == 0 {
  152. disableThreshold = 10000000 // a impossible value
  153. }
  154. go func() {
  155. for _, channel := range channels {
  156. if channel.Status != common.ChannelStatusEnabled {
  157. continue
  158. }
  159. tik := time.Now()
  160. err, openaiErr := testChannel(channel, *testRequest)
  161. tok := time.Now()
  162. milliseconds := tok.Sub(tik).Milliseconds()
  163. if milliseconds > disableThreshold {
  164. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  165. disableChannel(channel.Id, channel.Name, err.Error())
  166. }
  167. if shouldDisableChannel(openaiErr) {
  168. disableChannel(channel.Id, channel.Name, err.Error())
  169. }
  170. channel.UpdateResponseTime(milliseconds)
  171. time.Sleep(common.RequestInterval)
  172. }
  173. testAllChannelsLock.Lock()
  174. testAllChannelsRunning = false
  175. testAllChannelsLock.Unlock()
  176. if notify {
  177. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  178. if err != nil {
  179. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  180. }
  181. }
  182. }()
  183. return nil
  184. }
  185. func TestAllChannels(c *gin.Context) {
  186. err := testAllChannels(true)
  187. if err != nil {
  188. c.JSON(http.StatusOK, gin.H{
  189. "success": false,
  190. "message": err.Error(),
  191. })
  192. return
  193. }
  194. c.JSON(http.StatusOK, gin.H{
  195. "success": true,
  196. "message": "",
  197. })
  198. return
  199. }
  200. func AutomaticallyTestChannels(frequency int) {
  201. for {
  202. time.Sleep(time.Duration(frequency) * time.Minute)
  203. common.SysLog("testing all channels")
  204. _ = testAllChannels(false)
  205. common.SysLog("channel test finished")
  206. }
  207. }