relay.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package controller
  2. import (
  3. "fmt"
  4. "log"
  5. "net/http"
  6. "one-api/common"
  7. "strconv"
  8. "strings"
  9. "github.com/gin-gonic/gin"
  10. )
  11. type Message struct {
  12. Role string `json:"role"`
  13. Content string `json:"content"`
  14. Name *string `json:"name,omitempty"`
  15. }
  16. const (
  17. RelayModeUnknown = iota
  18. RelayModeChatCompletions
  19. RelayModeCompletions
  20. RelayModeEmbeddings
  21. RelayModeModerations
  22. RelayModeImagesGenerations
  23. RelayModeEdits
  24. RelayModeMidjourneyImagine
  25. RelayModeMidjourneyChange
  26. RelayModeMidjourneyNotify
  27. RelayModeMidjourneyTaskFetch
  28. )
  29. // https://platform.openai.com/docs/api-reference/chat
  30. type GeneralOpenAIRequest struct {
  31. Model string `json:"model,omitempty"`
  32. Messages []Message `json:"messages,omitempty"`
  33. Prompt any `json:"prompt,omitempty"`
  34. Stream bool `json:"stream,omitempty"`
  35. MaxTokens int `json:"max_tokens,omitempty"`
  36. Temperature float64 `json:"temperature,omitempty"`
  37. TopP float64 `json:"top_p,omitempty"`
  38. N int `json:"n,omitempty"`
  39. Input any `json:"input,omitempty"`
  40. Instruction string `json:"instruction,omitempty"`
  41. Size string `json:"size,omitempty"`
  42. }
  43. type ChatRequest struct {
  44. Model string `json:"model"`
  45. Messages []Message `json:"messages"`
  46. MaxTokens int `json:"max_tokens"`
  47. }
  48. type TextRequest struct {
  49. Model string `json:"model"`
  50. Messages []Message `json:"messages"`
  51. Prompt string `json:"prompt"`
  52. MaxTokens int `json:"max_tokens"`
  53. //Stream bool `json:"stream"`
  54. }
  55. type ImageRequest struct {
  56. Prompt string `json:"prompt"`
  57. N int `json:"n"`
  58. Size string `json:"size"`
  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. Usage `json:"usage"`
  77. Error OpenAIError `json:"error"`
  78. }
  79. type OpenAITextResponseChoice struct {
  80. Index int `json:"index"`
  81. Message `json:"message"`
  82. FinishReason string `json:"finish_reason"`
  83. }
  84. type OpenAITextResponse struct {
  85. Id string `json:"id"`
  86. Object string `json:"object"`
  87. Created int64 `json:"created"`
  88. Choices []OpenAITextResponseChoice `json:"choices"`
  89. Usage `json:"usage"`
  90. }
  91. type ImageResponse struct {
  92. Created int `json:"created"`
  93. Data []struct {
  94. Url string `json:"url"`
  95. }
  96. }
  97. type ChatCompletionsStreamResponseChoice struct {
  98. Delta struct {
  99. Content string `json:"content"`
  100. } `json:"delta"`
  101. FinishReason string `json:"finish_reason,omitempty"`
  102. }
  103. type ChatCompletionsStreamResponse struct {
  104. Id string `json:"id"`
  105. Object string `json:"object"`
  106. Created int64 `json:"created"`
  107. Model string `json:"model"`
  108. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  109. }
  110. type CompletionsStreamResponse struct {
  111. Choices []struct {
  112. Text string `json:"text"`
  113. FinishReason string `json:"finish_reason"`
  114. } `json:"choices"`
  115. }
  116. type MidjourneyRequest struct {
  117. Prompt string `json:"prompt"`
  118. NotifyHook string `json:"notifyHook"`
  119. Action string `json:"action"`
  120. Index int `json:"index"`
  121. State string `json:"state"`
  122. TaskId string `json:"taskId"`
  123. Base64Array []string `json:"base64Array"`
  124. }
  125. type MidjourneyResponse struct {
  126. Code int `json:"code"`
  127. Description string `json:"description"`
  128. Properties interface{} `json:"properties"`
  129. Result string `json:"result"`
  130. }
  131. func Relay(c *gin.Context) {
  132. relayMode := RelayModeUnknown
  133. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  134. relayMode = RelayModeChatCompletions
  135. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  136. relayMode = RelayModeCompletions
  137. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  138. relayMode = RelayModeEmbeddings
  139. } else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  140. relayMode = RelayModeEmbeddings
  141. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  142. relayMode = RelayModeModerations
  143. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  144. relayMode = RelayModeImagesGenerations
  145. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
  146. relayMode = RelayModeEdits
  147. }
  148. var err *OpenAIErrorWithStatusCode
  149. switch relayMode {
  150. case RelayModeImagesGenerations:
  151. err = relayImageHelper(c, relayMode)
  152. default:
  153. err = relayTextHelper(c, relayMode)
  154. }
  155. if err != nil {
  156. retryTimesStr := c.Query("retry")
  157. retryTimes, _ := strconv.Atoi(retryTimesStr)
  158. if retryTimesStr == "" {
  159. retryTimes = common.RetryTimes
  160. }
  161. if retryTimes > 0 {
  162. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  163. } else {
  164. if err.StatusCode == http.StatusTooManyRequests {
  165. err.OpenAIError.Message = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  166. }
  167. c.JSON(err.StatusCode, gin.H{
  168. "error": err.OpenAIError,
  169. })
  170. }
  171. channelId := c.GetInt("channel_id")
  172. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  173. // https://platform.openai.com/docs/guides/error-codes/api-errors
  174. if shouldDisableChannel(&err.OpenAIError) {
  175. channelId := c.GetInt("channel_id")
  176. channelName := c.GetString("channel_name")
  177. disableChannel(channelId, channelName, err.Message)
  178. }
  179. }
  180. }
  181. func RelayMidjourney(c *gin.Context) {
  182. relayMode := RelayModeUnknown
  183. if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/imagine") {
  184. relayMode = RelayModeMidjourneyImagine
  185. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/notify") {
  186. relayMode = RelayModeMidjourneyNotify
  187. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/change") {
  188. relayMode = RelayModeMidjourneyChange
  189. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/task") {
  190. relayMode = RelayModeMidjourneyTaskFetch
  191. }
  192. var err *MidjourneyResponse
  193. switch relayMode {
  194. case RelayModeMidjourneyNotify:
  195. err = relayMidjourneyNotify(c)
  196. case RelayModeMidjourneyTaskFetch:
  197. err = relayMidjourneyTask(c, relayMode)
  198. default:
  199. err = relayMidjourneySubmit(c, relayMode)
  200. }
  201. //err = relayMidjourneySubmit(c, relayMode)
  202. log.Println(err)
  203. if err != nil {
  204. retryTimesStr := c.Query("retry")
  205. retryTimes, _ := strconv.Atoi(retryTimesStr)
  206. if retryTimesStr == "" {
  207. retryTimes = common.RetryTimes
  208. }
  209. if retryTimes > 0 {
  210. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  211. } else {
  212. if err.Code == 30 {
  213. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  214. }
  215. c.JSON(400, gin.H{
  216. "error": err.Result,
  217. })
  218. }
  219. channelId := c.GetInt("channel_id")
  220. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Result))
  221. //if shouldDisableChannel(&err.OpenAIError) {
  222. // channelId := c.GetInt("channel_id")
  223. // channelName := c.GetString("channel_name")
  224. // disableChannel(channelId, channelName, err.Result)
  225. //}
  226. }
  227. }
  228. func RelayNotImplemented(c *gin.Context) {
  229. err := OpenAIError{
  230. Message: "API not implemented",
  231. Type: "one_api_error",
  232. Param: "",
  233. Code: "api_not_implemented",
  234. }
  235. c.JSON(http.StatusNotImplemented, gin.H{
  236. "error": err,
  237. })
  238. }
  239. func RelayNotFound(c *gin.Context) {
  240. err := OpenAIError{
  241. Message: fmt.Sprintf("API not found: %s:%s", c.Request.Method, c.Request.URL.Path),
  242. Type: "one_api_error",
  243. Param: "",
  244. Code: "api_not_found",
  245. }
  246. c.JSON(http.StatusNotFound, gin.H{
  247. "error": err,
  248. })
  249. }