relay.go 10.0 KB

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