adaptor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net/http"
  10. "one-api/common"
  11. constant2 "one-api/constant"
  12. "one-api/dto"
  13. "one-api/relay/channel"
  14. "one-api/relay/channel/ai360"
  15. "one-api/relay/channel/lingyiwanwu"
  16. "one-api/relay/channel/minimax"
  17. "one-api/relay/channel/moonshot"
  18. "one-api/relay/channel/openrouter"
  19. "one-api/relay/channel/xinference"
  20. relaycommon "one-api/relay/common"
  21. "one-api/relay/common_handler"
  22. "one-api/relay/constant"
  23. "one-api/service"
  24. "path/filepath"
  25. "strings"
  26. "github.com/gin-gonic/gin"
  27. "net/textproto"
  28. )
  29. type Adaptor struct {
  30. ChannelType int
  31. ResponseFormat string
  32. }
  33. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.ClaudeRequest) (any, error) {
  34. if !strings.Contains(request.Model, "claude") {
  35. return nil, fmt.Errorf("you are using openai channel type with path /v1/messages, only claude model supported convert, but got %s", request.Model)
  36. }
  37. aiRequest, err := service.ClaudeToOpenAIRequest(*request, info)
  38. if err != nil {
  39. return nil, err
  40. }
  41. if info.SupportStreamOptions {
  42. aiRequest.StreamOptions = &dto.StreamOptions{
  43. IncludeUsage: true,
  44. }
  45. }
  46. return a.ConvertOpenAIRequest(c, info, aiRequest)
  47. }
  48. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  49. a.ChannelType = info.ChannelType
  50. // initialize ThinkingContentInfo when thinking_to_content is enabled
  51. if think2Content, ok := info.ChannelSetting[constant2.ChannelSettingThinkingToContent].(bool); ok && think2Content {
  52. info.ThinkingContentInfo = relaycommon.ThinkingContentInfo{
  53. IsFirstThinkingContent: true,
  54. SendLastThinkingContent: false,
  55. HasSentThinkingContent: false,
  56. }
  57. }
  58. }
  59. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  60. if info.RelayFormat == relaycommon.RelayFormatClaude {
  61. return fmt.Sprintf("%s/v1/chat/completions", info.BaseUrl), nil
  62. }
  63. if info.RelayMode == constant.RelayModeRealtime {
  64. if strings.HasPrefix(info.BaseUrl, "https://") {
  65. baseUrl := strings.TrimPrefix(info.BaseUrl, "https://")
  66. baseUrl = "wss://" + baseUrl
  67. info.BaseUrl = baseUrl
  68. } else if strings.HasPrefix(info.BaseUrl, "http://") {
  69. baseUrl := strings.TrimPrefix(info.BaseUrl, "http://")
  70. baseUrl = "ws://" + baseUrl
  71. info.BaseUrl = baseUrl
  72. }
  73. }
  74. switch info.ChannelType {
  75. case common.ChannelTypeAzure:
  76. apiVersion := info.ApiVersion
  77. if apiVersion == "" {
  78. apiVersion = constant2.AzureDefaultAPIVersion
  79. }
  80. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  81. requestURL := strings.Split(info.RequestURLPath, "?")[0]
  82. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
  83. task := strings.TrimPrefix(requestURL, "/v1/")
  84. model_ := info.UpstreamModelName
  85. model_ = strings.Replace(model_, ".", "", -1)
  86. // https://github.com/songquanpeng/one-api/issues/67
  87. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  88. if info.RelayMode == constant.RelayModeRealtime {
  89. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, apiVersion)
  90. }
  91. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  92. case common.ChannelTypeMiniMax:
  93. return minimax.GetRequestURL(info)
  94. case common.ChannelTypeCustom:
  95. url := info.BaseUrl
  96. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  97. return url, nil
  98. default:
  99. return relaycommon.GetFullRequestURL(info.BaseUrl, info.RequestURLPath, info.ChannelType), nil
  100. }
  101. }
  102. func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *relaycommon.RelayInfo) error {
  103. channel.SetupApiRequestHeader(info, c, header)
  104. if info.ChannelType == common.ChannelTypeAzure {
  105. header.Set("api-key", info.ApiKey)
  106. return nil
  107. }
  108. if info.ChannelType == common.ChannelTypeOpenAI && "" != info.Organization {
  109. header.Set("OpenAI-Organization", info.Organization)
  110. }
  111. if info.RelayMode == constant.RelayModeRealtime {
  112. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  113. if swp != "" {
  114. items := []string{
  115. "realtime",
  116. "openai-insecure-api-key." + info.ApiKey,
  117. "openai-beta.realtime-v1",
  118. }
  119. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  120. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  121. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  122. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  123. } else {
  124. header.Set("openai-beta", "realtime=v1")
  125. header.Set("Authorization", "Bearer "+info.ApiKey)
  126. }
  127. } else {
  128. header.Set("Authorization", "Bearer "+info.ApiKey)
  129. }
  130. if info.ChannelType == common.ChannelTypeOpenRouter {
  131. header.Set("HTTP-Referer", "https://github.com/Calcium-Ion/new-api")
  132. header.Set("X-Title", "New API")
  133. }
  134. return nil
  135. }
  136. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  137. if request == nil {
  138. return nil, errors.New("request is nil")
  139. }
  140. if info.ChannelType != common.ChannelTypeOpenAI && info.ChannelType != common.ChannelTypeAzure {
  141. request.StreamOptions = nil
  142. }
  143. if strings.HasPrefix(request.Model, "o") {
  144. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  145. request.MaxCompletionTokens = request.MaxTokens
  146. request.MaxTokens = 0
  147. }
  148. request.Temperature = nil
  149. if strings.HasSuffix(request.Model, "-high") {
  150. request.ReasoningEffort = "high"
  151. request.Model = strings.TrimSuffix(request.Model, "-high")
  152. } else if strings.HasSuffix(request.Model, "-low") {
  153. request.ReasoningEffort = "low"
  154. request.Model = strings.TrimSuffix(request.Model, "-low")
  155. } else if strings.HasSuffix(request.Model, "-medium") {
  156. request.ReasoningEffort = "medium"
  157. request.Model = strings.TrimSuffix(request.Model, "-medium")
  158. }
  159. info.ReasoningEffort = request.ReasoningEffort
  160. info.UpstreamModelName = request.Model
  161. // o系列模型developer适配(o1-mini除外)
  162. if !strings.HasPrefix(request.Model, "o1-mini") {
  163. //修改第一个Message的内容,将system改为developer
  164. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  165. request.Messages[0].Role = "developer"
  166. }
  167. }
  168. }
  169. return request, nil
  170. }
  171. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  172. return request, nil
  173. }
  174. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  175. return request, nil
  176. }
  177. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  178. a.ResponseFormat = request.ResponseFormat
  179. if info.RelayMode == constant.RelayModeAudioSpeech {
  180. jsonData, err := json.Marshal(request)
  181. if err != nil {
  182. return nil, fmt.Errorf("error marshalling object: %w", err)
  183. }
  184. return bytes.NewReader(jsonData), nil
  185. } else {
  186. var requestBody bytes.Buffer
  187. writer := multipart.NewWriter(&requestBody)
  188. writer.WriteField("model", request.Model)
  189. // 获取所有表单字段
  190. formData := c.Request.PostForm
  191. // 遍历表单字段并打印输出
  192. for key, values := range formData {
  193. if key == "model" {
  194. continue
  195. }
  196. for _, value := range values {
  197. writer.WriteField(key, value)
  198. }
  199. }
  200. // 添加文件字段
  201. file, header, err := c.Request.FormFile("file")
  202. if err != nil {
  203. return nil, errors.New("file is required")
  204. }
  205. defer file.Close()
  206. part, err := writer.CreateFormFile("file", header.Filename)
  207. if err != nil {
  208. return nil, errors.New("create form file failed")
  209. }
  210. if _, err := io.Copy(part, file); err != nil {
  211. return nil, errors.New("copy file failed")
  212. }
  213. // 关闭 multipart 编写器以设置分界线
  214. writer.Close()
  215. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  216. return &requestBody, nil
  217. }
  218. }
  219. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  220. switch info.RelayMode {
  221. case constant.RelayModeImagesEdits:
  222. var requestBody bytes.Buffer
  223. writer := multipart.NewWriter(&requestBody)
  224. writer.WriteField("model", request.Model)
  225. // 获取所有表单字段
  226. formData := c.Request.PostForm
  227. // 遍历表单字段并打印输出
  228. for key, values := range formData {
  229. if key == "model" {
  230. continue
  231. }
  232. for _, value := range values {
  233. writer.WriteField(key, value)
  234. }
  235. }
  236. // Parse the multipart form to handle both single image and multiple images
  237. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  238. return nil, errors.New("failed to parse multipart form")
  239. }
  240. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  241. // Check if "image" field exists in any form, including array notation
  242. var imageFiles []*multipart.FileHeader
  243. var exists bool
  244. // First check for standard "image" field
  245. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  246. // If not found, check for "image[]" field
  247. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  248. // If still not found, iterate through all fields to find any that start with "image["
  249. foundArrayImages := false
  250. for fieldName, files := range c.Request.MultipartForm.File {
  251. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  252. foundArrayImages = true
  253. for _, file := range files {
  254. imageFiles = append(imageFiles, file)
  255. }
  256. }
  257. }
  258. // If no image fields found at all
  259. if !foundArrayImages && (len(imageFiles) == 0) {
  260. return nil, errors.New("image is required")
  261. }
  262. }
  263. }
  264. // Process all image files
  265. for i, fileHeader := range imageFiles {
  266. file, err := fileHeader.Open()
  267. if err != nil {
  268. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  269. }
  270. defer file.Close()
  271. // If multiple images, use image[] as the field name
  272. fieldName := "image"
  273. if len(imageFiles) > 1 {
  274. fieldName = "image[]"
  275. }
  276. // Determine MIME type based on file extension
  277. mimeType := detectImageMimeType(fileHeader.Filename)
  278. // Create a form file with the appropriate content type
  279. h := make(textproto.MIMEHeader)
  280. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  281. h.Set("Content-Type", mimeType)
  282. part, err := writer.CreatePart(h)
  283. if err != nil {
  284. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  285. }
  286. if _, err := io.Copy(part, file); err != nil {
  287. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  288. }
  289. }
  290. // Handle mask file if present
  291. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  292. maskFile, err := maskFiles[0].Open()
  293. if err != nil {
  294. return nil, errors.New("failed to open mask file")
  295. }
  296. defer maskFile.Close()
  297. // Determine MIME type for mask file
  298. mimeType := detectImageMimeType(maskFiles[0].Filename)
  299. // Create a form file with the appropriate content type
  300. h := make(textproto.MIMEHeader)
  301. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  302. h.Set("Content-Type", mimeType)
  303. maskPart, err := writer.CreatePart(h)
  304. if err != nil {
  305. return nil, errors.New("create form file failed for mask")
  306. }
  307. if _, err := io.Copy(maskPart, maskFile); err != nil {
  308. return nil, errors.New("copy mask file failed")
  309. }
  310. }
  311. } else {
  312. return nil, errors.New("no multipart form data found")
  313. }
  314. // 关闭 multipart 编写器以设置分界线
  315. writer.Close()
  316. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  317. return bytes.NewReader(requestBody.Bytes()), nil
  318. default:
  319. return request, nil
  320. }
  321. }
  322. // detectImageMimeType determines the MIME type based on the file extension
  323. func detectImageMimeType(filename string) string {
  324. ext := strings.ToLower(filepath.Ext(filename))
  325. switch ext {
  326. case ".jpg", ".jpeg":
  327. return "image/jpeg"
  328. case ".png":
  329. return "image/png"
  330. case ".webp":
  331. return "image/webp"
  332. default:
  333. // Try to detect from extension if possible
  334. if strings.HasPrefix(ext, ".jp") {
  335. return "image/jpeg"
  336. }
  337. // Default to png as a fallback
  338. return "image/png"
  339. }
  340. }
  341. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  342. if info.RelayMode == constant.RelayModeAudioTranscription ||
  343. info.RelayMode == constant.RelayModeAudioTranslation ||
  344. info.RelayMode == constant.RelayModeImagesEdits {
  345. return channel.DoFormRequest(a, c, info, requestBody)
  346. } else if info.RelayMode == constant.RelayModeRealtime {
  347. return channel.DoWssRequest(a, c, info, requestBody)
  348. } else {
  349. return channel.DoApiRequest(a, c, info, requestBody)
  350. }
  351. }
  352. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  353. switch info.RelayMode {
  354. case constant.RelayModeRealtime:
  355. err, usage = OpenaiRealtimeHandler(c, info)
  356. case constant.RelayModeAudioSpeech:
  357. err, usage = OpenaiTTSHandler(c, resp, info)
  358. case constant.RelayModeAudioTranslation:
  359. fallthrough
  360. case constant.RelayModeAudioTranscription:
  361. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  362. case constant.RelayModeImagesGenerations, constant.RelayModeImagesEdits:
  363. err, usage = OpenaiHandlerWithUsage(c, resp, info)
  364. case constant.RelayModeRerank:
  365. err, usage = common_handler.RerankHandler(c, info, resp)
  366. default:
  367. if info.IsStream {
  368. err, usage = OaiStreamHandler(c, resp, info)
  369. } else {
  370. err, usage = OpenaiHandler(c, resp, info)
  371. }
  372. }
  373. return
  374. }
  375. func (a *Adaptor) GetModelList() []string {
  376. switch a.ChannelType {
  377. case common.ChannelType360:
  378. return ai360.ModelList
  379. case common.ChannelTypeMoonshot:
  380. return moonshot.ModelList
  381. case common.ChannelTypeLingYiWanWu:
  382. return lingyiwanwu.ModelList
  383. case common.ChannelTypeMiniMax:
  384. return minimax.ModelList
  385. case common.ChannelTypeXinference:
  386. return xinference.ModelList
  387. case common.ChannelTypeOpenRouter:
  388. return openrouter.ModelList
  389. default:
  390. return ModelList
  391. }
  392. }
  393. func (a *Adaptor) GetChannelName() string {
  394. switch a.ChannelType {
  395. case common.ChannelType360:
  396. return ai360.ChannelName
  397. case common.ChannelTypeMoonshot:
  398. return moonshot.ChannelName
  399. case common.ChannelTypeLingYiWanWu:
  400. return lingyiwanwu.ChannelName
  401. case common.ChannelTypeMiniMax:
  402. return minimax.ChannelName
  403. case common.ChannelTypeXinference:
  404. return xinference.ChannelName
  405. case common.ChannelTypeOpenRouter:
  406. return openrouter.ChannelName
  407. default:
  408. return ChannelName
  409. }
  410. }