channel-test.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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.Type == common.ChannelTypeCustom {
  27. requestURL = channel.BaseURL
  28. } else if channel.Type == common.ChannelTypeOpenAI && channel.BaseURL != "" {
  29. requestURL = channel.BaseURL
  30. }
  31. requestURL += "/v1/chat/completions"
  32. }
  33. jsonData, err := json.Marshal(request)
  34. if err != nil {
  35. return err
  36. }
  37. req, err := http.NewRequest("POST", requestURL, bytes.NewBuffer(jsonData))
  38. if err != nil {
  39. return err
  40. }
  41. if channel.Type == common.ChannelTypeAzure {
  42. req.Header.Set("api-key", channel.Key)
  43. } else {
  44. req.Header.Set("Authorization", "Bearer "+channel.Key)
  45. }
  46. req.Header.Set("Content-Type", "application/json")
  47. client := &http.Client{}
  48. resp, err := client.Do(req)
  49. if err != nil {
  50. return err
  51. }
  52. defer resp.Body.Close()
  53. var response TextResponse
  54. err = json.NewDecoder(resp.Body).Decode(&response)
  55. if err != nil {
  56. return err
  57. }
  58. if response.Usage.CompletionTokens == 0 {
  59. return errors.New(fmt.Sprintf("type %s, code %v, message %s", response.Error.Type, response.Error.Code, response.Error.Message))
  60. }
  61. return nil
  62. }
  63. func buildTestRequest(c *gin.Context) *ChatRequest {
  64. model_ := c.Query("model")
  65. testRequest := &ChatRequest{
  66. Model: model_,
  67. MaxTokens: 1,
  68. }
  69. testMessage := Message{
  70. Role: "user",
  71. Content: "hi",
  72. }
  73. testRequest.Messages = append(testRequest.Messages, testMessage)
  74. return testRequest
  75. }
  76. func TestChannel(c *gin.Context) {
  77. id, err := strconv.Atoi(c.Param("id"))
  78. if err != nil {
  79. c.JSON(http.StatusOK, gin.H{
  80. "success": false,
  81. "message": err.Error(),
  82. })
  83. return
  84. }
  85. channel, err := model.GetChannelById(id, true)
  86. if err != nil {
  87. c.JSON(http.StatusOK, gin.H{
  88. "success": false,
  89. "message": err.Error(),
  90. })
  91. return
  92. }
  93. testRequest := buildTestRequest(c)
  94. tik := time.Now()
  95. err = testChannel(channel, *testRequest)
  96. tok := time.Now()
  97. milliseconds := tok.Sub(tik).Milliseconds()
  98. go channel.UpdateResponseTime(milliseconds)
  99. consumedTime := float64(milliseconds) / 1000.0
  100. if err != nil {
  101. c.JSON(http.StatusOK, gin.H{
  102. "success": false,
  103. "message": err.Error(),
  104. "time": consumedTime,
  105. })
  106. return
  107. }
  108. c.JSON(http.StatusOK, gin.H{
  109. "success": true,
  110. "message": "",
  111. "time": consumedTime,
  112. })
  113. return
  114. }
  115. var testAllChannelsLock sync.Mutex
  116. var testAllChannelsRunning bool = false
  117. // disable & notify
  118. func disableChannel(channelId int, channelName string, reason string) {
  119. if common.RootUserEmail == "" {
  120. common.RootUserEmail = model.GetRootUserEmail()
  121. }
  122. model.UpdateChannelStatusById(channelId, common.ChannelStatusDisabled)
  123. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  124. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  125. err := common.SendEmail(subject, common.RootUserEmail, content)
  126. if err != nil {
  127. common.SysError(fmt.Sprintf("发送邮件失败:%s", err.Error()))
  128. }
  129. }
  130. func testAllChannels(c *gin.Context) error {
  131. if common.RootUserEmail == "" {
  132. common.RootUserEmail = model.GetRootUserEmail()
  133. }
  134. testAllChannelsLock.Lock()
  135. if testAllChannelsRunning {
  136. testAllChannelsLock.Unlock()
  137. return errors.New("测试已在运行中")
  138. }
  139. testAllChannelsRunning = true
  140. testAllChannelsLock.Unlock()
  141. channels, err := model.GetAllChannels(0, 0, true)
  142. if err != nil {
  143. c.JSON(http.StatusOK, gin.H{
  144. "success": false,
  145. "message": err.Error(),
  146. })
  147. return err
  148. }
  149. testRequest := buildTestRequest(c)
  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 := testChannel(channel, *testRequest)
  161. tok := time.Now()
  162. milliseconds := tok.Sub(tik).Milliseconds()
  163. if err != nil || milliseconds > disableThreshold {
  164. if milliseconds > disableThreshold {
  165. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  166. }
  167. disableChannel(channel.Id, channel.Name, err.Error())
  168. }
  169. channel.UpdateResponseTime(milliseconds)
  170. }
  171. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  172. if err != nil {
  173. common.SysError(fmt.Sprintf("发送邮件失败:%s", err.Error()))
  174. }
  175. testAllChannelsLock.Lock()
  176. testAllChannelsRunning = false
  177. testAllChannelsLock.Unlock()
  178. }()
  179. return nil
  180. }
  181. func TestAllChannels(c *gin.Context) {
  182. err := testAllChannels(c)
  183. if err != nil {
  184. c.JSON(http.StatusOK, gin.H{
  185. "success": false,
  186. "message": err.Error(),
  187. })
  188. return
  189. }
  190. c.JSON(http.StatusOK, gin.H{
  191. "success": true,
  192. "message": "",
  193. })
  194. return
  195. }