adaptor.go 21 KB

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