adaptor.go 16 KB

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