adaptor.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. if info.RelayMode == relayconstant.RelayModeRealtime {
  173. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  174. if swp != "" {
  175. items := []string{
  176. "realtime",
  177. "openai-insecure-api-key." + info.ApiKey,
  178. "openai-beta.realtime-v1",
  179. }
  180. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  181. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  182. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  183. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  184. } else {
  185. header.Set("openai-beta", "realtime=v1")
  186. header.Set("Authorization", "Bearer "+info.ApiKey)
  187. }
  188. } else {
  189. header.Set("Authorization", "Bearer "+info.ApiKey)
  190. }
  191. if info.ChannelType == constant.ChannelTypeOpenRouter {
  192. header.Set("HTTP-Referer", "https://www.newapi.ai")
  193. header.Set("X-Title", "New API")
  194. }
  195. return nil
  196. }
  197. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  198. if request == nil {
  199. return nil, errors.New("request is nil")
  200. }
  201. if info.ChannelType != constant.ChannelTypeOpenAI && info.ChannelType != constant.ChannelTypeAzure {
  202. request.StreamOptions = nil
  203. }
  204. if info.ChannelType == constant.ChannelTypeOpenRouter {
  205. if len(request.Usage) == 0 {
  206. request.Usage = json.RawMessage(`{"include":true}`)
  207. }
  208. // 适配 OpenRouter 的 thinking 后缀
  209. if !model_setting.ShouldPreserveThinkingSuffix(info.OriginModelName) &&
  210. strings.HasSuffix(info.UpstreamModelName, "-thinking") {
  211. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  212. request.Model = info.UpstreamModelName
  213. if len(request.Reasoning) == 0 {
  214. reasoning := map[string]any{
  215. "enabled": true,
  216. }
  217. if request.ReasoningEffort != "" && request.ReasoningEffort != "none" {
  218. reasoning["effort"] = request.ReasoningEffort
  219. }
  220. marshal, err := common.Marshal(reasoning)
  221. if err != nil {
  222. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  223. }
  224. request.Reasoning = marshal
  225. }
  226. // 清空多余的ReasoningEffort
  227. request.ReasoningEffort = ""
  228. } else {
  229. if len(request.Reasoning) == 0 {
  230. // 适配 OpenAI 的 ReasoningEffort 格式
  231. if request.ReasoningEffort != "" {
  232. reasoning := map[string]any{
  233. "enabled": true,
  234. }
  235. if request.ReasoningEffort != "none" {
  236. reasoning["effort"] = request.ReasoningEffort
  237. marshal, err := common.Marshal(reasoning)
  238. if err != nil {
  239. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  240. }
  241. request.Reasoning = marshal
  242. }
  243. }
  244. }
  245. request.ReasoningEffort = ""
  246. }
  247. // https://docs.anthropic.com/en/api/openai-sdk#extended-thinking-support
  248. // 没有做排除3.5Haiku等,要出问题再加吧,最佳兼容性(不是
  249. if request.THINKING != nil && strings.HasPrefix(info.UpstreamModelName, "anthropic") {
  250. var thinking dto.Thinking // Claude标准Thinking格式
  251. if err := json.Unmarshal(request.THINKING, &thinking); err != nil {
  252. return nil, fmt.Errorf("error Unmarshal thinking: %w", err)
  253. }
  254. // 只有当 thinking.Type 是 "enabled" 时才处理
  255. if thinking.Type == "enabled" {
  256. // 检查 BudgetTokens 是否为 nil
  257. if thinking.BudgetTokens == nil {
  258. return nil, fmt.Errorf("BudgetTokens is nil when thinking is enabled")
  259. }
  260. reasoning := openrouter.RequestReasoning{
  261. MaxTokens: *thinking.BudgetTokens,
  262. }
  263. marshal, err := common.Marshal(reasoning)
  264. if err != nil {
  265. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  266. }
  267. request.Reasoning = marshal
  268. }
  269. // 清空 THINKING
  270. request.THINKING = nil
  271. }
  272. }
  273. if strings.HasPrefix(info.UpstreamModelName, "o") || strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
  274. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  275. request.MaxCompletionTokens = request.MaxTokens
  276. request.MaxTokens = 0
  277. }
  278. if strings.HasPrefix(info.UpstreamModelName, "o") {
  279. request.Temperature = nil
  280. }
  281. // gpt-5系列模型适配 归零不再支持的参数
  282. if strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
  283. request.Temperature = nil
  284. request.TopP = 0 // oai 的 top_p 默认值是 1.0,但是为了 omitempty 属性直接不传,这里显式设置为 0
  285. request.LogProbs = false
  286. }
  287. // 转换模型推理力度后缀
  288. effort, originModel := parseReasoningEffortFromModelSuffix(info.UpstreamModelName)
  289. if effort != "" {
  290. request.ReasoningEffort = effort
  291. info.UpstreamModelName = originModel
  292. request.Model = originModel
  293. }
  294. info.ReasoningEffort = request.ReasoningEffort
  295. // o系列模型developer适配(o1-mini除外)
  296. if !strings.HasPrefix(info.UpstreamModelName, "o1-mini") && !strings.HasPrefix(info.UpstreamModelName, "o1-preview") {
  297. //修改第一个Message的内容,将system改为developer
  298. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  299. request.Messages[0].Role = "developer"
  300. }
  301. }
  302. }
  303. return request, nil
  304. }
  305. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  306. return request, nil
  307. }
  308. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  309. return request, nil
  310. }
  311. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  312. a.ResponseFormat = request.ResponseFormat
  313. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  314. jsonData, err := json.Marshal(request)
  315. if err != nil {
  316. return nil, fmt.Errorf("error marshalling object: %w", err)
  317. }
  318. return bytes.NewReader(jsonData), nil
  319. } else {
  320. var requestBody bytes.Buffer
  321. writer := multipart.NewWriter(&requestBody)
  322. writer.WriteField("model", request.Model)
  323. formData, err2 := common.ParseMultipartFormReusable(c)
  324. if err2 != nil {
  325. return nil, fmt.Errorf("error parsing multipart form: %w", err2)
  326. }
  327. // 打印类似 curl 命令格式的信息
  328. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'model=\"%s\"'", request.Model))
  329. // 遍历表单字段并打印输出
  330. for key, values := range formData.Value {
  331. if key == "model" {
  332. continue
  333. }
  334. for _, value := range values {
  335. writer.WriteField(key, value)
  336. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form '%s=\"%s\"'", key, value))
  337. }
  338. }
  339. // 从 formData 中获取文件
  340. fileHeaders := formData.File["file"]
  341. if len(fileHeaders) == 0 {
  342. return nil, errors.New("file is required")
  343. }
  344. // 使用 formData 中的第一个文件
  345. fileHeader := fileHeaders[0]
  346. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'file=@\"%s\"' (size: %d bytes, content-type: %s)",
  347. fileHeader.Filename, fileHeader.Size, fileHeader.Header.Get("Content-Type")))
  348. file, err := fileHeader.Open()
  349. if err != nil {
  350. return nil, fmt.Errorf("error opening audio file: %v", err)
  351. }
  352. defer file.Close()
  353. part, err := writer.CreateFormFile("file", fileHeader.Filename)
  354. if err != nil {
  355. return nil, errors.New("create form file failed")
  356. }
  357. if _, err := io.Copy(part, file); err != nil {
  358. return nil, errors.New("copy file failed")
  359. }
  360. // 关闭 multipart 编写器以设置分界线
  361. writer.Close()
  362. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  363. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--header 'Content-Type: %s'", writer.FormDataContentType()))
  364. return &requestBody, nil
  365. }
  366. }
  367. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  368. switch info.RelayMode {
  369. case relayconstant.RelayModeImagesEdits:
  370. var requestBody bytes.Buffer
  371. writer := multipart.NewWriter(&requestBody)
  372. writer.WriteField("model", request.Model)
  373. // 使用已解析的 multipart 表单,避免重复解析
  374. mf := c.Request.MultipartForm
  375. if mf == nil {
  376. if _, err := c.MultipartForm(); err != nil {
  377. return nil, errors.New("failed to parse multipart form")
  378. }
  379. mf = c.Request.MultipartForm
  380. }
  381. // 写入所有非文件字段
  382. if mf != nil {
  383. for key, values := range mf.Value {
  384. if key == "model" {
  385. continue
  386. }
  387. for _, value := range values {
  388. writer.WriteField(key, value)
  389. }
  390. }
  391. }
  392. if mf != nil && mf.File != nil {
  393. // Check if "image" field exists in any form, including array notation
  394. var imageFiles []*multipart.FileHeader
  395. var exists bool
  396. // First check for standard "image" field
  397. if imageFiles, exists = mf.File["image"]; !exists || len(imageFiles) == 0 {
  398. // If not found, check for "image[]" field
  399. if imageFiles, exists = mf.File["image[]"]; !exists || len(imageFiles) == 0 {
  400. // If still not found, iterate through all fields to find any that start with "image["
  401. foundArrayImages := false
  402. for fieldName, files := range mf.File {
  403. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  404. foundArrayImages = true
  405. imageFiles = append(imageFiles, files...)
  406. }
  407. }
  408. // If no image fields found at all
  409. if !foundArrayImages && (len(imageFiles) == 0) {
  410. return nil, errors.New("image is required")
  411. }
  412. }
  413. }
  414. // Process all image files
  415. for i, fileHeader := range imageFiles {
  416. file, err := fileHeader.Open()
  417. if err != nil {
  418. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  419. }
  420. // If multiple images, use image[] as the field name
  421. fieldName := "image"
  422. if len(imageFiles) > 1 {
  423. fieldName = "image[]"
  424. }
  425. // Determine MIME type based on file extension
  426. mimeType := detectImageMimeType(fileHeader.Filename)
  427. // Create a form file with the appropriate content type
  428. h := make(textproto.MIMEHeader)
  429. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  430. h.Set("Content-Type", mimeType)
  431. part, err := writer.CreatePart(h)
  432. if err != nil {
  433. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  434. }
  435. if _, err := io.Copy(part, file); err != nil {
  436. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  437. }
  438. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  439. _ = file.Close()
  440. }
  441. // Handle mask file if present
  442. if maskFiles, exists := mf.File["mask"]; exists && len(maskFiles) > 0 {
  443. maskFile, err := maskFiles[0].Open()
  444. if err != nil {
  445. return nil, errors.New("failed to open mask file")
  446. }
  447. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  448. // Determine MIME type for mask file
  449. mimeType := detectImageMimeType(maskFiles[0].Filename)
  450. // Create a form file with the appropriate content type
  451. h := make(textproto.MIMEHeader)
  452. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  453. h.Set("Content-Type", mimeType)
  454. maskPart, err := writer.CreatePart(h)
  455. if err != nil {
  456. return nil, errors.New("create form file failed for mask")
  457. }
  458. if _, err := io.Copy(maskPart, maskFile); err != nil {
  459. return nil, errors.New("copy mask file failed")
  460. }
  461. _ = maskFile.Close()
  462. }
  463. } else {
  464. return nil, errors.New("no multipart form data found")
  465. }
  466. // 关闭 multipart 编写器以设置分界线
  467. writer.Close()
  468. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  469. return &requestBody, nil
  470. default:
  471. return request, nil
  472. }
  473. }
  474. // detectImageMimeType determines the MIME type based on the file extension
  475. func detectImageMimeType(filename string) string {
  476. ext := strings.ToLower(filepath.Ext(filename))
  477. switch ext {
  478. case ".jpg", ".jpeg":
  479. return "image/jpeg"
  480. case ".png":
  481. return "image/png"
  482. case ".webp":
  483. return "image/webp"
  484. default:
  485. // Try to detect from extension if possible
  486. if strings.HasPrefix(ext, ".jp") {
  487. return "image/jpeg"
  488. }
  489. // Default to png as a fallback
  490. return "image/png"
  491. }
  492. }
  493. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  494. // 转换模型推理力度后缀
  495. effort, originModel := parseReasoningEffortFromModelSuffix(request.Model)
  496. if effort != "" {
  497. if request.Reasoning == nil {
  498. request.Reasoning = &dto.Reasoning{
  499. Effort: effort,
  500. }
  501. } else {
  502. request.Reasoning.Effort = effort
  503. }
  504. request.Model = originModel
  505. }
  506. return request, nil
  507. }
  508. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  509. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  510. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  511. info.RelayMode == relayconstant.RelayModeImagesEdits {
  512. return channel.DoFormRequest(a, c, info, requestBody)
  513. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  514. return channel.DoWssRequest(a, c, info, requestBody)
  515. } else {
  516. return channel.DoApiRequest(a, c, info, requestBody)
  517. }
  518. }
  519. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  520. switch info.RelayMode {
  521. case relayconstant.RelayModeRealtime:
  522. err, usage = OpenaiRealtimeHandler(c, info)
  523. case relayconstant.RelayModeAudioSpeech:
  524. usage = OpenaiTTSHandler(c, resp, info)
  525. case relayconstant.RelayModeAudioTranslation:
  526. fallthrough
  527. case relayconstant.RelayModeAudioTranscription:
  528. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  529. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  530. usage, err = OpenaiHandlerWithUsage(c, info, resp)
  531. case relayconstant.RelayModeRerank:
  532. usage, err = common_handler.RerankHandler(c, info, resp)
  533. case relayconstant.RelayModeResponses:
  534. if info.IsStream {
  535. usage, err = OaiResponsesStreamHandler(c, info, resp)
  536. } else {
  537. usage, err = OaiResponsesHandler(c, info, resp)
  538. }
  539. default:
  540. if info.IsStream {
  541. usage, err = OaiStreamHandler(c, info, resp)
  542. } else {
  543. usage, err = OpenaiHandler(c, info, resp)
  544. }
  545. }
  546. return
  547. }
  548. func (a *Adaptor) GetModelList() []string {
  549. switch a.ChannelType {
  550. case constant.ChannelType360:
  551. return ai360.ModelList
  552. case constant.ChannelTypeLingYiWanWu:
  553. return lingyiwanwu.ModelList
  554. //case constant.ChannelTypeMiniMax:
  555. // return minimax.ModelList
  556. case constant.ChannelTypeXinference:
  557. return xinference.ModelList
  558. case constant.ChannelTypeOpenRouter:
  559. return openrouter.ModelList
  560. default:
  561. return ModelList
  562. }
  563. }
  564. func (a *Adaptor) GetChannelName() string {
  565. switch a.ChannelType {
  566. case constant.ChannelType360:
  567. return ai360.ChannelName
  568. case constant.ChannelTypeLingYiWanWu:
  569. return lingyiwanwu.ChannelName
  570. //case constant.ChannelTypeMiniMax:
  571. // return minimax.ChannelName
  572. case constant.ChannelTypeXinference:
  573. return xinference.ChannelName
  574. case constant.ChannelTypeOpenRouter:
  575. return openrouter.ChannelName
  576. default:
  577. return ChannelName
  578. }
  579. }