adaptor.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net/http"
  10. "net/textproto"
  11. "path/filepath"
  12. "strings"
  13. "github.com/QuantumNous/new-api/common"
  14. "github.com/QuantumNous/new-api/constant"
  15. "github.com/QuantumNous/new-api/dto"
  16. "github.com/QuantumNous/new-api/logger"
  17. "github.com/QuantumNous/new-api/relay/channel"
  18. "github.com/QuantumNous/new-api/relay/channel/ai360"
  19. "github.com/QuantumNous/new-api/relay/channel/lingyiwanwu"
  20. //"github.com/QuantumNous/new-api/relay/channel/minimax"
  21. "github.com/QuantumNous/new-api/relay/channel/openrouter"
  22. "github.com/QuantumNous/new-api/relay/channel/xinference"
  23. relaycommon "github.com/QuantumNous/new-api/relay/common"
  24. "github.com/QuantumNous/new-api/relay/common_handler"
  25. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  26. "github.com/QuantumNous/new-api/service"
  27. "github.com/QuantumNous/new-api/setting/model_setting"
  28. "github.com/QuantumNous/new-api/setting/reasoning"
  29. "github.com/QuantumNous/new-api/types"
  30. "github.com/samber/lo"
  31. "github.com/gin-gonic/gin"
  32. )
  33. type Adaptor struct {
  34. ChannelType int
  35. ResponseFormat string
  36. }
  37. func (a *Adaptor) ConvertGeminiRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeminiChatRequest) (any, error) {
  38. // 使用 service.GeminiToOpenAIRequest 转换请求格式
  39. openaiRequest, err := service.GeminiToOpenAIRequest(request, info)
  40. if err != nil {
  41. return nil, err
  42. }
  43. return a.ConvertOpenAIRequest(c, info, openaiRequest)
  44. }
  45. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.ClaudeRequest) (any, error) {
  46. //if !strings.Contains(request.Model, "claude") {
  47. // return nil, fmt.Errorf("you are using openai channel type with path /v1/messages, only claude model supported convert, but got %s", request.Model)
  48. //}
  49. //if common.DebugEnabled {
  50. // bodyBytes := []byte(common.GetJsonString(request))
  51. // err := os.WriteFile(fmt.Sprintf("claude_request_%s.txt", c.GetString(common.RequestIdKey)), bodyBytes, 0644)
  52. // if err != nil {
  53. // println(fmt.Sprintf("failed to save request body to file: %v", err))
  54. // }
  55. //}
  56. aiRequest, err := service.ClaudeToOpenAIRequest(*request, info)
  57. if err != nil {
  58. return nil, err
  59. }
  60. //if common.DebugEnabled {
  61. // println(fmt.Sprintf("convert claude to openai request result: %s", common.GetJsonString(aiRequest)))
  62. // // Save request body to file for debugging
  63. // bodyBytes := []byte(common.GetJsonString(aiRequest))
  64. // err = os.WriteFile(fmt.Sprintf("claude_to_openai_request_%s.txt", c.GetString(common.RequestIdKey)), bodyBytes, 0644)
  65. // if err != nil {
  66. // println(fmt.Sprintf("failed to save request body to file: %v", err))
  67. // }
  68. //}
  69. if info.SupportStreamOptions && info.IsStream {
  70. aiRequest.StreamOptions = &dto.StreamOptions{
  71. IncludeUsage: true,
  72. }
  73. }
  74. return a.ConvertOpenAIRequest(c, info, aiRequest)
  75. }
  76. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  77. a.ChannelType = info.ChannelType
  78. // initialize ThinkingContentInfo when thinking_to_content is enabled
  79. if info.ChannelSetting.ThinkingToContent {
  80. info.ThinkingContentInfo = relaycommon.ThinkingContentInfo{
  81. IsFirstThinkingContent: true,
  82. SendLastThinkingContent: false,
  83. HasSentThinkingContent: false,
  84. }
  85. }
  86. }
  87. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  88. if info.RelayMode == relayconstant.RelayModeRealtime {
  89. if strings.HasPrefix(info.ChannelBaseUrl, "https://") {
  90. baseUrl := strings.TrimPrefix(info.ChannelBaseUrl, "https://")
  91. baseUrl = "wss://" + baseUrl
  92. info.ChannelBaseUrl = baseUrl
  93. } else if strings.HasPrefix(info.ChannelBaseUrl, "http://") {
  94. baseUrl := strings.TrimPrefix(info.ChannelBaseUrl, "http://")
  95. baseUrl = "ws://" + baseUrl
  96. info.ChannelBaseUrl = baseUrl
  97. }
  98. }
  99. switch info.ChannelType {
  100. case constant.ChannelTypeAzure:
  101. apiVersion := info.ApiVersion
  102. if apiVersion == "" {
  103. apiVersion = constant.AzureDefaultAPIVersion
  104. }
  105. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  106. requestURL := strings.Split(info.RequestURLPath, "?")[0]
  107. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
  108. task := strings.TrimPrefix(requestURL, "/v1/")
  109. if info.RelayFormat == types.RelayFormatClaude {
  110. task = strings.TrimPrefix(task, "messages")
  111. task = "chat/completions" + task
  112. }
  113. // 特殊处理 responses API(包含 compact)
  114. if info.RelayMode == relayconstant.RelayModeResponses || info.RelayMode == relayconstant.RelayModeResponsesCompact {
  115. responsesApiVersion := "preview"
  116. subUrl := "/openai/v1/responses"
  117. if strings.Contains(info.ChannelBaseUrl, "cognitiveservices.azure.com") {
  118. subUrl = "/openai/responses"
  119. responsesApiVersion = apiVersion
  120. }
  121. if info.ChannelOtherSettings.AzureResponsesVersion != "" {
  122. responsesApiVersion = info.ChannelOtherSettings.AzureResponsesVersion
  123. }
  124. // compact 模式追加 /compact
  125. if info.RelayMode == relayconstant.RelayModeResponsesCompact {
  126. subUrl = subUrl + "/compact"
  127. }
  128. requestURL = fmt.Sprintf("%s?api-version=%s", subUrl, responsesApiVersion)
  129. return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, requestURL, info.ChannelType), nil
  130. }
  131. model_ := info.UpstreamModelName
  132. // 2025年5月10日后创建的渠道不移除.
  133. if info.ChannelCreateTime < constant.AzureNoRemoveDotTime {
  134. model_ = strings.Replace(model_, ".", "", -1)
  135. }
  136. // https://github.com/songquanpeng/one-api/issues/67
  137. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  138. if info.RelayMode == relayconstant.RelayModeRealtime {
  139. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, apiVersion)
  140. }
  141. return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, requestURL, info.ChannelType), nil
  142. //case constant.ChannelTypeMiniMax:
  143. // return minimax.GetRequestURL(info)
  144. case constant.ChannelTypeCustom:
  145. url := info.ChannelBaseUrl
  146. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  147. return url, nil
  148. default:
  149. if (info.RelayFormat == types.RelayFormatClaude || info.RelayFormat == types.RelayFormatGemini) &&
  150. info.RelayMode != relayconstant.RelayModeResponses &&
  151. info.RelayMode != relayconstant.RelayModeResponsesCompact {
  152. return fmt.Sprintf("%s/v1/chat/completions", info.ChannelBaseUrl), nil
  153. }
  154. return relaycommon.GetFullRequestURL(info.ChannelBaseUrl, info.RequestURLPath, info.ChannelType), nil
  155. }
  156. }
  157. func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *relaycommon.RelayInfo) error {
  158. channel.SetupApiRequestHeader(info, c, header)
  159. if info.ChannelType == constant.ChannelTypeAzure {
  160. header.Set("api-key", info.ApiKey)
  161. return nil
  162. }
  163. if info.ChannelType == constant.ChannelTypeOpenAI && "" != info.Organization {
  164. header.Set("OpenAI-Organization", info.Organization)
  165. }
  166. // 检查 Header Override 是否已设置 Authorization,如果已设置则跳过默认设置
  167. // 这样可以避免在 Header Override 应用时被覆盖(虽然 Header Override 会在之后应用,但这里作为额外保护)
  168. hasAuthOverride := false
  169. if len(info.HeadersOverride) > 0 {
  170. for k := range info.HeadersOverride {
  171. if strings.EqualFold(k, "Authorization") {
  172. hasAuthOverride = true
  173. break
  174. }
  175. }
  176. }
  177. if info.RelayMode == relayconstant.RelayModeRealtime {
  178. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  179. if swp != "" {
  180. items := []string{
  181. "realtime",
  182. "openai-insecure-api-key." + info.ApiKey,
  183. "openai-beta.realtime-v1",
  184. }
  185. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  186. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  187. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  188. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  189. } else {
  190. header.Set("openai-beta", "realtime=v1")
  191. if !hasAuthOverride {
  192. header.Set("Authorization", "Bearer "+info.ApiKey)
  193. }
  194. }
  195. } else {
  196. if !hasAuthOverride {
  197. header.Set("Authorization", "Bearer "+info.ApiKey)
  198. }
  199. }
  200. if info.ChannelType == constant.ChannelTypeOpenRouter {
  201. if header.Get("HTTP-Referer") == "" {
  202. header.Set("HTTP-Referer", "https://www.newapi.ai")
  203. }
  204. if header.Get("X-OpenRouter-Title") == "" {
  205. header.Set("X-OpenRouter-Title", "New API")
  206. }
  207. }
  208. return nil
  209. }
  210. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  211. if request == nil {
  212. return nil, errors.New("request is nil")
  213. }
  214. if info.ChannelType != constant.ChannelTypeOpenAI && info.ChannelType != constant.ChannelTypeAzure {
  215. request.StreamOptions = nil
  216. }
  217. if info.ChannelType == constant.ChannelTypeOpenRouter {
  218. if len(request.Usage) == 0 {
  219. request.Usage = json.RawMessage(`{"include":true}`)
  220. }
  221. // 适配 OpenRouter 的 thinking 后缀
  222. if !model_setting.ShouldPreserveThinkingSuffix(info.OriginModelName) &&
  223. strings.HasSuffix(info.UpstreamModelName, "-thinking") {
  224. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  225. request.Model = info.UpstreamModelName
  226. if len(request.Reasoning) == 0 {
  227. reasoning := map[string]any{
  228. "enabled": true,
  229. }
  230. if request.ReasoningEffort != "" && request.ReasoningEffort != "none" {
  231. reasoning["effort"] = request.ReasoningEffort
  232. }
  233. marshal, err := common.Marshal(reasoning)
  234. if err != nil {
  235. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  236. }
  237. request.Reasoning = marshal
  238. }
  239. // 清空多余的ReasoningEffort
  240. request.ReasoningEffort = ""
  241. } else {
  242. if len(request.Reasoning) == 0 {
  243. // 适配 OpenAI 的 ReasoningEffort 格式
  244. if request.ReasoningEffort != "" {
  245. reasoning := map[string]any{
  246. "enabled": true,
  247. }
  248. if request.ReasoningEffort != "none" {
  249. reasoning["effort"] = request.ReasoningEffort
  250. marshal, err := common.Marshal(reasoning)
  251. if err != nil {
  252. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  253. }
  254. request.Reasoning = marshal
  255. }
  256. }
  257. }
  258. request.ReasoningEffort = ""
  259. }
  260. // https://docs.anthropic.com/en/api/openai-sdk#extended-thinking-support
  261. // 没有做排除3.5Haiku等,要出问题再加吧,最佳兼容性(不是
  262. if request.THINKING != nil && strings.HasPrefix(info.UpstreamModelName, "anthropic") {
  263. var thinking dto.Thinking // Claude标准Thinking格式
  264. if err := json.Unmarshal(request.THINKING, &thinking); err != nil {
  265. return nil, fmt.Errorf("error Unmarshal thinking: %w", err)
  266. }
  267. // 只有当 thinking.Type 是 "enabled" 时才处理
  268. if thinking.Type == "enabled" {
  269. // 检查 BudgetTokens 是否为 nil
  270. if thinking.BudgetTokens == nil {
  271. return nil, fmt.Errorf("BudgetTokens is nil when thinking is enabled")
  272. }
  273. reasoning := openrouter.RequestReasoning{
  274. Enabled: true,
  275. MaxTokens: *thinking.BudgetTokens,
  276. }
  277. marshal, err := common.Marshal(reasoning)
  278. if err != nil {
  279. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  280. }
  281. request.Reasoning = marshal
  282. }
  283. // 清空 THINKING
  284. request.THINKING = nil
  285. }
  286. }
  287. if strings.HasPrefix(info.UpstreamModelName, "o") || strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
  288. if lo.FromPtrOr(request.MaxCompletionTokens, uint(0)) == 0 && lo.FromPtrOr(request.MaxTokens, uint(0)) != 0 {
  289. request.MaxCompletionTokens = request.MaxTokens
  290. request.MaxTokens = nil
  291. }
  292. if strings.HasPrefix(info.UpstreamModelName, "o") {
  293. request.Temperature = nil
  294. }
  295. // gpt-5系列模型适配 归零不再支持的参数
  296. if strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
  297. request.Temperature = nil
  298. request.TopP = nil
  299. request.LogProbs = nil
  300. }
  301. // 转换模型推理力度后缀
  302. effort, originModel := reasoning.ParseOpenAIReasoningEffortFromModelSuffix(info.UpstreamModelName)
  303. if effort != "" {
  304. request.ReasoningEffort = effort
  305. info.UpstreamModelName = originModel
  306. request.Model = originModel
  307. }
  308. info.ReasoningEffort = request.ReasoningEffort
  309. // o系列模型developer适配(o1-mini除外)
  310. if !strings.HasPrefix(info.UpstreamModelName, "o1-mini") && !strings.HasPrefix(info.UpstreamModelName, "o1-preview") {
  311. //修改第一个Message的内容,将system改为developer
  312. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  313. request.Messages[0].Role = "developer"
  314. }
  315. }
  316. }
  317. return request, nil
  318. }
  319. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  320. return request, nil
  321. }
  322. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  323. return request, nil
  324. }
  325. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  326. a.ResponseFormat = request.ResponseFormat
  327. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  328. jsonData, err := common.Marshal(request)
  329. if err != nil {
  330. return nil, fmt.Errorf("error marshalling object: %w", err)
  331. }
  332. return bytes.NewReader(jsonData), nil
  333. } else {
  334. var requestBody bytes.Buffer
  335. writer := multipart.NewWriter(&requestBody)
  336. writer.WriteField("model", request.Model)
  337. formData, err2 := common.ParseMultipartFormReusable(c)
  338. if err2 != nil {
  339. return nil, fmt.Errorf("error parsing multipart form: %w", err2)
  340. }
  341. // 打印类似 curl 命令格式的信息
  342. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'model=\"%s\"'", request.Model))
  343. // 遍历表单字段并打印输出
  344. for key, values := range formData.Value {
  345. if key == "model" {
  346. continue
  347. }
  348. for _, value := range values {
  349. writer.WriteField(key, value)
  350. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form '%s=\"%s\"'", key, value))
  351. }
  352. }
  353. // 从 formData 中获取文件
  354. fileHeaders := formData.File["file"]
  355. if len(fileHeaders) == 0 {
  356. return nil, errors.New("file is required")
  357. }
  358. // 使用 formData 中的第一个文件
  359. fileHeader := fileHeaders[0]
  360. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'file=@\"%s\"' (size: %d bytes, content-type: %s)",
  361. fileHeader.Filename, fileHeader.Size, fileHeader.Header.Get("Content-Type")))
  362. file, err := fileHeader.Open()
  363. if err != nil {
  364. return nil, fmt.Errorf("error opening audio file: %v", err)
  365. }
  366. defer file.Close()
  367. part, err := writer.CreateFormFile("file", fileHeader.Filename)
  368. if err != nil {
  369. return nil, errors.New("create form file failed")
  370. }
  371. if _, err := io.Copy(part, file); err != nil {
  372. return nil, errors.New("copy file failed")
  373. }
  374. // 关闭 multipart 编写器以设置分界线
  375. writer.Close()
  376. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  377. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--header 'Content-Type: %s'", writer.FormDataContentType()))
  378. return &requestBody, nil
  379. }
  380. }
  381. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  382. switch info.RelayMode {
  383. case relayconstant.RelayModeImagesEdits:
  384. var requestBody bytes.Buffer
  385. writer := multipart.NewWriter(&requestBody)
  386. writer.WriteField("model", request.Model)
  387. // 使用已解析的 multipart 表单,避免重复解析
  388. mf := c.Request.MultipartForm
  389. if mf == nil {
  390. if _, err := c.MultipartForm(); err != nil {
  391. return nil, errors.New("failed to parse multipart form")
  392. }
  393. mf = c.Request.MultipartForm
  394. }
  395. // 写入所有非文件字段
  396. if mf != nil {
  397. for key, values := range mf.Value {
  398. if key == "model" {
  399. continue
  400. }
  401. for _, value := range values {
  402. writer.WriteField(key, value)
  403. }
  404. }
  405. }
  406. if mf != nil && mf.File != nil {
  407. // Check if "image" field exists in any form, including array notation
  408. var imageFiles []*multipart.FileHeader
  409. var exists bool
  410. // First check for standard "image" field
  411. if imageFiles, exists = mf.File["image"]; !exists || len(imageFiles) == 0 {
  412. // If not found, check for "image[]" field
  413. if imageFiles, exists = mf.File["image[]"]; !exists || len(imageFiles) == 0 {
  414. // If still not found, iterate through all fields to find any that start with "image["
  415. foundArrayImages := false
  416. for fieldName, files := range mf.File {
  417. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  418. foundArrayImages = true
  419. imageFiles = append(imageFiles, files...)
  420. }
  421. }
  422. // If no image fields found at all
  423. if !foundArrayImages && (len(imageFiles) == 0) {
  424. return nil, errors.New("image is required")
  425. }
  426. }
  427. }
  428. // Process all image files
  429. for i, fileHeader := range imageFiles {
  430. file, err := fileHeader.Open()
  431. if err != nil {
  432. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  433. }
  434. // If multiple images, use image[] as the field name
  435. fieldName := "image"
  436. if len(imageFiles) > 1 {
  437. fieldName = "image[]"
  438. }
  439. // Determine MIME type based on file extension
  440. mimeType := detectImageMimeType(fileHeader.Filename)
  441. // Create a form file with the appropriate content type
  442. h := make(textproto.MIMEHeader)
  443. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  444. h.Set("Content-Type", mimeType)
  445. part, err := writer.CreatePart(h)
  446. if err != nil {
  447. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  448. }
  449. if _, err := io.Copy(part, file); err != nil {
  450. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  451. }
  452. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  453. _ = file.Close()
  454. }
  455. // Handle mask file if present
  456. if maskFiles, exists := mf.File["mask"]; exists && len(maskFiles) > 0 {
  457. maskFile, err := maskFiles[0].Open()
  458. if err != nil {
  459. return nil, errors.New("failed to open mask file")
  460. }
  461. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  462. // Determine MIME type for mask file
  463. mimeType := detectImageMimeType(maskFiles[0].Filename)
  464. // Create a form file with the appropriate content type
  465. h := make(textproto.MIMEHeader)
  466. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  467. h.Set("Content-Type", mimeType)
  468. maskPart, err := writer.CreatePart(h)
  469. if err != nil {
  470. return nil, errors.New("create form file failed for mask")
  471. }
  472. if _, err := io.Copy(maskPart, maskFile); err != nil {
  473. return nil, errors.New("copy mask file failed")
  474. }
  475. _ = maskFile.Close()
  476. }
  477. } else {
  478. return nil, errors.New("no multipart form data found")
  479. }
  480. // 关闭 multipart 编写器以设置分界线
  481. writer.Close()
  482. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  483. return &requestBody, nil
  484. default:
  485. return request, nil
  486. }
  487. }
  488. // detectImageMimeType determines the MIME type based on the file extension
  489. func detectImageMimeType(filename string) string {
  490. ext := strings.ToLower(filepath.Ext(filename))
  491. switch ext {
  492. case ".jpg", ".jpeg":
  493. return "image/jpeg"
  494. case ".png":
  495. return "image/png"
  496. case ".webp":
  497. return "image/webp"
  498. default:
  499. // Try to detect from extension if possible
  500. if strings.HasPrefix(ext, ".jp") {
  501. return "image/jpeg"
  502. }
  503. // Default to png as a fallback
  504. return "image/png"
  505. }
  506. }
  507. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  508. // 转换模型推理力度后缀
  509. effort, originModel := reasoning.ParseOpenAIReasoningEffortFromModelSuffix(request.Model)
  510. if effort != "" {
  511. if request.Reasoning == nil {
  512. request.Reasoning = &dto.Reasoning{
  513. Effort: effort,
  514. }
  515. } else {
  516. request.Reasoning.Effort = effort
  517. }
  518. request.Model = originModel
  519. }
  520. if info != nil && request.Reasoning != nil && request.Reasoning.Effort != "" {
  521. info.ReasoningEffort = request.Reasoning.Effort
  522. }
  523. return request, nil
  524. }
  525. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  526. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  527. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  528. info.RelayMode == relayconstant.RelayModeImagesEdits {
  529. return channel.DoFormRequest(a, c, info, requestBody)
  530. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  531. return channel.DoWssRequest(a, c, info, requestBody)
  532. } else {
  533. return channel.DoApiRequest(a, c, info, requestBody)
  534. }
  535. }
  536. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  537. switch info.RelayMode {
  538. case relayconstant.RelayModeRealtime:
  539. err, usage = OpenaiRealtimeHandler(c, info)
  540. case relayconstant.RelayModeAudioSpeech:
  541. usage = OpenaiTTSHandler(c, resp, info)
  542. case relayconstant.RelayModeAudioTranslation:
  543. fallthrough
  544. case relayconstant.RelayModeAudioTranscription:
  545. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  546. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  547. usage, err = OpenaiHandlerWithUsage(c, info, resp)
  548. case relayconstant.RelayModeRerank:
  549. usage, err = common_handler.RerankHandler(c, info, resp)
  550. case relayconstant.RelayModeResponses:
  551. if info.IsStream {
  552. usage, err = OaiResponsesStreamHandler(c, info, resp)
  553. } else {
  554. usage, err = OaiResponsesHandler(c, info, resp)
  555. }
  556. case relayconstant.RelayModeResponsesCompact:
  557. usage, err = OaiResponsesCompactionHandler(c, resp)
  558. default:
  559. if info.IsStream {
  560. usage, err = OaiStreamHandler(c, info, resp)
  561. } else {
  562. usage, err = OpenaiHandler(c, info, resp)
  563. }
  564. }
  565. return
  566. }
  567. func (a *Adaptor) GetModelList() []string {
  568. switch a.ChannelType {
  569. case constant.ChannelType360:
  570. return ai360.ModelList
  571. case constant.ChannelTypeLingYiWanWu:
  572. return lingyiwanwu.ModelList
  573. //case constant.ChannelTypeMiniMax:
  574. // return minimax.ModelList
  575. case constant.ChannelTypeXinference:
  576. return xinference.ModelList
  577. case constant.ChannelTypeOpenRouter:
  578. return openrouter.ModelList
  579. default:
  580. return ModelList
  581. }
  582. }
  583. func (a *Adaptor) GetChannelName() string {
  584. switch a.ChannelType {
  585. case constant.ChannelType360:
  586. return ai360.ChannelName
  587. case constant.ChannelTypeLingYiWanWu:
  588. return lingyiwanwu.ChannelName
  589. //case constant.ChannelTypeMiniMax:
  590. // return minimax.ChannelName
  591. case constant.ChannelTypeXinference:
  592. return xinference.ChannelName
  593. case constant.ChannelTypeOpenRouter:
  594. return openrouter.ChannelName
  595. default:
  596. return ChannelName
  597. }
  598. }