relay.go 6.2 KB

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