adaptor.go 22 KB

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