relay.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 OpenAITextResponseChoice struct {
  75. Index int `json:"index"`
  76. Message `json:"message"`
  77. FinishReason string `json:"finish_reason"`
  78. }
  79. type OpenAITextResponse struct {
  80. Id string `json:"id"`
  81. Object string `json:"object"`
  82. Created int64 `json:"created"`
  83. Choices []OpenAITextResponseChoice `json:"choices"`
  84. Usage `json:"usage"`
  85. }
  86. type OpenAIEmbeddingResponseItem struct {
  87. Object string `json:"object"`
  88. Index int `json:"index"`
  89. Embedding []float64 `json:"embedding"`
  90. }
  91. type OpenAIEmbeddingResponse struct {
  92. Object string `json:"object"`
  93. Data []OpenAIEmbeddingResponseItem `json:"data"`
  94. Model string `json:"model"`
  95. Usage `json:"usage"`
  96. }
  97. type ImageResponse struct {
  98. Created int `json:"created"`
  99. Data []struct {
  100. Url string `json:"url"`
  101. }
  102. }
  103. type ChatCompletionsStreamResponseChoice struct {
  104. Delta struct {
  105. Content string `json:"content"`
  106. } `json:"delta"`
  107. FinishReason string `json:"finish_reason,omitempty"`
  108. }
  109. type ChatCompletionsStreamResponse struct {
  110. Id string `json:"id"`
  111. Object string `json:"object"`
  112. Created int64 `json:"created"`
  113. Model string `json:"model"`
  114. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  115. }
  116. type CompletionsStreamResponse struct {
  117. Choices []struct {
  118. Text string `json:"text"`
  119. FinishReason string `json:"finish_reason"`
  120. } `json:"choices"`
  121. }
  122. func Relay(c *gin.Context) {
  123. relayMode := RelayModeUnknown
  124. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  125. relayMode = RelayModeChatCompletions
  126. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  127. relayMode = RelayModeCompletions
  128. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  129. relayMode = RelayModeEmbeddings
  130. } else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  131. relayMode = RelayModeEmbeddings
  132. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  133. relayMode = RelayModeModerations
  134. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  135. relayMode = RelayModeImagesGenerations
  136. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
  137. relayMode = RelayModeEdits
  138. }
  139. var err *OpenAIErrorWithStatusCode
  140. switch relayMode {
  141. case RelayModeImagesGenerations:
  142. err = relayImageHelper(c, relayMode)
  143. default:
  144. err = relayTextHelper(c, relayMode)
  145. }
  146. if err != nil {
  147. retryTimesStr := c.Query("retry")
  148. retryTimes, _ := strconv.Atoi(retryTimesStr)
  149. if retryTimesStr == "" {
  150. retryTimes = common.RetryTimes
  151. }
  152. if retryTimes > 0 {
  153. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  154. } else {
  155. if err.StatusCode == http.StatusTooManyRequests {
  156. err.OpenAIError.Message = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  157. }
  158. c.JSON(err.StatusCode, gin.H{
  159. "error": err.OpenAIError,
  160. })
  161. }
  162. channelId := c.GetInt("channel_id")
  163. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  164. // https://platform.openai.com/docs/guides/error-codes/api-errors
  165. if shouldDisableChannel(&err.OpenAIError) {
  166. channelId := c.GetInt("channel_id")
  167. channelName := c.GetString("channel_name")
  168. disableChannel(channelId, channelName, err.Message)
  169. }
  170. }
  171. }
  172. func RelayNotImplemented(c *gin.Context) {
  173. err := OpenAIError{
  174. Message: "API not implemented",
  175. Type: "one_api_error",
  176. Param: "",
  177. Code: "api_not_implemented",
  178. }
  179. c.JSON(http.StatusNotImplemented, gin.H{
  180. "error": err,
  181. })
  182. }
  183. func RelayNotFound(c *gin.Context) {
  184. err := OpenAIError{
  185. Message: fmt.Sprintf("API not found: %s:%s", c.Request.Method, c.Request.URL.Path),
  186. Type: "one_api_error",
  187. Param: "",
  188. Code: "api_not_found",
  189. }
  190. c.JSON(http.StatusNotFound, gin.H{
  191. "error": err,
  192. })
  193. }