adaptor.go 22 KB

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