channel-test.go 6.1 KB

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