channel-test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. content, _ := json.Marshal("hi")
  85. testMessage := Message{
  86. Role: "user",
  87. Content: content,
  88. }
  89. testRequest.Messages = append(testRequest.Messages, testMessage)
  90. return testRequest
  91. }
  92. func TestChannel(c *gin.Context) {
  93. id, err := strconv.Atoi(c.Param("id"))
  94. if err != nil {
  95. c.JSON(http.StatusOK, gin.H{
  96. "success": false,
  97. "message": err.Error(),
  98. })
  99. return
  100. }
  101. channel, err := model.GetChannelById(id, true)
  102. if err != nil {
  103. c.JSON(http.StatusOK, gin.H{
  104. "success": false,
  105. "message": err.Error(),
  106. })
  107. return
  108. }
  109. testRequest := buildTestRequest()
  110. tik := time.Now()
  111. err, _ = testChannel(channel, *testRequest)
  112. tok := time.Now()
  113. milliseconds := tok.Sub(tik).Milliseconds()
  114. go channel.UpdateResponseTime(milliseconds)
  115. consumedTime := float64(milliseconds) / 1000.0
  116. if err != nil {
  117. c.JSON(http.StatusOK, gin.H{
  118. "success": false,
  119. "message": err.Error(),
  120. "time": consumedTime,
  121. })
  122. return
  123. }
  124. c.JSON(http.StatusOK, gin.H{
  125. "success": true,
  126. "message": "",
  127. "time": consumedTime,
  128. })
  129. return
  130. }
  131. var testAllChannelsLock sync.Mutex
  132. var testAllChannelsRunning bool = false
  133. // disable & notify
  134. func disableChannel(channelId int, channelName string, reason string) {
  135. if common.RootUserEmail == "" {
  136. common.RootUserEmail = model.GetRootUserEmail()
  137. }
  138. model.UpdateChannelStatusById(channelId, common.ChannelStatusAutoDisabled)
  139. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  140. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  141. err := common.SendEmail(subject, common.RootUserEmail, content)
  142. if err != nil {
  143. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  144. }
  145. }
  146. func testAllChannels(notify bool) error {
  147. if common.RootUserEmail == "" {
  148. common.RootUserEmail = model.GetRootUserEmail()
  149. }
  150. testAllChannelsLock.Lock()
  151. if testAllChannelsRunning {
  152. testAllChannelsLock.Unlock()
  153. return errors.New("测试已在运行中")
  154. }
  155. testAllChannelsRunning = true
  156. testAllChannelsLock.Unlock()
  157. channels, err := model.GetAllChannels(0, 0, true)
  158. if err != nil {
  159. return err
  160. }
  161. testRequest := buildTestRequest()
  162. var disableThreshold = int64(common.ChannelDisableThreshold * 1000)
  163. if disableThreshold == 0 {
  164. disableThreshold = 10000000 // a impossible value
  165. }
  166. go func() {
  167. for _, channel := range channels {
  168. if channel.Status != common.ChannelStatusEnabled {
  169. continue
  170. }
  171. tik := time.Now()
  172. err, openaiErr := testChannel(channel, *testRequest)
  173. tok := time.Now()
  174. milliseconds := tok.Sub(tik).Milliseconds()
  175. ban := false
  176. if milliseconds > disableThreshold {
  177. err = errors.New(fmt.Sprintf("响应时间 %.2fs 超过阈值 %.2fs", float64(milliseconds)/1000.0, float64(disableThreshold)/1000.0))
  178. ban = true
  179. }
  180. if openaiErr != nil {
  181. err = errors.New(fmt.Sprintf("type %s, code %v, message %s", openaiErr.Type, openaiErr.Code, openaiErr.Message))
  182. ban = true
  183. }
  184. // parse *int to bool
  185. if channel.AutoBan != nil && *channel.AutoBan == 0 {
  186. ban = false
  187. }
  188. if shouldDisableChannel(openaiErr, -1) && ban {
  189. disableChannel(channel.Id, channel.Name, err.Error())
  190. }
  191. channel.UpdateResponseTime(milliseconds)
  192. time.Sleep(common.RequestInterval)
  193. }
  194. testAllChannelsLock.Lock()
  195. testAllChannelsRunning = false
  196. testAllChannelsLock.Unlock()
  197. if notify {
  198. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  199. if err != nil {
  200. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  201. }
  202. }
  203. }()
  204. return nil
  205. }
  206. func TestAllChannels(c *gin.Context) {
  207. err := testAllChannels(true)
  208. if err != nil {
  209. c.JSON(http.StatusOK, gin.H{
  210. "success": false,
  211. "message": err.Error(),
  212. })
  213. return
  214. }
  215. c.JSON(http.StatusOK, gin.H{
  216. "success": true,
  217. "message": "",
  218. })
  219. return
  220. }
  221. func AutomaticallyTestChannels(frequency int) {
  222. for {
  223. time.Sleep(time.Duration(frequency) * time.Minute)
  224. common.SysLog("testing all channels")
  225. _ = testAllChannels(false)
  226. common.SysLog("channel test finished")
  227. }
  228. }