relay.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. Functions any `json:"functions,omitempty"`
  38. }
  39. type ChatRequest struct {
  40. Model string `json:"model"`
  41. Messages []Message `json:"messages"`
  42. MaxTokens int `json:"max_tokens"`
  43. }
  44. type TextRequest struct {
  45. Model string `json:"model"`
  46. Messages []Message `json:"messages"`
  47. Prompt string `json:"prompt"`
  48. MaxTokens int `json:"max_tokens"`
  49. //Stream bool `json:"stream"`
  50. }
  51. type ImageRequest struct {
  52. Prompt string `json:"prompt"`
  53. N int `json:"n"`
  54. Size string `json:"size"`
  55. }
  56. type Usage struct {
  57. PromptTokens int `json:"prompt_tokens"`
  58. CompletionTokens int `json:"completion_tokens"`
  59. TotalTokens int `json:"total_tokens"`
  60. }
  61. type OpenAIError struct {
  62. Message string `json:"message"`
  63. Type string `json:"type"`
  64. Param string `json:"param"`
  65. Code any `json:"code"`
  66. }
  67. type OpenAIErrorWithStatusCode struct {
  68. OpenAIError
  69. StatusCode int `json:"status_code"`
  70. }
  71. type TextResponse struct {
  72. Choices []OpenAITextResponseChoice `json:"choices"`
  73. Usage `json:"usage"`
  74. Error OpenAIError `json:"error"`
  75. }
  76. type OpenAITextResponseChoice struct {
  77. Index int `json:"index"`
  78. Message `json:"message"`
  79. FinishReason string `json:"finish_reason"`
  80. }
  81. type OpenAITextResponse struct {
  82. Id string `json:"id"`
  83. Object string `json:"object"`
  84. Created int64 `json:"created"`
  85. Choices []OpenAITextResponseChoice `json:"choices"`
  86. Usage `json:"usage"`
  87. }
  88. type OpenAIEmbeddingResponseItem struct {
  89. Object string `json:"object"`
  90. Index int `json:"index"`
  91. Embedding []float64 `json:"embedding"`
  92. }
  93. type OpenAIEmbeddingResponse struct {
  94. Object string `json:"object"`
  95. Data []OpenAIEmbeddingResponseItem `json:"data"`
  96. Model string `json:"model"`
  97. Usage `json:"usage"`
  98. }
  99. type ImageResponse struct {
  100. Created int `json:"created"`
  101. Data []struct {
  102. Url string `json:"url"`
  103. }
  104. }
  105. type ChatCompletionsStreamResponseChoice struct {
  106. Delta struct {
  107. Content string `json:"content"`
  108. } `json:"delta"`
  109. FinishReason *string `json:"finish_reason"`
  110. }
  111. type ChatCompletionsStreamResponse struct {
  112. Id string `json:"id"`
  113. Object string `json:"object"`
  114. Created int64 `json:"created"`
  115. Model string `json:"model"`
  116. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  117. }
  118. type CompletionsStreamResponse struct {
  119. Choices []struct {
  120. Text string `json:"text"`
  121. FinishReason string `json:"finish_reason"`
  122. } `json:"choices"`
  123. }
  124. func Relay(c *gin.Context) {
  125. relayMode := RelayModeUnknown
  126. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  127. relayMode = RelayModeChatCompletions
  128. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  129. relayMode = RelayModeCompletions
  130. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  131. relayMode = RelayModeEmbeddings
  132. } else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  133. relayMode = RelayModeEmbeddings
  134. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  135. relayMode = RelayModeModerations
  136. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  137. relayMode = RelayModeImagesGenerations
  138. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
  139. relayMode = RelayModeEdits
  140. }
  141. var err *OpenAIErrorWithStatusCode
  142. switch relayMode {
  143. case RelayModeImagesGenerations:
  144. err = relayImageHelper(c, relayMode)
  145. default:
  146. err = relayTextHelper(c, relayMode)
  147. }
  148. if err != nil {
  149. retryTimesStr := c.Query("retry")
  150. retryTimes, _ := strconv.Atoi(retryTimesStr)
  151. if retryTimesStr == "" {
  152. retryTimes = common.RetryTimes
  153. }
  154. if retryTimes > 0 {
  155. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  156. } else {
  157. if err.StatusCode == http.StatusTooManyRequests {
  158. err.OpenAIError.Message = "当前分组上游负载已饱和,请稍后再试"
  159. }
  160. c.JSON(err.StatusCode, gin.H{
  161. "error": err.OpenAIError,
  162. })
  163. }
  164. channelId := c.GetInt("channel_id")
  165. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  166. // https://platform.openai.com/docs/guides/error-codes/api-errors
  167. if shouldDisableChannel(&err.OpenAIError, err.StatusCode) {
  168. channelId := c.GetInt("channel_id")
  169. channelName := c.GetString("channel_name")
  170. disableChannel(channelId, channelName, err.Message)
  171. }
  172. }
  173. }
  174. func RelayNotImplemented(c *gin.Context) {
  175. err := OpenAIError{
  176. Message: "API not implemented",
  177. Type: "one_api_error",
  178. Param: "",
  179. Code: "api_not_implemented",
  180. }
  181. c.JSON(http.StatusNotImplemented, gin.H{
  182. "error": err,
  183. })
  184. }
  185. func RelayNotFound(c *gin.Context) {
  186. err := OpenAIError{
  187. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  188. Type: "invalid_request_error",
  189. Param: "",
  190. Code: "",
  191. }
  192. c.JSON(http.StatusNotFound, gin.H{
  193. "error": err,
  194. })
  195. }