relay.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. RelayModeMidjourneyDescribe
  26. RelayModeMidjourneyBlend
  27. RelayModeMidjourneyChange
  28. RelayModeMidjourneyNotify
  29. RelayModeMidjourneyTaskFetch
  30. RelayModeAudio
  31. )
  32. // https://platform.openai.com/docs/api-reference/chat
  33. type GeneralOpenAIRequest struct {
  34. Model string `json:"model,omitempty"`
  35. Messages []Message `json:"messages,omitempty"`
  36. Prompt any `json:"prompt,omitempty"`
  37. Stream bool `json:"stream,omitempty"`
  38. MaxTokens int `json:"max_tokens,omitempty"`
  39. Temperature float64 `json:"temperature,omitempty"`
  40. TopP float64 `json:"top_p,omitempty"`
  41. N int `json:"n,omitempty"`
  42. Input any `json:"input,omitempty"`
  43. Instruction string `json:"instruction,omitempty"`
  44. Size string `json:"size,omitempty"`
  45. Functions any `json:"functions,omitempty"`
  46. }
  47. func (r GeneralOpenAIRequest) ParseInput() []string {
  48. if r.Input == nil {
  49. return nil
  50. }
  51. var input []string
  52. switch r.Input.(type) {
  53. case string:
  54. input = []string{r.Input.(string)}
  55. case []any:
  56. input = make([]string, 0, len(r.Input.([]any)))
  57. for _, item := range r.Input.([]any) {
  58. if str, ok := item.(string); ok {
  59. input = append(input, str)
  60. }
  61. }
  62. }
  63. return input
  64. }
  65. type AudioRequest struct {
  66. Model string `json:"model"`
  67. Voice string `json:"voice"`
  68. Input string `json:"input"`
  69. }
  70. type ChatRequest struct {
  71. Model string `json:"model"`
  72. Messages []Message `json:"messages"`
  73. MaxTokens int `json:"max_tokens"`
  74. }
  75. type TextRequest struct {
  76. Model string `json:"model"`
  77. Messages []Message `json:"messages"`
  78. Prompt string `json:"prompt"`
  79. MaxTokens int `json:"max_tokens"`
  80. //Stream bool `json:"stream"`
  81. }
  82. type ImageRequest struct {
  83. Model string `json:"model"`
  84. Prompt string `json:"prompt"`
  85. N int `json:"n"`
  86. Size string `json:"size"`
  87. Quality string `json:"quality,omitempty"`
  88. ResponseFormat string `json:"response_format,omitempty"`
  89. Style string `json:"style,omitempty"`
  90. }
  91. type AudioResponse struct {
  92. Text string `json:"text,omitempty"`
  93. }
  94. type Usage struct {
  95. PromptTokens int `json:"prompt_tokens"`
  96. CompletionTokens int `json:"completion_tokens"`
  97. TotalTokens int `json:"total_tokens"`
  98. }
  99. type OpenAIError struct {
  100. Message string `json:"message"`
  101. Type string `json:"type"`
  102. Param string `json:"param"`
  103. Code any `json:"code"`
  104. }
  105. type OpenAIErrorWithStatusCode struct {
  106. OpenAIError
  107. StatusCode int `json:"status_code"`
  108. }
  109. type TextResponse struct {
  110. Choices []OpenAITextResponseChoice `json:"choices"`
  111. Usage `json:"usage"`
  112. Error OpenAIError `json:"error"`
  113. }
  114. type OpenAITextResponseChoice struct {
  115. Index int `json:"index"`
  116. Message `json:"message"`
  117. FinishReason string `json:"finish_reason"`
  118. }
  119. type OpenAITextResponse struct {
  120. Id string `json:"id"`
  121. Object string `json:"object"`
  122. Created int64 `json:"created"`
  123. Choices []OpenAITextResponseChoice `json:"choices"`
  124. Usage `json:"usage"`
  125. }
  126. type OpenAIEmbeddingResponseItem struct {
  127. Object string `json:"object"`
  128. Index int `json:"index"`
  129. Embedding []float64 `json:"embedding"`
  130. }
  131. type OpenAIEmbeddingResponse struct {
  132. Object string `json:"object"`
  133. Data []OpenAIEmbeddingResponseItem `json:"data"`
  134. Model string `json:"model"`
  135. Usage `json:"usage"`
  136. }
  137. type ImageResponse struct {
  138. Created int `json:"created"`
  139. Data []struct {
  140. Url string `json:"url"`
  141. }
  142. }
  143. type ChatCompletionsStreamResponseChoice struct {
  144. Delta struct {
  145. Content string `json:"content"`
  146. } `json:"delta"`
  147. FinishReason *string `json:"finish_reason"`
  148. }
  149. type ChatCompletionsStreamResponse struct {
  150. Id string `json:"id"`
  151. Object string `json:"object"`
  152. Created int64 `json:"created"`
  153. Model string `json:"model"`
  154. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  155. }
  156. type CompletionsStreamResponse struct {
  157. Choices []struct {
  158. Text string `json:"text"`
  159. FinishReason string `json:"finish_reason"`
  160. } `json:"choices"`
  161. }
  162. type MidjourneyRequest struct {
  163. Prompt string `json:"prompt"`
  164. NotifyHook string `json:"notifyHook"`
  165. Action string `json:"action"`
  166. Index int `json:"index"`
  167. State string `json:"state"`
  168. TaskId string `json:"taskId"`
  169. Base64Array []string `json:"base64Array"`
  170. }
  171. type MidjourneyResponse struct {
  172. Code int `json:"code"`
  173. Description string `json:"description"`
  174. Properties interface{} `json:"properties"`
  175. Result string `json:"result"`
  176. }
  177. func Relay(c *gin.Context) {
  178. relayMode := RelayModeUnknown
  179. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  180. relayMode = RelayModeChatCompletions
  181. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  182. relayMode = RelayModeCompletions
  183. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  184. relayMode = RelayModeEmbeddings
  185. } else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  186. relayMode = RelayModeEmbeddings
  187. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  188. relayMode = RelayModeModerations
  189. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  190. relayMode = RelayModeImagesGenerations
  191. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
  192. relayMode = RelayModeEdits
  193. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  194. relayMode = RelayModeAudio
  195. }
  196. var err *OpenAIErrorWithStatusCode
  197. switch relayMode {
  198. case RelayModeImagesGenerations:
  199. err = relayImageHelper(c, relayMode)
  200. case RelayModeAudio:
  201. err = relayAudioHelper(c, relayMode)
  202. default:
  203. err = relayTextHelper(c, relayMode)
  204. }
  205. if err != nil {
  206. requestId := c.GetString(common.RequestIdKey)
  207. retryTimesStr := c.Query("retry")
  208. retryTimes, _ := strconv.Atoi(retryTimesStr)
  209. if retryTimesStr == "" {
  210. retryTimes = common.RetryTimes
  211. }
  212. if retryTimes > 0 {
  213. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  214. } else {
  215. if err.StatusCode == http.StatusTooManyRequests {
  216. //err.OpenAIError.Message = "当前分组上游负载已饱和,请稍后再试"
  217. }
  218. err.OpenAIError.Message = common.MessageWithRequestId(err.OpenAIError.Message, requestId)
  219. c.JSON(err.StatusCode, gin.H{
  220. "error": err.OpenAIError,
  221. })
  222. }
  223. channelId := c.GetInt("channel_id")
  224. autoBan := c.GetBool("auto_ban")
  225. common.LogError(c.Request.Context(), fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  226. // https://platform.openai.com/docs/guides/error-codes/api-errors
  227. if shouldDisableChannel(&err.OpenAIError, err.StatusCode) && autoBan {
  228. channelId := c.GetInt("channel_id")
  229. channelName := c.GetString("channel_name")
  230. disableChannel(channelId, channelName, err.Message)
  231. }
  232. }
  233. }
  234. func RelayMidjourney(c *gin.Context) {
  235. relayMode := RelayModeUnknown
  236. if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/imagine") {
  237. relayMode = RelayModeMidjourneyImagine
  238. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/blend") {
  239. relayMode = RelayModeMidjourneyBlend
  240. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/describe") {
  241. relayMode = RelayModeMidjourneyDescribe
  242. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/notify") {
  243. relayMode = RelayModeMidjourneyNotify
  244. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/change") {
  245. relayMode = RelayModeMidjourneyChange
  246. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/task") {
  247. relayMode = RelayModeMidjourneyTaskFetch
  248. }
  249. var err *MidjourneyResponse
  250. switch relayMode {
  251. case RelayModeMidjourneyNotify:
  252. err = relayMidjourneyNotify(c)
  253. case RelayModeMidjourneyTaskFetch:
  254. err = relayMidjourneyTask(c, relayMode)
  255. default:
  256. err = relayMidjourneySubmit(c, relayMode)
  257. }
  258. //err = relayMidjourneySubmit(c, relayMode)
  259. log.Println(err)
  260. if err != nil {
  261. retryTimesStr := c.Query("retry")
  262. retryTimes, _ := strconv.Atoi(retryTimesStr)
  263. if retryTimesStr == "" {
  264. retryTimes = common.RetryTimes
  265. }
  266. if retryTimes > 0 {
  267. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  268. } else {
  269. if err.Code == 30 {
  270. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  271. }
  272. c.JSON(400, gin.H{
  273. "error": err.Result,
  274. })
  275. }
  276. channelId := c.GetInt("channel_id")
  277. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Result))
  278. //if shouldDisableChannel(&err.OpenAIError) {
  279. // channelId := c.GetInt("channel_id")
  280. // channelName := c.GetString("channel_name")
  281. // disableChannel(channelId, channelName, err.Result)
  282. //};''''''''''''''''''''''''''''''''
  283. }
  284. }
  285. func RelayNotImplemented(c *gin.Context) {
  286. err := OpenAIError{
  287. Message: "API not implemented",
  288. Type: "one_api_error",
  289. Param: "",
  290. Code: "api_not_implemented",
  291. }
  292. c.JSON(http.StatusNotImplemented, gin.H{
  293. "error": err,
  294. })
  295. }
  296. func RelayNotFound(c *gin.Context) {
  297. err := OpenAIError{
  298. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  299. Type: "invalid_request_error",
  300. Param: "",
  301. Code: "",
  302. }
  303. c.JSON(http.StatusNotFound, gin.H{
  304. "error": err,
  305. })
  306. }