adaptor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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/constant"
  12. "one-api/dto"
  13. "one-api/relay/channel"
  14. "one-api/relay/channel/ai360"
  15. "one-api/relay/channel/lingyiwanwu"
  16. "one-api/relay/channel/minimax"
  17. "one-api/relay/channel/moonshot"
  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. "path/filepath"
  25. "strings"
  26. "github.com/gin-gonic/gin"
  27. )
  28. type Adaptor struct {
  29. ChannelType int
  30. ResponseFormat string
  31. }
  32. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.ClaudeRequest) (any, error) {
  33. if !strings.Contains(request.Model, "claude") {
  34. return nil, fmt.Errorf("you are using openai channel type with path /v1/messages, only claude model supported convert, but got %s", request.Model)
  35. }
  36. aiRequest, err := service.ClaudeToOpenAIRequest(*request, info)
  37. if err != nil {
  38. return nil, err
  39. }
  40. if info.SupportStreamOptions {
  41. aiRequest.StreamOptions = &dto.StreamOptions{
  42. IncludeUsage: true,
  43. }
  44. }
  45. return a.ConvertOpenAIRequest(c, info, aiRequest)
  46. }
  47. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  48. a.ChannelType = info.ChannelType
  49. // initialize ThinkingContentInfo when thinking_to_content is enabled
  50. if think2Content, ok := info.ChannelSetting[constant.ChannelSettingThinkingToContent].(bool); ok && think2Content {
  51. info.ThinkingContentInfo = relaycommon.ThinkingContentInfo{
  52. IsFirstThinkingContent: true,
  53. SendLastThinkingContent: false,
  54. HasSentThinkingContent: false,
  55. }
  56. }
  57. }
  58. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  59. if info.RelayFormat == relaycommon.RelayFormatClaude {
  60. return fmt.Sprintf("%s/v1/chat/completions", info.BaseUrl), nil
  61. }
  62. if info.RelayMode == relayconstant.RelayModeRealtime {
  63. if strings.HasPrefix(info.BaseUrl, "https://") {
  64. baseUrl := strings.TrimPrefix(info.BaseUrl, "https://")
  65. baseUrl = "wss://" + baseUrl
  66. info.BaseUrl = baseUrl
  67. } else if strings.HasPrefix(info.BaseUrl, "http://") {
  68. baseUrl := strings.TrimPrefix(info.BaseUrl, "http://")
  69. baseUrl = "ws://" + baseUrl
  70. info.BaseUrl = baseUrl
  71. }
  72. }
  73. switch info.ChannelType {
  74. case constant.ChannelTypeAzure:
  75. apiVersion := info.ApiVersion
  76. if apiVersion == "" {
  77. apiVersion = constant.AzureDefaultAPIVersion
  78. }
  79. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  80. requestURL := strings.Split(info.RequestURLPath, "?")[0]
  81. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
  82. task := strings.TrimPrefix(requestURL, "/v1/")
  83. // 特殊处理 responses API
  84. if info.RelayMode == relayconstant.RelayModeResponses {
  85. requestURL = fmt.Sprintf("/openai/v1/responses?api-version=preview")
  86. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  87. }
  88. model_ := info.UpstreamModelName
  89. // 2025年5月10日后创建的渠道不移除.
  90. if info.ChannelCreateTime < constant.AzureNoRemoveDotTime {
  91. model_ = strings.Replace(model_, ".", "", -1)
  92. }
  93. // https://github.com/songquanpeng/one-api/issues/67
  94. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  95. if info.RelayMode == relayconstant.RelayModeRealtime {
  96. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, apiVersion)
  97. }
  98. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  99. case constant.ChannelTypeMiniMax:
  100. return minimax.GetRequestURL(info)
  101. case constant.ChannelTypeCustom:
  102. url := info.BaseUrl
  103. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  104. return url, nil
  105. default:
  106. return relaycommon.GetFullRequestURL(info.BaseUrl, info.RequestURLPath, info.ChannelType), nil
  107. }
  108. }
  109. func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *relaycommon.RelayInfo) error {
  110. channel.SetupApiRequestHeader(info, c, header)
  111. if info.ChannelType == constant.ChannelTypeAzure {
  112. header.Set("api-key", info.ApiKey)
  113. return nil
  114. }
  115. if info.ChannelType == constant.ChannelTypeOpenAI && "" != info.Organization {
  116. header.Set("OpenAI-Organization", info.Organization)
  117. }
  118. if info.RelayMode == relayconstant.RelayModeRealtime {
  119. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  120. if swp != "" {
  121. items := []string{
  122. "realtime",
  123. "openai-insecure-api-key." + info.ApiKey,
  124. "openai-beta.realtime-v1",
  125. }
  126. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  127. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  128. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  129. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  130. } else {
  131. header.Set("openai-beta", "realtime=v1")
  132. header.Set("Authorization", "Bearer "+info.ApiKey)
  133. }
  134. } else {
  135. header.Set("Authorization", "Bearer "+info.ApiKey)
  136. }
  137. if info.ChannelType == constant.ChannelTypeOpenRouter {
  138. header.Set("HTTP-Referer", "https://github.com/Calcium-Ion/new-api")
  139. header.Set("X-Title", "New API")
  140. }
  141. return nil
  142. }
  143. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  144. if request == nil {
  145. return nil, errors.New("request is nil")
  146. }
  147. if info.ChannelType != constant.ChannelTypeOpenAI && info.ChannelType != constant.ChannelTypeAzure {
  148. request.StreamOptions = nil
  149. }
  150. if info.ChannelType == constant.ChannelTypeOpenRouter {
  151. if len(request.Usage) == 0 {
  152. request.Usage = json.RawMessage(`{"include":true}`)
  153. }
  154. }
  155. if strings.HasPrefix(request.Model, "o") {
  156. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  157. request.MaxCompletionTokens = request.MaxTokens
  158. request.MaxTokens = 0
  159. }
  160. request.Temperature = nil
  161. if strings.HasSuffix(request.Model, "-high") {
  162. request.ReasoningEffort = "high"
  163. request.Model = strings.TrimSuffix(request.Model, "-high")
  164. } else if strings.HasSuffix(request.Model, "-low") {
  165. request.ReasoningEffort = "low"
  166. request.Model = strings.TrimSuffix(request.Model, "-low")
  167. } else if strings.HasSuffix(request.Model, "-medium") {
  168. request.ReasoningEffort = "medium"
  169. request.Model = strings.TrimSuffix(request.Model, "-medium")
  170. }
  171. info.ReasoningEffort = request.ReasoningEffort
  172. info.UpstreamModelName = request.Model
  173. // o系列模型developer适配(o1-mini除外)
  174. if !strings.HasPrefix(request.Model, "o1-mini") && !strings.HasPrefix(request.Model, "o1-preview") {
  175. //修改第一个Message的内容,将system改为developer
  176. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  177. request.Messages[0].Role = "developer"
  178. }
  179. }
  180. }
  181. return request, nil
  182. }
  183. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  184. return request, nil
  185. }
  186. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  187. return request, nil
  188. }
  189. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  190. a.ResponseFormat = request.ResponseFormat
  191. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  192. jsonData, err := json.Marshal(request)
  193. if err != nil {
  194. return nil, fmt.Errorf("error marshalling object: %w", err)
  195. }
  196. return bytes.NewReader(jsonData), nil
  197. } else {
  198. var requestBody bytes.Buffer
  199. writer := multipart.NewWriter(&requestBody)
  200. writer.WriteField("model", request.Model)
  201. // 获取所有表单字段
  202. formData := c.Request.PostForm
  203. // 遍历表单字段并打印输出
  204. for key, values := range formData {
  205. if key == "model" {
  206. continue
  207. }
  208. for _, value := range values {
  209. writer.WriteField(key, value)
  210. }
  211. }
  212. // 添加文件字段
  213. file, header, err := c.Request.FormFile("file")
  214. if err != nil {
  215. return nil, errors.New("file is required")
  216. }
  217. defer file.Close()
  218. part, err := writer.CreateFormFile("file", header.Filename)
  219. if err != nil {
  220. return nil, errors.New("create form file failed")
  221. }
  222. if _, err := io.Copy(part, file); err != nil {
  223. return nil, errors.New("copy file failed")
  224. }
  225. // 关闭 multipart 编写器以设置分界线
  226. writer.Close()
  227. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  228. return &requestBody, nil
  229. }
  230. }
  231. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  232. switch info.RelayMode {
  233. case relayconstant.RelayModeImagesEdits:
  234. var requestBody bytes.Buffer
  235. writer := multipart.NewWriter(&requestBody)
  236. writer.WriteField("model", request.Model)
  237. // 获取所有表单字段
  238. formData := c.Request.PostForm
  239. // 遍历表单字段并打印输出
  240. for key, values := range formData {
  241. if key == "model" {
  242. continue
  243. }
  244. for _, value := range values {
  245. writer.WriteField(key, value)
  246. }
  247. }
  248. // Parse the multipart form to handle both single image and multiple images
  249. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  250. return nil, errors.New("failed to parse multipart form")
  251. }
  252. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  253. // Check if "image" field exists in any form, including array notation
  254. var imageFiles []*multipart.FileHeader
  255. var exists bool
  256. // First check for standard "image" field
  257. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  258. // If not found, check for "image[]" field
  259. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  260. // If still not found, iterate through all fields to find any that start with "image["
  261. foundArrayImages := false
  262. for fieldName, files := range c.Request.MultipartForm.File {
  263. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  264. foundArrayImages = true
  265. for _, file := range files {
  266. imageFiles = append(imageFiles, file)
  267. }
  268. }
  269. }
  270. // If no image fields found at all
  271. if !foundArrayImages && (len(imageFiles) == 0) {
  272. return nil, errors.New("image is required")
  273. }
  274. }
  275. }
  276. // Process all image files
  277. for i, fileHeader := range imageFiles {
  278. file, err := fileHeader.Open()
  279. if err != nil {
  280. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  281. }
  282. defer file.Close()
  283. // If multiple images, use image[] as the field name
  284. fieldName := "image"
  285. if len(imageFiles) > 1 {
  286. fieldName = "image[]"
  287. }
  288. // Determine MIME type based on file extension
  289. mimeType := detectImageMimeType(fileHeader.Filename)
  290. // Create a form file with the appropriate content type
  291. h := make(textproto.MIMEHeader)
  292. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  293. h.Set("Content-Type", mimeType)
  294. part, err := writer.CreatePart(h)
  295. if err != nil {
  296. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  297. }
  298. if _, err := io.Copy(part, file); err != nil {
  299. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  300. }
  301. }
  302. // Handle mask file if present
  303. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  304. maskFile, err := maskFiles[0].Open()
  305. if err != nil {
  306. return nil, errors.New("failed to open mask file")
  307. }
  308. defer maskFile.Close()
  309. // Determine MIME type for mask file
  310. mimeType := detectImageMimeType(maskFiles[0].Filename)
  311. // Create a form file with the appropriate content type
  312. h := make(textproto.MIMEHeader)
  313. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  314. h.Set("Content-Type", mimeType)
  315. maskPart, err := writer.CreatePart(h)
  316. if err != nil {
  317. return nil, errors.New("create form file failed for mask")
  318. }
  319. if _, err := io.Copy(maskPart, maskFile); err != nil {
  320. return nil, errors.New("copy mask file failed")
  321. }
  322. }
  323. } else {
  324. return nil, errors.New("no multipart form data found")
  325. }
  326. // 关闭 multipart 编写器以设置分界线
  327. writer.Close()
  328. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  329. return bytes.NewReader(requestBody.Bytes()), nil
  330. default:
  331. return request, nil
  332. }
  333. }
  334. // detectImageMimeType determines the MIME type based on the file extension
  335. func detectImageMimeType(filename string) string {
  336. ext := strings.ToLower(filepath.Ext(filename))
  337. switch ext {
  338. case ".jpg", ".jpeg":
  339. return "image/jpeg"
  340. case ".png":
  341. return "image/png"
  342. case ".webp":
  343. return "image/webp"
  344. default:
  345. // Try to detect from extension if possible
  346. if strings.HasPrefix(ext, ".jp") {
  347. return "image/jpeg"
  348. }
  349. // Default to png as a fallback
  350. return "image/png"
  351. }
  352. }
  353. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  354. // 模型后缀转换 reasoning effort
  355. if strings.HasSuffix(request.Model, "-high") {
  356. request.Reasoning.Effort = "high"
  357. request.Model = strings.TrimSuffix(request.Model, "-high")
  358. } else if strings.HasSuffix(request.Model, "-low") {
  359. request.Reasoning.Effort = "low"
  360. request.Model = strings.TrimSuffix(request.Model, "-low")
  361. } else if strings.HasSuffix(request.Model, "-medium") {
  362. request.Reasoning.Effort = "medium"
  363. request.Model = strings.TrimSuffix(request.Model, "-medium")
  364. }
  365. return request, nil
  366. }
  367. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  368. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  369. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  370. info.RelayMode == relayconstant.RelayModeImagesEdits {
  371. return channel.DoFormRequest(a, c, info, requestBody)
  372. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  373. return channel.DoWssRequest(a, c, info, requestBody)
  374. } else {
  375. return channel.DoApiRequest(a, c, info, requestBody)
  376. }
  377. }
  378. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  379. switch info.RelayMode {
  380. case relayconstant.RelayModeRealtime:
  381. err, usage = OpenaiRealtimeHandler(c, info)
  382. case relayconstant.RelayModeAudioSpeech:
  383. err, usage = OpenaiTTSHandler(c, resp, info)
  384. case relayconstant.RelayModeAudioTranslation:
  385. fallthrough
  386. case relayconstant.RelayModeAudioTranscription:
  387. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  388. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  389. err, usage = OpenaiHandlerWithUsage(c, resp, info)
  390. case relayconstant.RelayModeRerank:
  391. err, usage = common_handler.RerankHandler(c, info, resp)
  392. case relayconstant.RelayModeResponses:
  393. if info.IsStream {
  394. err, usage = OaiResponsesStreamHandler(c, resp, info)
  395. } else {
  396. err, usage = OaiResponsesHandler(c, resp, info)
  397. }
  398. default:
  399. if info.IsStream {
  400. err, usage = OaiStreamHandler(c, resp, info)
  401. } else {
  402. err, usage = OpenaiHandler(c, resp, info)
  403. }
  404. }
  405. return
  406. }
  407. func (a *Adaptor) GetModelList() []string {
  408. switch a.ChannelType {
  409. case constant.ChannelType360:
  410. return ai360.ModelList
  411. case constant.ChannelTypeMoonshot:
  412. return moonshot.ModelList
  413. case constant.ChannelTypeLingYiWanWu:
  414. return lingyiwanwu.ModelList
  415. case constant.ChannelTypeMiniMax:
  416. return minimax.ModelList
  417. case constant.ChannelTypeXinference:
  418. return xinference.ModelList
  419. case constant.ChannelTypeOpenRouter:
  420. return openrouter.ModelList
  421. default:
  422. return ModelList
  423. }
  424. }
  425. func (a *Adaptor) GetChannelName() string {
  426. switch a.ChannelType {
  427. case constant.ChannelType360:
  428. return ai360.ChannelName
  429. case constant.ChannelTypeMoonshot:
  430. return moonshot.ChannelName
  431. case constant.ChannelTypeLingYiWanWu:
  432. return lingyiwanwu.ChannelName
  433. case constant.ChannelTypeMiniMax:
  434. return minimax.ChannelName
  435. case constant.ChannelTypeXinference:
  436. return xinference.ChannelName
  437. case constant.ChannelTypeOpenRouter:
  438. return openrouter.ChannelName
  439. default:
  440. return ChannelName
  441. }
  442. }