relay.go 9.2 KB

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