relay.go 4.9 KB

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