relay.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. package controller
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "net/http"
  6. "one-api/common"
  7. "strings"
  8. )
  9. type Message struct {
  10. Role string `json:"role"`
  11. Content string `json:"content"`
  12. Name *string `json:"name,omitempty"`
  13. }
  14. const (
  15. RelayModeUnknown = iota
  16. RelayModeChatCompletions
  17. RelayModeCompletions
  18. RelayModeEmbeddings
  19. RelayModeModeration
  20. RelayModeImagesGenerations
  21. )
  22. // https://platform.openai.com/docs/api-reference/chat
  23. type GeneralOpenAIRequest struct {
  24. Model string `json:"model"`
  25. Messages []Message `json:"messages"`
  26. Prompt any `json:"prompt"`
  27. Stream bool `json:"stream"`
  28. MaxTokens int `json:"max_tokens"`
  29. Temperature float64 `json:"temperature"`
  30. TopP float64 `json:"top_p"`
  31. N int `json:"n"`
  32. Input any `json:"input"`
  33. }
  34. type ChatRequest struct {
  35. Model string `json:"model"`
  36. Messages []Message `json:"messages"`
  37. MaxTokens int `json:"max_tokens"`
  38. }
  39. type TextRequest struct {
  40. Model string `json:"model"`
  41. Messages []Message `json:"messages"`
  42. Prompt string `json:"prompt"`
  43. MaxTokens int `json:"max_tokens"`
  44. //Stream bool `json:"stream"`
  45. }
  46. type Usage struct {
  47. PromptTokens int `json:"prompt_tokens"`
  48. CompletionTokens int `json:"completion_tokens"`
  49. TotalTokens int `json:"total_tokens"`
  50. }
  51. type OpenAIError struct {
  52. Message string `json:"message"`
  53. Type string `json:"type"`
  54. Param string `json:"param"`
  55. Code any `json:"code"`
  56. }
  57. type OpenAIErrorWithStatusCode struct {
  58. OpenAIError
  59. StatusCode int `json:"status_code"`
  60. }
  61. type TextResponse struct {
  62. Usage `json:"usage"`
  63. Error OpenAIError `json:"error"`
  64. }
  65. type ChatCompletionsStreamResponse struct {
  66. Choices []struct {
  67. Delta struct {
  68. Content string `json:"content"`
  69. } `json:"delta"`
  70. FinishReason string `json:"finish_reason"`
  71. } `json:"choices"`
  72. }
  73. type CompletionsStreamResponse struct {
  74. Choices []struct {
  75. Text string `json:"text"`
  76. FinishReason string `json:"finish_reason"`
  77. } `json:"choices"`
  78. }
  79. func Relay(c *gin.Context) {
  80. relayMode := RelayModeUnknown
  81. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  82. relayMode = RelayModeChatCompletions
  83. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  84. relayMode = RelayModeCompletions
  85. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  86. relayMode = RelayModeEmbeddings
  87. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  88. relayMode = RelayModeModeration
  89. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  90. relayMode = RelayModeImagesGenerations
  91. }
  92. var err *OpenAIErrorWithStatusCode
  93. switch relayMode {
  94. case RelayModeImagesGenerations:
  95. err = relayImageHelper(c, relayMode)
  96. default:
  97. err = relayTextHelper(c, relayMode)
  98. }
  99. if err != nil {
  100. if err.StatusCode == http.StatusTooManyRequests {
  101. err.OpenAIError.Message = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  102. }
  103. c.JSON(err.StatusCode, gin.H{
  104. "error": err.OpenAIError,
  105. })
  106. channelId := c.GetInt("channel_id")
  107. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  108. // https://platform.openai.com/docs/guides/error-codes/api-errors
  109. if common.AutomaticDisableChannelEnabled && (err.Type == "insufficient_quota" || err.Code == "invalid_api_key") {
  110. channelId := c.GetInt("channel_id")
  111. channelName := c.GetString("channel_name")
  112. disableChannel(channelId, channelName, err.Message)
  113. }
  114. }
  115. }
  116. func RelayNotImplemented(c *gin.Context) {
  117. err := OpenAIError{
  118. Message: "API not implemented",
  119. Type: "one_api_error",
  120. Param: "",
  121. Code: "api_not_implemented",
  122. }
  123. c.JSON(http.StatusNotImplemented, gin.H{
  124. "error": err,
  125. })
  126. }
  127. func RelayNotFound(c *gin.Context) {
  128. err := OpenAIError{
  129. Message: fmt.Sprintf("API not found: %s:%s", c.Request.Method, c.Request.URL.Path),
  130. Type: "one_api_error",
  131. Param: "",
  132. Code: "api_not_found",
  133. }
  134. c.JSON(http.StatusNotFound, gin.H{
  135. "error": err,
  136. })
  137. }