channel-test.go 6.3 KB

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