adaptor.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. "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. 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 info.ChannelSetting.ThinkingToContent {
  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 == relayconstant.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 constant.ChannelTypeAzure:
  76. apiVersion := info.ApiVersion
  77. if apiVersion == "" {
  78. apiVersion = constant.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 == relayconstant.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 < constant.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 == relayconstant.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 constant.ChannelTypeMiniMax:
  101. return minimax.GetRequestURL(info)
  102. case constant.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 == constant.ChannelTypeAzure {
  113. header.Set("api-key", info.ApiKey)
  114. return nil
  115. }
  116. if info.ChannelType == constant.ChannelTypeOpenAI && "" != info.Organization {
  117. header.Set("OpenAI-Organization", info.Organization)
  118. }
  119. if info.RelayMode == relayconstant.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 == constant.ChannelTypeOpenRouter {
  139. header.Set("HTTP-Referer", "https://www.newapi.ai")
  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 != constant.ChannelTypeOpenAI && info.ChannelType != constant.ChannelTypeAzure {
  149. request.StreamOptions = nil
  150. }
  151. if info.ChannelType == constant.ChannelTypeOpenRouter {
  152. if len(request.Usage) == 0 {
  153. request.Usage = json.RawMessage(`{"include":true}`)
  154. }
  155. }
  156. if strings.HasPrefix(request.Model, "o") {
  157. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  158. request.MaxCompletionTokens = request.MaxTokens
  159. request.MaxTokens = 0
  160. }
  161. request.Temperature = nil
  162. if strings.HasSuffix(request.Model, "-high") {
  163. request.ReasoningEffort = "high"
  164. request.Model = strings.TrimSuffix(request.Model, "-high")
  165. } else if strings.HasSuffix(request.Model, "-low") {
  166. request.ReasoningEffort = "low"
  167. request.Model = strings.TrimSuffix(request.Model, "-low")
  168. } else if strings.HasSuffix(request.Model, "-medium") {
  169. request.ReasoningEffort = "medium"
  170. request.Model = strings.TrimSuffix(request.Model, "-medium")
  171. }
  172. info.ReasoningEffort = request.ReasoningEffort
  173. info.UpstreamModelName = request.Model
  174. // o系列模型developer适配(o1-mini除外)
  175. if !strings.HasPrefix(request.Model, "o1-mini") && !strings.HasPrefix(request.Model, "o1-preview") {
  176. //修改第一个Message的内容,将system改为developer
  177. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  178. request.Messages[0].Role = "developer"
  179. }
  180. }
  181. }
  182. return request, nil
  183. }
  184. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  185. return request, nil
  186. }
  187. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  188. return request, nil
  189. }
  190. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  191. a.ResponseFormat = request.ResponseFormat
  192. if info.RelayMode == relayconstant.RelayModeAudioSpeech {
  193. jsonData, err := json.Marshal(request)
  194. if err != nil {
  195. return nil, fmt.Errorf("error marshalling object: %w", err)
  196. }
  197. return bytes.NewReader(jsonData), nil
  198. } else {
  199. var requestBody bytes.Buffer
  200. writer := multipart.NewWriter(&requestBody)
  201. writer.WriteField("model", request.Model)
  202. // 获取所有表单字段
  203. formData := c.Request.PostForm
  204. // 遍历表单字段并打印输出
  205. for key, values := range formData {
  206. if key == "model" {
  207. continue
  208. }
  209. for _, value := range values {
  210. writer.WriteField(key, value)
  211. }
  212. }
  213. // 添加文件字段
  214. file, header, err := c.Request.FormFile("file")
  215. if err != nil {
  216. return nil, errors.New("file is required")
  217. }
  218. defer file.Close()
  219. part, err := writer.CreateFormFile("file", header.Filename)
  220. if err != nil {
  221. return nil, errors.New("create form file failed")
  222. }
  223. if _, err := io.Copy(part, file); err != nil {
  224. return nil, errors.New("copy file failed")
  225. }
  226. // 关闭 multipart 编写器以设置分界线
  227. writer.Close()
  228. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  229. return &requestBody, nil
  230. }
  231. }
  232. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  233. switch info.RelayMode {
  234. case relayconstant.RelayModeImagesEdits:
  235. var requestBody bytes.Buffer
  236. writer := multipart.NewWriter(&requestBody)
  237. writer.WriteField("model", request.Model)
  238. // 获取所有表单字段
  239. formData := c.Request.PostForm
  240. // 遍历表单字段并打印输出
  241. for key, values := range formData {
  242. if key == "model" {
  243. continue
  244. }
  245. for _, value := range values {
  246. writer.WriteField(key, value)
  247. }
  248. }
  249. // Parse the multipart form to handle both single image and multiple images
  250. if err := c.Request.ParseMultipartForm(32 << 20); err != nil { // 32MB max memory
  251. return nil, errors.New("failed to parse multipart form")
  252. }
  253. if c.Request.MultipartForm != nil && c.Request.MultipartForm.File != nil {
  254. // Check if "image" field exists in any form, including array notation
  255. var imageFiles []*multipart.FileHeader
  256. var exists bool
  257. // First check for standard "image" field
  258. if imageFiles, exists = c.Request.MultipartForm.File["image"]; !exists || len(imageFiles) == 0 {
  259. // If not found, check for "image[]" field
  260. if imageFiles, exists = c.Request.MultipartForm.File["image[]"]; !exists || len(imageFiles) == 0 {
  261. // If still not found, iterate through all fields to find any that start with "image["
  262. foundArrayImages := false
  263. for fieldName, files := range c.Request.MultipartForm.File {
  264. if strings.HasPrefix(fieldName, "image[") && len(files) > 0 {
  265. foundArrayImages = true
  266. for _, file := range files {
  267. imageFiles = append(imageFiles, file)
  268. }
  269. }
  270. }
  271. // If no image fields found at all
  272. if !foundArrayImages && (len(imageFiles) == 0) {
  273. return nil, errors.New("image is required")
  274. }
  275. }
  276. }
  277. // Process all image files
  278. for i, fileHeader := range imageFiles {
  279. file, err := fileHeader.Open()
  280. if err != nil {
  281. return nil, fmt.Errorf("failed to open image file %d: %w", i, err)
  282. }
  283. defer file.Close()
  284. // If multiple images, use image[] as the field name
  285. fieldName := "image"
  286. if len(imageFiles) > 1 {
  287. fieldName = "image[]"
  288. }
  289. // Determine MIME type based on file extension
  290. mimeType := detectImageMimeType(fileHeader.Filename)
  291. // Create a form file with the appropriate content type
  292. h := make(textproto.MIMEHeader)
  293. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileHeader.Filename))
  294. h.Set("Content-Type", mimeType)
  295. part, err := writer.CreatePart(h)
  296. if err != nil {
  297. return nil, fmt.Errorf("create form part failed for image %d: %w", i, err)
  298. }
  299. if _, err := io.Copy(part, file); err != nil {
  300. return nil, fmt.Errorf("copy file failed for image %d: %w", i, err)
  301. }
  302. }
  303. // Handle mask file if present
  304. if maskFiles, exists := c.Request.MultipartForm.File["mask"]; exists && len(maskFiles) > 0 {
  305. maskFile, err := maskFiles[0].Open()
  306. if err != nil {
  307. return nil, errors.New("failed to open mask file")
  308. }
  309. defer maskFile.Close()
  310. // Determine MIME type for mask file
  311. mimeType := detectImageMimeType(maskFiles[0].Filename)
  312. // Create a form file with the appropriate content type
  313. h := make(textproto.MIMEHeader)
  314. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="mask"; filename="%s"`, maskFiles[0].Filename))
  315. h.Set("Content-Type", mimeType)
  316. maskPart, err := writer.CreatePart(h)
  317. if err != nil {
  318. return nil, errors.New("create form file failed for mask")
  319. }
  320. if _, err := io.Copy(maskPart, maskFile); err != nil {
  321. return nil, errors.New("copy mask file failed")
  322. }
  323. }
  324. } else {
  325. return nil, errors.New("no multipart form data found")
  326. }
  327. // 关闭 multipart 编写器以设置分界线
  328. writer.Close()
  329. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  330. return bytes.NewReader(requestBody.Bytes()), nil
  331. default:
  332. return request, nil
  333. }
  334. }
  335. // detectImageMimeType determines the MIME type based on the file extension
  336. func detectImageMimeType(filename string) string {
  337. ext := strings.ToLower(filepath.Ext(filename))
  338. switch ext {
  339. case ".jpg", ".jpeg":
  340. return "image/jpeg"
  341. case ".png":
  342. return "image/png"
  343. case ".webp":
  344. return "image/webp"
  345. default:
  346. // Try to detect from extension if possible
  347. if strings.HasPrefix(ext, ".jp") {
  348. return "image/jpeg"
  349. }
  350. // Default to png as a fallback
  351. return "image/png"
  352. }
  353. }
  354. func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
  355. // 模型后缀转换 reasoning effort
  356. if strings.HasSuffix(request.Model, "-high") {
  357. request.Reasoning.Effort = "high"
  358. request.Model = strings.TrimSuffix(request.Model, "-high")
  359. } else if strings.HasSuffix(request.Model, "-low") {
  360. request.Reasoning.Effort = "low"
  361. request.Model = strings.TrimSuffix(request.Model, "-low")
  362. } else if strings.HasSuffix(request.Model, "-medium") {
  363. request.Reasoning.Effort = "medium"
  364. request.Model = strings.TrimSuffix(request.Model, "-medium")
  365. }
  366. return request, nil
  367. }
  368. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  369. if info.RelayMode == relayconstant.RelayModeAudioTranscription ||
  370. info.RelayMode == relayconstant.RelayModeAudioTranslation ||
  371. info.RelayMode == relayconstant.RelayModeImagesEdits {
  372. return channel.DoFormRequest(a, c, info, requestBody)
  373. } else if info.RelayMode == relayconstant.RelayModeRealtime {
  374. return channel.DoWssRequest(a, c, info, requestBody)
  375. } else {
  376. return channel.DoApiRequest(a, c, info, requestBody)
  377. }
  378. }
  379. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
  380. switch info.RelayMode {
  381. case relayconstant.RelayModeRealtime:
  382. err, usage = OpenaiRealtimeHandler(c, info)
  383. case relayconstant.RelayModeAudioSpeech:
  384. usage = OpenaiTTSHandler(c, resp, info)
  385. case relayconstant.RelayModeAudioTranslation:
  386. fallthrough
  387. case relayconstant.RelayModeAudioTranscription:
  388. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  389. case relayconstant.RelayModeImagesGenerations, relayconstant.RelayModeImagesEdits:
  390. usage, err = OpenaiHandlerWithUsage(c, info, resp)
  391. case relayconstant.RelayModeRerank:
  392. usage, err = common_handler.RerankHandler(c, info, resp)
  393. case relayconstant.RelayModeResponses:
  394. if info.IsStream {
  395. usage, err = OaiResponsesStreamHandler(c, info, resp)
  396. } else {
  397. usage, err = OaiResponsesHandler(c, info, resp)
  398. }
  399. default:
  400. if info.IsStream {
  401. usage, err = OaiStreamHandler(c, info, resp)
  402. } else {
  403. usage, err = OpenaiHandler(c, info, resp)
  404. }
  405. }
  406. return
  407. }
  408. func (a *Adaptor) GetModelList() []string {
  409. switch a.ChannelType {
  410. case constant.ChannelType360:
  411. return ai360.ModelList
  412. case constant.ChannelTypeMoonshot:
  413. return moonshot.ModelList
  414. case constant.ChannelTypeLingYiWanWu:
  415. return lingyiwanwu.ModelList
  416. case constant.ChannelTypeMiniMax:
  417. return minimax.ModelList
  418. case constant.ChannelTypeXinference:
  419. return xinference.ModelList
  420. case constant.ChannelTypeOpenRouter:
  421. return openrouter.ModelList
  422. default:
  423. return ModelList
  424. }
  425. }
  426. func (a *Adaptor) GetChannelName() string {
  427. switch a.ChannelType {
  428. case constant.ChannelType360:
  429. return ai360.ChannelName
  430. case constant.ChannelTypeMoonshot:
  431. return moonshot.ChannelName
  432. case constant.ChannelTypeLingYiWanWu:
  433. return lingyiwanwu.ChannelName
  434. case constant.ChannelTypeMiniMax:
  435. return minimax.ChannelName
  436. case constant.ChannelTypeXinference:
  437. return xinference.ChannelName
  438. case constant.ChannelTypeOpenRouter:
  439. return openrouter.ChannelName
  440. default:
  441. return ChannelName
  442. }
  443. }