adaptor.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. package openai
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "net/http"
  10. "one-api/common"
  11. constant2 "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. "one-api/relay/constant"
  23. "one-api/service"
  24. "strings"
  25. "github.com/gin-gonic/gin"
  26. )
  27. type Adaptor struct {
  28. ChannelType int
  29. ResponseFormat string
  30. }
  31. func (a *Adaptor) ConvertClaudeRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.ClaudeRequest) (any, error) {
  32. if !strings.Contains(request.Model, "claude") {
  33. return nil, fmt.Errorf("you are using openai channel type with path /v1/messages, only claude model supported convert, but got %s", request.Model)
  34. }
  35. aiRequest, err := service.ClaudeToOpenAIRequest(*request, info)
  36. if err != nil {
  37. return nil, err
  38. }
  39. if info.SupportStreamOptions {
  40. aiRequest.StreamOptions = &dto.StreamOptions{
  41. IncludeUsage: true,
  42. }
  43. }
  44. return a.ConvertOpenAIRequest(c, info, aiRequest)
  45. }
  46. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  47. a.ChannelType = info.ChannelType
  48. // initialize ThinkingContentInfo when thinking_to_content is enabled
  49. if think2Content, ok := info.ChannelSetting[constant2.ChannelSettingThinkingToContent].(bool); ok && think2Content {
  50. info.ThinkingContentInfo = relaycommon.ThinkingContentInfo{
  51. IsFirstThinkingContent: true,
  52. SendLastThinkingContent: false,
  53. HasSentThinkingContent: false,
  54. }
  55. }
  56. }
  57. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  58. if info.RelayFormat == relaycommon.RelayFormatClaude {
  59. return fmt.Sprintf("%s/v1/chat/completions", info.BaseUrl), nil
  60. }
  61. if info.RelayMode == constant.RelayModeRealtime {
  62. if strings.HasPrefix(info.BaseUrl, "https://") {
  63. baseUrl := strings.TrimPrefix(info.BaseUrl, "https://")
  64. baseUrl = "wss://" + baseUrl
  65. info.BaseUrl = baseUrl
  66. } else if strings.HasPrefix(info.BaseUrl, "http://") {
  67. baseUrl := strings.TrimPrefix(info.BaseUrl, "http://")
  68. baseUrl = "ws://" + baseUrl
  69. info.BaseUrl = baseUrl
  70. }
  71. }
  72. switch info.ChannelType {
  73. case common.ChannelTypeAzure:
  74. apiVersion := info.ApiVersion
  75. if apiVersion == "" {
  76. apiVersion = constant2.AzureDefaultAPIVersion
  77. }
  78. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  79. requestURL := strings.Split(info.RequestURLPath, "?")[0]
  80. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, apiVersion)
  81. task := strings.TrimPrefix(requestURL, "/v1/")
  82. model_ := info.UpstreamModelName
  83. model_ = strings.Replace(model_, ".", "", -1)
  84. // https://github.com/songquanpeng/one-api/issues/67
  85. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  86. if info.RelayMode == constant.RelayModeRealtime {
  87. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, apiVersion)
  88. }
  89. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  90. case common.ChannelTypeMiniMax:
  91. return minimax.GetRequestURL(info)
  92. case common.ChannelTypeCustom:
  93. url := info.BaseUrl
  94. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  95. return url, nil
  96. default:
  97. return relaycommon.GetFullRequestURL(info.BaseUrl, info.RequestURLPath, info.ChannelType), nil
  98. }
  99. }
  100. func (a *Adaptor) SetupRequestHeader(c *gin.Context, header *http.Header, info *relaycommon.RelayInfo) error {
  101. channel.SetupApiRequestHeader(info, c, header)
  102. if info.ChannelType == common.ChannelTypeAzure {
  103. header.Set("api-key", info.ApiKey)
  104. return nil
  105. }
  106. if info.ChannelType == common.ChannelTypeOpenAI && "" != info.Organization {
  107. header.Set("OpenAI-Organization", info.Organization)
  108. }
  109. if info.RelayMode == constant.RelayModeRealtime {
  110. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  111. if swp != "" {
  112. items := []string{
  113. "realtime",
  114. "openai-insecure-api-key." + info.ApiKey,
  115. "openai-beta.realtime-v1",
  116. }
  117. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  118. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  119. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  120. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  121. } else {
  122. header.Set("openai-beta", "realtime=v1")
  123. header.Set("Authorization", "Bearer "+info.ApiKey)
  124. }
  125. } else {
  126. header.Set("Authorization", "Bearer "+info.ApiKey)
  127. }
  128. if info.ChannelType == common.ChannelTypeOpenRouter {
  129. header.Set("HTTP-Referer", "https://github.com/Calcium-Ion/new-api")
  130. header.Set("X-Title", "New API")
  131. }
  132. return nil
  133. }
  134. func (a *Adaptor) ConvertOpenAIRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  135. if request == nil {
  136. return nil, errors.New("request is nil")
  137. }
  138. if info.ChannelType != common.ChannelTypeOpenAI && info.ChannelType != common.ChannelTypeAzure {
  139. request.StreamOptions = nil
  140. }
  141. if strings.HasPrefix(request.Model, "o") {
  142. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  143. request.MaxCompletionTokens = request.MaxTokens
  144. request.MaxTokens = 0
  145. }
  146. request.Temperature = nil
  147. if strings.HasSuffix(request.Model, "-high") {
  148. request.ReasoningEffort = "high"
  149. request.Model = strings.TrimSuffix(request.Model, "-high")
  150. } else if strings.HasSuffix(request.Model, "-low") {
  151. request.ReasoningEffort = "low"
  152. request.Model = strings.TrimSuffix(request.Model, "-low")
  153. } else if strings.HasSuffix(request.Model, "-medium") {
  154. request.ReasoningEffort = "medium"
  155. request.Model = strings.TrimSuffix(request.Model, "-medium")
  156. }
  157. info.ReasoningEffort = request.ReasoningEffort
  158. info.UpstreamModelName = request.Model
  159. // o系列模型developer适配(o1-mini除外)
  160. if !strings.HasPrefix(request.Model, "o1-mini") {
  161. //修改第一个Message的内容,将system改为developer
  162. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  163. request.Messages[0].Role = "developer"
  164. }
  165. }
  166. }
  167. return request, nil
  168. }
  169. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  170. return request, nil
  171. }
  172. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  173. return request, nil
  174. }
  175. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  176. a.ResponseFormat = request.ResponseFormat
  177. if info.RelayMode == constant.RelayModeAudioSpeech {
  178. jsonData, err := json.Marshal(request)
  179. if err != nil {
  180. return nil, fmt.Errorf("error marshalling object: %w", err)
  181. }
  182. return bytes.NewReader(jsonData), nil
  183. } else {
  184. var requestBody bytes.Buffer
  185. writer := multipart.NewWriter(&requestBody)
  186. writer.WriteField("model", request.Model)
  187. // 获取所有表单字段
  188. formData := c.Request.PostForm
  189. // 遍历表单字段并打印输出
  190. for key, values := range formData {
  191. if key == "model" {
  192. continue
  193. }
  194. for _, value := range values {
  195. writer.WriteField(key, value)
  196. }
  197. }
  198. // 添加文件字段
  199. file, header, err := c.Request.FormFile("file")
  200. if err != nil {
  201. return nil, errors.New("file is required")
  202. }
  203. defer file.Close()
  204. part, err := writer.CreateFormFile("file", header.Filename)
  205. if err != nil {
  206. return nil, errors.New("create form file failed")
  207. }
  208. if _, err := io.Copy(part, file); err != nil {
  209. return nil, errors.New("copy file failed")
  210. }
  211. // 关闭 multipart 编写器以设置分界线
  212. writer.Close()
  213. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  214. return &requestBody, nil
  215. }
  216. }
  217. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  218. return request, nil
  219. }
  220. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  221. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  222. return channel.DoFormRequest(a, c, info, requestBody)
  223. } else if info.RelayMode == constant.RelayModeRealtime {
  224. return channel.DoWssRequest(a, c, info, requestBody)
  225. } else {
  226. return channel.DoApiRequest(a, c, info, requestBody)
  227. }
  228. }
  229. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  230. switch info.RelayMode {
  231. case constant.RelayModeRealtime:
  232. err, usage = OpenaiRealtimeHandler(c, info)
  233. case constant.RelayModeAudioSpeech:
  234. err, usage = OpenaiTTSHandler(c, resp, info)
  235. case constant.RelayModeAudioTranslation:
  236. fallthrough
  237. case constant.RelayModeAudioTranscription:
  238. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  239. case constant.RelayModeImagesGenerations:
  240. err, usage = OpenaiTTSHandler(c, resp, info)
  241. case constant.RelayModeRerank:
  242. err, usage = common_handler.RerankHandler(c, info, resp)
  243. default:
  244. if info.IsStream {
  245. err, usage = OaiStreamHandler(c, resp, info)
  246. } else {
  247. err, usage = OpenaiHandler(c, resp, info)
  248. }
  249. }
  250. return
  251. }
  252. func (a *Adaptor) GetModelList() []string {
  253. switch a.ChannelType {
  254. case common.ChannelType360:
  255. return ai360.ModelList
  256. case common.ChannelTypeMoonshot:
  257. return moonshot.ModelList
  258. case common.ChannelTypeLingYiWanWu:
  259. return lingyiwanwu.ModelList
  260. case common.ChannelTypeMiniMax:
  261. return minimax.ModelList
  262. case common.ChannelTypeXinference:
  263. return xinference.ModelList
  264. case common.ChannelTypeOpenRouter:
  265. return openrouter.ModelList
  266. default:
  267. return ModelList
  268. }
  269. }
  270. func (a *Adaptor) GetChannelName() string {
  271. switch a.ChannelType {
  272. case common.ChannelType360:
  273. return ai360.ChannelName
  274. case common.ChannelTypeMoonshot:
  275. return moonshot.ChannelName
  276. case common.ChannelTypeLingYiWanWu:
  277. return lingyiwanwu.ChannelName
  278. case common.ChannelTypeMiniMax:
  279. return minimax.ChannelName
  280. case common.ChannelTypeXinference:
  281. return xinference.ChannelName
  282. case common.ChannelTypeOpenRouter:
  283. return openrouter.ChannelName
  284. default:
  285. return ChannelName
  286. }
  287. }