relay.go 9.1 KB

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