channel-test.go 7.2 KB

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