relay.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. B64Json string `json:"b64_json"`
  152. }
  153. }
  154. type ChatCompletionsStreamResponseChoice struct {
  155. Delta struct {
  156. Content string `json:"content"`
  157. } `json:"delta"`
  158. FinishReason *string `json:"finish_reason"`
  159. }
  160. type ChatCompletionsStreamResponse struct {
  161. Id string `json:"id"`
  162. Object string `json:"object"`
  163. Created int64 `json:"created"`
  164. Model string `json:"model"`
  165. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  166. }
  167. type ChatCompletionsStreamResponseSimple struct {
  168. Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
  169. }
  170. type CompletionsStreamResponse struct {
  171. Choices []struct {
  172. Text string `json:"text"`
  173. FinishReason string `json:"finish_reason"`
  174. } `json:"choices"`
  175. }
  176. type MidjourneyRequest struct {
  177. Prompt string `json:"prompt"`
  178. NotifyHook string `json:"notifyHook"`
  179. Action string `json:"action"`
  180. Index int `json:"index"`
  181. State string `json:"state"`
  182. TaskId string `json:"taskId"`
  183. Base64Array []string `json:"base64Array"`
  184. }
  185. type MidjourneyResponse struct {
  186. Code int `json:"code"`
  187. Description string `json:"description"`
  188. Properties interface{} `json:"properties"`
  189. Result string `json:"result"`
  190. }
  191. func Relay(c *gin.Context) {
  192. relayMode := RelayModeUnknown
  193. if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
  194. relayMode = RelayModeChatCompletions
  195. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
  196. relayMode = RelayModeCompletions
  197. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
  198. relayMode = RelayModeEmbeddings
  199. } else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
  200. relayMode = RelayModeEmbeddings
  201. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
  202. relayMode = RelayModeModerations
  203. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
  204. relayMode = RelayModeImagesGenerations
  205. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
  206. relayMode = RelayModeEdits
  207. } else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio") {
  208. relayMode = RelayModeAudio
  209. }
  210. var err *OpenAIErrorWithStatusCode
  211. switch relayMode {
  212. case RelayModeImagesGenerations:
  213. err = relayImageHelper(c, relayMode)
  214. case RelayModeAudio:
  215. err = relayAudioHelper(c, relayMode)
  216. default:
  217. err = relayTextHelper(c, relayMode)
  218. }
  219. if err != nil {
  220. requestId := c.GetString(common.RequestIdKey)
  221. retryTimesStr := c.Query("retry")
  222. retryTimes, _ := strconv.Atoi(retryTimesStr)
  223. if retryTimesStr == "" {
  224. retryTimes = common.RetryTimes
  225. }
  226. if retryTimes > 0 {
  227. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  228. } else {
  229. if err.StatusCode == http.StatusTooManyRequests {
  230. //err.OpenAIError.Message = "当前分组上游负载已饱和,请稍后再试"
  231. }
  232. err.OpenAIError.Message = common.MessageWithRequestId(err.OpenAIError.Message, requestId)
  233. c.JSON(err.StatusCode, gin.H{
  234. "error": err.OpenAIError,
  235. })
  236. }
  237. channelId := c.GetInt("channel_id")
  238. autoBan := c.GetBool("auto_ban")
  239. common.LogError(c.Request.Context(), fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
  240. // https://platform.openai.com/docs/guides/error-codes/api-errors
  241. if shouldDisableChannel(&err.OpenAIError, err.StatusCode) && autoBan {
  242. channelId := c.GetInt("channel_id")
  243. channelName := c.GetString("channel_name")
  244. disableChannel(channelId, channelName, err.Message)
  245. }
  246. }
  247. }
  248. func RelayMidjourney(c *gin.Context) {
  249. relayMode := RelayModeUnknown
  250. if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/imagine") {
  251. relayMode = RelayModeMidjourneyImagine
  252. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/blend") {
  253. relayMode = RelayModeMidjourneyBlend
  254. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/describe") {
  255. relayMode = RelayModeMidjourneyDescribe
  256. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/notify") {
  257. relayMode = RelayModeMidjourneyNotify
  258. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/submit/change") {
  259. relayMode = RelayModeMidjourneyChange
  260. } else if strings.HasPrefix(c.Request.URL.Path, "/mj/task") {
  261. relayMode = RelayModeMidjourneyTaskFetch
  262. }
  263. var err *MidjourneyResponse
  264. switch relayMode {
  265. case RelayModeMidjourneyNotify:
  266. err = relayMidjourneyNotify(c)
  267. case RelayModeMidjourneyTaskFetch:
  268. err = relayMidjourneyTask(c, relayMode)
  269. default:
  270. err = relayMidjourneySubmit(c, relayMode)
  271. }
  272. //err = relayMidjourneySubmit(c, relayMode)
  273. log.Println(err)
  274. if err != nil {
  275. retryTimesStr := c.Query("retry")
  276. retryTimes, _ := strconv.Atoi(retryTimesStr)
  277. if retryTimesStr == "" {
  278. retryTimes = common.RetryTimes
  279. }
  280. if retryTimes > 0 {
  281. c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
  282. } else {
  283. if err.Code == 30 {
  284. err.Result = "当前分组负载已饱和,请稍后再试,或升级账户以提升服务质量。"
  285. }
  286. c.JSON(400, gin.H{
  287. "error": err.Description + " " + err.Result,
  288. })
  289. }
  290. channelId := c.GetInt("channel_id")
  291. common.SysError(fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Result))
  292. //if shouldDisableChannel(&err.OpenAIError) {
  293. // channelId := c.GetInt("channel_id")
  294. // channelName := c.GetString("channel_name")
  295. // disableChannel(channelId, channelName, err.Result)
  296. //};''''''''''''''''''''''''''''''''
  297. }
  298. }
  299. func RelayNotImplemented(c *gin.Context) {
  300. err := OpenAIError{
  301. Message: "API not implemented",
  302. Type: "new_api_error",
  303. Param: "",
  304. Code: "api_not_implemented",
  305. }
  306. c.JSON(http.StatusNotImplemented, gin.H{
  307. "error": err,
  308. })
  309. }
  310. func RelayNotFound(c *gin.Context) {
  311. err := OpenAIError{
  312. Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
  313. Type: "invalid_request_error",
  314. Param: "",
  315. Code: "",
  316. }
  317. c.JSON(http.StatusNotFound, gin.H{
  318. "error": err,
  319. })
  320. }