channel-test.go 7.3 KB

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