adaptor.go 15 KB

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