channel-test.go 5.8 KB

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