adaptor.go 20 KB

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