adaptor.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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"}
  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. if strings.HasPrefix(info.UpstreamModelName, "gpt-5") {
  282. if info.UpstreamModelName != "gpt-5-chat-latest" {
  283. request.Temperature = nil
  284. }
  285. }
  286. // 转换模型推理力度后缀
  287. effort, originModel := parseReasoningEffortFromModelSuffix(info.UpstreamModelName)
  288. if effort != "" {
  289. request.ReasoningEffort = effort
  290. info.UpstreamModelName = originModel
  291. request.Model = originModel
  292. }
  293. info.ReasoningEffort = request.ReasoningEffort
  294. // o系列模型developer适配(o1-mini除外)
  295. if !strings.HasPrefix(info.UpstreamModelName, "o1-mini") && !strings.HasPrefix(info.UpstreamModelName, "o1-preview") {
  296. //修改第一个Message的内容,将system改为developer
  297. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  298. request.Messages[0].Role = "developer"
  299. }
  300. }
  301. }
  302. return request, nil
  303. }
  304. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  305. return request, nil
  306. }
  307. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  308. return request, nil
  309. }
  310. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  311. a.ResponseFormat = request.ResponseFormat
  312. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  313. jsonData, err := json.Marshal(request)
  314. if err != nil {
  315. return nil, fmt.Errorf("error marshalling object: %w", err)
  316. }
  317. return bytes.NewReader(jsonData), nil
  318. } else {
  319. var requestBody bytes.Buffer
  320. writer := multipart.NewWriter(&requestBody)
  321. writer.WriteField("model", request.Model)
  322. formData, err2 := common.ParseMultipartFormReusable(c)
  323. if err2 != nil {
  324. return nil, fmt.Errorf("error parsing multipart form: %w", err2)
  325. }
  326. // 打印类似 curl 命令格式的信息
  327. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'model=\"%s\"'", request.Model))
  328. // 遍历表单字段并打印输出
  329. for key, values := range formData.Value {
  330. if key == "model" {
  331. continue
  332. }
  333. for _, value := range values {
  334. writer.WriteField(key, value)
  335. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form '%s=\"%s\"'", key, value))
  336. }
  337. }
  338. // 从 formData 中获取文件
  339. fileHeaders := formData.File["file"]
  340. if len(fileHeaders) == 0 {
  341. return nil, errors.New("file is required")
  342. }
  343. // 使用 formData 中的第一个文件
  344. fileHeader := fileHeaders[0]
  345. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--form 'file=@\"%s\"' (size: %d bytes, content-type: %s)",
  346. fileHeader.Filename, fileHeader.Size, fileHeader.Header.Get("Content-Type")))
  347. file, err := fileHeader.Open()
  348. if err != nil {
  349. return nil, fmt.Errorf("error opening audio file: %v", err)
  350. }
  351. defer file.Close()
  352. part, err := writer.CreateFormFile("file", fileHeader.Filename)
  353. if err != nil {
  354. return nil, errors.New("create form file failed")
  355. }
  356. if _, err := io.Copy(part, file); err != nil {
  357. return nil, errors.New("copy file failed")
  358. }
  359. // 关闭 multipart 编写器以设置分界线
  360. writer.Close()
  361. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  362. logger.LogDebug(c.Request.Context(), fmt.Sprintf("--header 'Content-Type: %s'", writer.FormDataContentType()))
  363. return &requestBody, nil
  364. }
  365. }
  366. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  367. switch info.RelayMode {
  368. case relayconstant.RelayModeImagesEdits:
  369. var requestBody bytes.Buffer
  370. writer := multipart.NewWriter(&requestBody)
  371. writer.WriteField("model", request.Model)
  372. // 使用已解析的 multipart 表单,避免重复解析
  373. mf := c.Request.MultipartForm
  374. if mf == nil {
  375. if _, err := c.MultipartForm(); err != nil {
  376. return nil, errors.New("failed to parse multipart form")
  377. }
  378. mf = c.Request.MultipartForm
  379. }
  380. // 写入所有非文件字段
  381. if mf != nil {
  382. for key, values := range mf.Value {
  383. if key == "model" {
  384. continue
  385. }
  386. for _, value := range values {
  387. writer.WriteField(key, value)
  388. }
  389. }
  390. }
  391. if mf != nil && mf.File != nil {
  392. // Check if "image" field exists in any form, including array notation
  393. var imageFiles []*multipart.FileHeader
  394. var exists bool
  395. // First check for standard "image" field
  396. if imageFiles, exists = mf.File["image"]; !exists || len(imageFiles) == 0 {
  397. // If not found, check for "image[]" field
  398. if imageFiles, exists = mf.File["image[]"]; !exists || len(imageFiles) == 0 {
  399. // If still not found, iterate through all fields to find any that start with "image["
  400. foundArrayImages := false
  401. for fieldName, files := range mf.File {
  402. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  403. foundArrayImages = true
  404. imageFiles = append(imageFiles, files...)
  405. }
  406. }
  407. // If no image fields found at all
  408. if !foundArrayImages && (len(imageFiles) == 0) {
  409. return nil, errors.New("image is required")
  410. }
  411. }
  412. }
  413. // Process all image files
  414. for i, fileHeader := range imageFiles {
  415. file, err := fileHeader.Open()
  416. if err != nil {
  417. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  418. }
  419. // If multiple images, use image[] as the field name
  420. fieldName := "image"
  421. if len(imageFiles) > 1 {
  422. fieldName = "image[]"
  423. }
  424. // Determine MIME type based on file extension
  425. mimeType := detectImageMimeType(fileHeader.Filename)
  426. // Create a form file with the appropriate content type
  427. h := make(textproto.MIMEHeader)
  428. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  429. h.Set("Content-Type", mimeType)
  430. part, err := writer.CreatePart(h)
  431. if err != nil {
  432. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  433. }
  434. if _, err := io.Copy(part, file); err != nil {
  435. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  436. }
  437. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  438. _ = file.Close()
  439. }
  440. // Handle mask file if present
  441. if maskFiles, exists := mf.File["mask"]; exists && len(maskFiles) > 0 {
  442. maskFile, err := maskFiles[0].Open()
  443. if err != nil {
  444. return nil, errors.New("failed to open mask file")
  445. }
  446. // 复制完立即关闭,避免在循环内使用 defer 占用资源
  447. // Determine MIME type for mask file
  448. mimeType := detectImageMimeType(maskFiles[0].Filename)
  449. // Create a form file with the appropriate content type
  450. h := make(textproto.MIMEHeader)
  451. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  452. h.Set("Content-Type", mimeType)
  453. maskPart, err := writer.CreatePart(h)
  454. if err != nil {
  455. return nil, errors.New("create form file failed for mask")
  456. }
  457. if _, err := io.Copy(maskPart, maskFile); err != nil {
  458. return nil, errors.New("copy mask file failed")
  459. }
  460. _ = maskFile.Close()
  461. }
  462. } else {
  463. return nil, errors.New("no multipart form data found")
  464. }
  465. // 关闭 multipart 编写器以设置分界线
  466. writer.Close()
  467. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  468. return &requestBody, nil
  469. default:
  470. return request, nil
  471. }
  472. }
  473. // detectImageMimeType determines the MIME type based on the file extension
  474. func detectImageMimeType(filename string) string {
  475. ext := strings.ToLower(filepath.Ext(filename))
  476. switch ext {
  477. case ".jpg", ".jpeg":
  478. return "image/jpeg"
  479. case ".png":
  480. return "image/png"
  481. case ".webp":
  482. return "image/webp"
  483. default:
  484. // Try to detect from extension if possible
  485. if strings.HasPrefix(ext, ".jp") {
  486. return "image/jpeg"
  487. }
  488. // Default to png as a fallback
  489. return "image/png"
  490. }
  491. }
  492. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  493. // 转换模型推理力度后缀
  494. effort, originModel := parseReasoningEffortFromModelSuffix(request.Model)
  495. if effort != "" {
  496. if request.Reasoning == nil {
  497. request.Reasoning = &dto.Reasoning{
  498. Effort: effort,
  499. }
  500. } else {
  501. request.Reasoning.Effort = effort
  502. }
  503. request.Model = originModel
  504. }
  505. return request, nil
  506. }
  507. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  508. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  509. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  510. info.RelayMode == relayconstant.RelayModeImagesEdits {
  511. return channel.DoFormRequest(a, c, info, requestBody)
  512. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  513. return channel.DoWssRequest(a, c, info, requestBody)
  514. } else {
  515. return channel.DoApiRequest(a, c, info, requestBody)
  516. }
  517. }
  518. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  519. switch info.RelayMode {
  520. case relayconstant.RelayModeRealtime:
  521. err, usage = OpenaiRealtimeHandler(c, info)
  522. case relayconstant.RelayModeAudioSpeech:
  523. usage = OpenaiTTSHandler(c, resp, info)
  524. case relayconstant.RelayModeAudioTranslation:
  525. fallthrough
  526. case relayconstant.RelayModeAudioTranscription:
  527. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  528. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  529. usage, err = OpenaiHandlerWithUsage(c, info, resp)
  530. case relayconstant.RelayModeRerank:
  531. usage, err = common_handler.RerankHandler(c, info, resp)
  532. case relayconstant.RelayModeResponses:
  533. if info.IsStream {
  534. usage, err = OaiResponsesStreamHandler(c, info, resp)
  535. } else {
  536. usage, err = OaiResponsesHandler(c, info, resp)
  537. }
  538. default:
  539. if info.IsStream {
  540. usage, err = OaiStreamHandler(c, info, resp)
  541. } else {
  542. usage, err = OpenaiHandler(c, info, resp)
  543. }
  544. }
  545. return
  546. }
  547. func (a *Adaptor) GetModelList() []string {
  548. switch a.ChannelType {
  549. case constant.ChannelType360:
  550. return ai360.ModelList
  551. case constant.ChannelTypeLingYiWanWu:
  552. return lingyiwanwu.ModelList
  553. //case constant.ChannelTypeMiniMax:
  554. // return minimax.ModelList
  555. case constant.ChannelTypeXinference:
  556. return xinference.ModelList
  557. case constant.ChannelTypeOpenRouter:
  558. return openrouter.ModelList
  559. default:
  560. return ModelList
  561. }
  562. }
  563. func (a *Adaptor) GetChannelName() string {
  564. switch a.ChannelType {
  565. case constant.ChannelType360:
  566. return ai360.ChannelName
  567. case constant.ChannelTypeLingYiWanWu:
  568. return lingyiwanwu.ChannelName
  569. //case constant.ChannelTypeMiniMax:
  570. // return minimax.ChannelName
  571. case constant.ChannelTypeXinference:
  572. return xinference.ChannelName
  573. case constant.ChannelTypeOpenRouter:
  574. return openrouter.ChannelName
  575. default:
  576. return ChannelName
  577. }
  578. }