channel-test.go 6.3 KB

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