channel-test.go 7.1 KB

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