relay.go 6.6 KB

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