adaptor.go 16 KB

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