relay.go 10 KB

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