channel-test.go 6.4 KB

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