relay.go 9.3 KB

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