relay.go 11 KB

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