channel.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package service
  2. import (
  3. "fmt"
  4. "net/http"
  5. "one-api/common"
  6. relaymodel "one-api/dto"
  7. "one-api/model"
  8. "strings"
  9. )
  10. // disable & notify
  11. func DisableChannel(channelId int, channelName string, reason string) {
  12. model.UpdateChannelStatusById(channelId, common.ChannelStatusAutoDisabled)
  13. subject := fmt.Sprintf("通道「%s」(#%d)已被禁用", channelName, channelId)
  14. content := fmt.Sprintf("通道「%s」(#%d)已被禁用,原因:%s", channelName, channelId, reason)
  15. notifyRootUser(subject, content)
  16. }
  17. func EnableChannel(channelId int, channelName string) {
  18. model.UpdateChannelStatusById(channelId, common.ChannelStatusEnabled)
  19. subject := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  20. content := fmt.Sprintf("通道「%s」(#%d)已被启用", channelName, channelId)
  21. notifyRootUser(subject, content)
  22. }
  23. func ShouldDisableChannel(err *relaymodel.OpenAIError, statusCode int) bool {
  24. if !common.AutomaticDisableChannelEnabled {
  25. return false
  26. }
  27. if err == nil {
  28. return false
  29. }
  30. if statusCode == http.StatusUnauthorized {
  31. return true
  32. }
  33. switch err.Code {
  34. case "invalid_api_key":
  35. return true
  36. case "account_deactivated":
  37. return true
  38. case "billing_not_active":
  39. return true
  40. }
  41. switch err.Type {
  42. case "insufficient_quota":
  43. return true
  44. // https://docs.anthropic.com/claude/reference/errors
  45. case "authentication_error":
  46. return true
  47. case "permission_error":
  48. return true
  49. case "forbidden":
  50. return true
  51. }
  52. if strings.HasPrefix(err.Message, "Your credit balance is too low") { // anthropic
  53. return true
  54. } else if strings.HasPrefix(err.Message, "This organization has been disabled.") {
  55. return true
  56. } else if strings.HasPrefix(err.Message, "You exceeded your current quota") {
  57. return true
  58. }
  59. return false
  60. }
  61. func ShouldEnableChannel(err error, openAIErr *relaymodel.OpenAIError, status int) bool {
  62. if !common.AutomaticEnableChannelEnabled {
  63. return false
  64. }
  65. if err != nil {
  66. return false
  67. }
  68. if openAIErr != nil {
  69. return false
  70. }
  71. if status != common.ChannelStatusAutoDisabled {
  72. return false
  73. }
  74. return true
  75. }