adaptor.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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.BaseUrl, "https://") {
  100. baseUrl := strings.TrimPrefix(info.BaseUrl, "https://")
  101. baseUrl = "wss://" + baseUrl
  102. info.BaseUrl = baseUrl
  103. } else if strings.HasPrefix(info.BaseUrl, "http://") {
  104. baseUrl := strings.TrimPrefix(info.BaseUrl, "http://")
  105. baseUrl = "ws://" + baseUrl
  106. info.BaseUrl = 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. // 特殊处理 responses API
  120. if info.RelayMode == relayconstant.RelayModeResponses {
  121. requestURL = fmt.Sprintf("/openai/v1/responses?api-version=preview")
  122. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  123. }
  124. model_ := info.UpstreamModelName
  125. // 2025年5月10日后创建的渠道不移除.
  126. if info.ChannelCreateTime < constant.AzureNoRemoveDotTime {
  127. model_ = strings.Replace(model_, ".", "", -1)
  128. }
  129. // https://github.com/songquanpeng/one-api/issues/67
  130. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  131. if info.RelayMode == relayconstant.RelayModeRealtime {
  132. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, apiVersion)
  133. }
  134. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  135. case constant.ChannelTypeMiniMax:
  136. return minimax.GetRequestURL(info)
  137. case constant.ChannelTypeCustom:
  138. url := info.BaseUrl
  139. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  140. return url, nil
  141. default:
  142. if info.RelayFormat == relaycommon.RelayFormatClaude || info.RelayFormat == relaycommon.RelayFormatGemini {
  143. return fmt.Sprintf("%s/v1/chat/completions", info.BaseUrl), nil
  144. }
  145. return relaycommon.GetFullRequestURL(info.BaseUrl, info.RequestURLPath, info.ChannelType), nil
  146. }
  147. }
  148. func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *relaycommon.RelayInfo) error {
  149. channel.SetupApiRequestHeader(info, c, header)
  150. if info.ChannelType == constant.ChannelTypeAzure {
  151. header.Set("api-key", info.ApiKey)
  152. return nil
  153. }
  154. if info.ChannelType == constant.ChannelTypeOpenAI && "" != info.Organization {
  155. header.Set("OpenAI-Organization", info.Organization)
  156. }
  157. if info.RelayMode == relayconstant.RelayModeRealtime {
  158. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  159. if swp != "" {
  160. items := []string{
  161. "realtime",
  162. "openai-insecure-api-key." + info.ApiKey,
  163. "openai-beta.realtime-v1",
  164. }
  165. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  166. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  167. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  168. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  169. } else {
  170. header.Set("openai-beta", "realtime=v1")
  171. header.Set("Authorization", "Bearer "+info.ApiKey)
  172. }
  173. } else {
  174. header.Set("Authorization", "Bearer "+info.ApiKey)
  175. }
  176. if info.ChannelType == constant.ChannelTypeOpenRouter {
  177. header.Set("HTTP-Referer", "https://www.newapi.ai")
  178. header.Set("X-Title", "New API")
  179. }
  180. return nil
  181. }
  182. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  183. if request == nil {
  184. return nil, errors.New("request is nil")
  185. }
  186. if info.ChannelType != constant.ChannelTypeOpenAI && info.ChannelType != constant.ChannelTypeAzure {
  187. request.StreamOptions = nil
  188. }
  189. if info.ChannelType == constant.ChannelTypeOpenRouter {
  190. if len(request.Usage) == 0 {
  191. request.Usage = json.RawMessage(`{"include":true}`)
  192. }
  193. // 适配 OpenRouter 的 thinking 后缀
  194. if strings.HasSuffix(info.UpstreamModelName, "-thinking") {
  195. info.UpstreamModelName = strings.TrimSuffix(info.UpstreamModelName, "-thinking")
  196. request.Model = info.UpstreamModelName
  197. if len(request.Reasoning) == 0 {
  198. reasoning := map[string]any{
  199. "enabled": true,
  200. }
  201. if request.ReasoningEffort != "" && request.ReasoningEffort != "none" {
  202. reasoning["effort"] = request.ReasoningEffort
  203. }
  204. marshal, err := common.Marshal(reasoning)
  205. if err != nil {
  206. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  207. }
  208. request.Reasoning = marshal
  209. }
  210. } else {
  211. if len(request.Reasoning) == 0 {
  212. // 适配 OpenAI 的 ReasoningEffort 格式
  213. if request.ReasoningEffort != "" {
  214. reasoning := map[string]any{
  215. "enabled": true,
  216. }
  217. if request.ReasoningEffort != "none" {
  218. reasoning["effort"] = request.ReasoningEffort
  219. marshal, err := common.Marshal(reasoning)
  220. if err != nil {
  221. return nil, fmt.Errorf("error marshalling reasoning: %w", err)
  222. }
  223. request.Reasoning = marshal
  224. }
  225. }
  226. }
  227. }
  228. }
  229. if strings.HasPrefix(request.Model, "o") || strings.HasPrefix(request.Model, "gpt-5") {
  230. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  231. request.MaxCompletionTokens = request.MaxTokens
  232. request.MaxTokens = 0
  233. }
  234. if strings.HasPrefix(request.Model, "o") {
  235. request.Temperature = nil
  236. }
  237. if strings.HasPrefix(request.Model, "gpt-5") {
  238. if request.Model != "gpt-5-chat-latest" {
  239. request.Temperature = nil
  240. }
  241. }
  242. // 转换模型推理力度后缀
  243. effort, originModel := parseReasoningEffortFromModelSuffix(request.Model)
  244. if effort != "" {
  245. request.ReasoningEffort = effort
  246. request.Model = originModel
  247. }
  248. info.ReasoningEffort = request.ReasoningEffort
  249. info.UpstreamModelName = request.Model
  250. // o系列模型developer适配(o1-mini除外)
  251. if !strings.HasPrefix(request.Model, "o1-mini") && !strings.HasPrefix(request.Model, "o1-preview") {
  252. //修改第一个Message的内容,将system改为developer
  253. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  254. request.Messages[0].Role = "developer"
  255. }
  256. }
  257. }
  258. return request, nil
  259. }
  260. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  261. return request, nil
  262. }
  263. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  264. return request, nil
  265. }
  266. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  267. a.ResponseFormat = request.ResponseFormat
  268. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  269. jsonData, err := json.Marshal(request)
  270. if err != nil {
  271. return nil, fmt.Errorf("error marshalling object: %w", err)
  272. }
  273. return bytes.NewReader(jsonData), nil
  274. } else {
  275. var requestBody bytes.Buffer
  276. writer := multipart.NewWriter(&requestBody)
  277. writer.WriteField("model", request.Model)
  278. // 获取所有表单字段
  279. formData := c.Request.PostForm
  280. // 遍历表单字段并打印输出
  281. for key, values := range formData {
  282. if key == "model" {
  283. continue
  284. }
  285. for _, value := range values {
  286. writer.WriteField(key, value)
  287. }
  288. }
  289. // 添加文件字段
  290. file, header, err := c.Request.FormFile("file")
  291. if err != nil {
  292. return nil, errors.New("file is required")
  293. }
  294. defer file.Close()
  295. part, err := writer.CreateFormFile("file", header.Filename)
  296. if err != nil {
  297. return nil, errors.New("create form file failed")
  298. }
  299. if _, err := io.Copy(part, file); err != nil {
  300. return nil, errors.New("copy file failed")
  301. }
  302. // 关闭 multipart 编写器以设置分界线
  303. writer.Close()
  304. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  305. return &requestBody, nil
  306. }
  307. }
  308. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  309. switch info.RelayMode {
  310. case relayconstant.RelayModeImagesEdits:
  311. var requestBody bytes.Buffer
  312. writer := multipart.NewWriter(&requestBody)
  313. writer.WriteField("model", request.Model)
  314. // 获取所有表单字段
  315. formData := c.Request.PostForm
  316. // 遍历表单字段并打印输出
  317. for key, values := range formData {
  318. if key == "model" {
  319. continue
  320. }
  321. for _, value := range values {
  322. writer.WriteField(key, value)
  323. }
  324. }
  325. // Parse the multipart form to handle both single image and multiple images
  326. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  327. return nil, errors.New("failed to parse multipart form")
  328. }
  329. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  330. // Check if "image" field exists in any form, including array notation
  331. var imageFiles []*multipart.FileHeader
  332. var exists bool
  333. // First check for standard "image" field
  334. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  335. // If not found, check for "image[]" field
  336. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  337. // If still not found, iterate through all fields to find any that start with "image["
  338. foundArrayImages := false
  339. for fieldName, files := range c.Request.MultipartForm.File {
  340. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  341. foundArrayImages = true
  342. for _, file := range files {
  343. imageFiles = append(imageFiles, file)
  344. }
  345. }
  346. }
  347. // If no image fields found at all
  348. if !foundArrayImages && (len(imageFiles) == 0) {
  349. return nil, errors.New("image is required")
  350. }
  351. }
  352. }
  353. // Process all image files
  354. for i, fileHeader := range imageFiles {
  355. file, err := fileHeader.Open()
  356. if err != nil {
  357. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  358. }
  359. defer file.Close()
  360. // If multiple images, use image[] as the field name
  361. fieldName := "image"
  362. if len(imageFiles) > 1 {
  363. fieldName = "image[]"
  364. }
  365. // Determine MIME type based on file extension
  366. mimeType := detectImageMimeType(fileHeader.Filename)
  367. // Create a form file with the appropriate content type
  368. h := make(textproto.MIMEHeader)
  369. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  370. h.Set("Content-Type", mimeType)
  371. part, err := writer.CreatePart(h)
  372. if err != nil {
  373. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  374. }
  375. if _, err := io.Copy(part, file); err != nil {
  376. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  377. }
  378. }
  379. // Handle mask file if present
  380. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  381. maskFile, err := maskFiles[0].Open()
  382. if err != nil {
  383. return nil, errors.New("failed to open mask file")
  384. }
  385. defer maskFile.Close()
  386. // Determine MIME type for mask file
  387. mimeType := detectImageMimeType(maskFiles[0].Filename)
  388. // Create a form file with the appropriate content type
  389. h := make(textproto.MIMEHeader)
  390. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  391. h.Set("Content-Type", mimeType)
  392. maskPart, err := writer.CreatePart(h)
  393. if err != nil {
  394. return nil, errors.New("create form file failed for mask")
  395. }
  396. if _, err := io.Copy(maskPart, maskFile); err != nil {
  397. return nil, errors.New("copy mask file failed")
  398. }
  399. }
  400. } else {
  401. return nil, errors.New("no multipart form data found")
  402. }
  403. // 关闭 multipart 编写器以设置分界线
  404. writer.Close()
  405. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  406. return bytes.NewReader(requestBody.Bytes()), nil
  407. default:
  408. return request, nil
  409. }
  410. }
  411. // detectImageMimeType determines the MIME type based on the file extension
  412. func detectImageMimeType(filename string) string {
  413. ext := strings.ToLower(filepath.Ext(filename))
  414. switch ext {
  415. case ".jpg", ".jpeg":
  416. return "image/jpeg"
  417. case ".png":
  418. return "image/png"
  419. case ".webp":
  420. return "image/webp"
  421. default:
  422. // Try to detect from extension if possible
  423. if strings.HasPrefix(ext, ".jp") {
  424. return "image/jpeg"
  425. }
  426. // Default to png as a fallback
  427. return "image/png"
  428. }
  429. }
  430. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  431. // 转换模型推理力度后缀
  432. effort, originModel := parseReasoningEffortFromModelSuffix(request.Model)
  433. if effort != "" {
  434. request.Reasoning.Effort = effort
  435. request.Model = originModel
  436. }
  437. return request, nil
  438. }
  439. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  440. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  441. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  442. info.RelayMode == relayconstant.RelayModeImagesEdits {
  443. return channel.DoFormRequest(a, c, info, requestBody)
  444. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  445. return channel.DoWssRequest(a, c, info, requestBody)
  446. } else {
  447. return channel.DoApiRequest(a, c, info, requestBody)
  448. }
  449. }
  450. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  451. switch info.RelayMode {
  452. case relayconstant.RelayModeRealtime:
  453. err, usage = OpenaiRealtimeHandler(c, info)
  454. case relayconstant.RelayModeAudioSpeech:
  455. usage = OpenaiTTSHandler(c, resp, info)
  456. case relayconstant.RelayModeAudioTranslation:
  457. fallthrough
  458. case relayconstant.RelayModeAudioTranscription:
  459. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  460. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  461. usage, err = OpenaiHandlerWithUsage(c, info, resp)
  462. case relayconstant.RelayModeRerank:
  463. usage, err = common_handler.RerankHandler(c, info, resp)
  464. case relayconstant.RelayModeResponses:
  465. if info.IsStream {
  466. usage, err = OaiResponsesStreamHandler(c, info, resp)
  467. } else {
  468. usage, err = OaiResponsesHandler(c, info, resp)
  469. }
  470. default:
  471. if info.IsStream {
  472. usage, err = OaiStreamHandler(c, info, resp)
  473. } else {
  474. usage, err = OpenaiHandler(c, info, resp)
  475. }
  476. }
  477. return
  478. }
  479. func (a *Adaptor) GetModelList() []string {
  480. switch a.ChannelType {
  481. case constant.ChannelType360:
  482. return ai360.ModelList
  483. case constant.ChannelTypeLingYiWanWu:
  484. return lingyiwanwu.ModelList
  485. case constant.ChannelTypeMiniMax:
  486. return minimax.ModelList
  487. case constant.ChannelTypeXinference:
  488. return xinference.ModelList
  489. case constant.ChannelTypeOpenRouter:
  490. return openrouter.ModelList
  491. default:
  492. return ModelList
  493. }
  494. }
  495. func (a *Adaptor) GetChannelName() string {
  496. switch a.ChannelType {
  497. case constant.ChannelType360:
  498. return ai360.ChannelName
  499. case constant.ChannelTypeLingYiWanWu:
  500. return lingyiwanwu.ChannelName
  501. case constant.ChannelTypeMiniMax:
  502. return minimax.ChannelName
  503. case constant.ChannelTypeXinference:
  504. return xinference.ChannelName
  505. case constant.ChannelTypeOpenRouter:
  506. return openrouter.ChannelName
  507. default:
  508. return ChannelName
  509. }
  510. }