relay.go 6.0 KB

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