channel-test.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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) (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.ChannelStatusDisabled)
  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. if shouldDisableChannel(openaiErr, -1) {
  179. disableChannel(channel.Id, channel.Name, err.Error())
  180. }
  181. channel.UpdateResponseTime(milliseconds)
  182. time.Sleep(common.RequestInterval)
  183. }
  184. testAllChannelsLock.Lock()
  185. testAllChannelsRunning = false
  186. testAllChannelsLock.Unlock()
  187. if notify {
  188. err := common.SendEmail("通道测试完成", common.RootUserEmail, "通道测试完成,如果没有收到禁用通知,说明所有通道都正常")
  189. if err != nil {
  190. common.SysError(fmt.Sprintf("failed to send email: %s", err.Error()))
  191. }
  192. }
  193. }()
  194. return nil
  195. }
  196. func TestAllChannels(c *gin.Context) {
  197. err := testAllChannels(true)
  198. if err != nil {
  199. c.JSON(http.StatusOK, gin.H{
  200. "success": false,
  201. "message": err.Error(),
  202. })
  203. return
  204. }
  205. c.JSON(http.StatusOK, gin.H{
  206. "success": true,
  207. "message": "",
  208. })
  209. return
  210. }
  211. func AutomaticallyTestChannels(frequency int) {
  212. for {
  213. time.Sleep(time.Duration(frequency) * time.Minute)
  214. common.SysLog("testing all channels")
  215. _ = testAllChannels(false)
  216. common.SysLog("channel test finished")
  217. }
  218. }