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)
  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, "o1") || strings.HasPrefix(request.Model, "o3") {
  142. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  143. request.MaxCompletionTokens = request.MaxTokens
  144. request.MaxTokens = 0
  145. }
  146. if strings.HasPrefix(request.Model, "o3") || strings.HasPrefix(request.Model, "o1") {
  147. request.Temperature = nil
  148. }
  149. if strings.HasSuffix(request.Model, "-high") {
  150. request.ReasoningEffort = "high"
  151. request.Model = strings.TrimSuffix(request.Model, "-high")
  152. } else if strings.HasSuffix(request.Model, "-low") {
  153. request.ReasoningEffort = "low"
  154. request.Model = strings.TrimSuffix(request.Model, "-low")
  155. } else if strings.HasSuffix(request.Model, "-medium") {
  156. request.ReasoningEffort = "medium"
  157. request.Model = strings.TrimSuffix(request.Model, "-medium")
  158. }
  159. info.ReasoningEffort = request.ReasoningEffort
  160. info.UpstreamModelName = request.Model
  161. }
  162. if request.Model == "o1" || request.Model == "o1-2024-12-17" || strings.HasPrefix(request.Model, "o3") {
  163. //修改第一个Message的内容,将system改为developer
  164. if len(request.Messages) > 0 && request.Messages[0].Role == "system" {
  165. request.Messages[0].Role = "developer"
  166. }
  167. }
  168. return request, nil
  169. }
  170. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  171. return request, nil
  172. }
  173. func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.EmbeddingRequest) (any, error) {
  174. return request, nil
  175. }
  176. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  177. a.ResponseFormat = request.ResponseFormat
  178. if info.RelayMode == constant.RelayModeAudioSpeech {
  179. jsonData, err := json.Marshal(request)
  180. if err != nil {
  181. return nil, fmt.Errorf("error marshalling object: %w", err)
  182. }
  183. return bytes.NewReader(jsonData), nil
  184. } else {
  185. var requestBody bytes.Buffer
  186. writer := multipart.NewWriter(&requestBody)
  187. writer.WriteField("model", request.Model)
  188. // 获取所有表单字段
  189. formData := c.Request.PostForm
  190. // 遍历表单字段并打印输出
  191. for key, values := range formData {
  192. if key == "model" {
  193. continue
  194. }
  195. for _, value := range values {
  196. writer.WriteField(key, value)
  197. }
  198. }
  199. // 添加文件字段
  200. file, header, err := c.Request.FormFile("file")
  201. if err != nil {
  202. return nil, errors.New("file is required")
  203. }
  204. defer file.Close()
  205. part, err := writer.CreateFormFile("file", header.Filename)
  206. if err != nil {
  207. return nil, errors.New("create form file failed")
  208. }
  209. if _, err := io.Copy(part, file); err != nil {
  210. return nil, errors.New("copy file failed")
  211. }
  212. // 关闭 multipart 编写器以设置分界线
  213. writer.Close()
  214. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  215. return &requestBody, nil
  216. }
  217. }
  218. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  219. return request, nil
  220. }
  221. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  222. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  223. return channel.DoFormRequest(a, c, info, requestBody)
  224. } else if info.RelayMode == constant.RelayModeRealtime {
  225. return channel.DoWssRequest(a, c, info, requestBody)
  226. } else {
  227. return channel.DoApiRequest(a, c, info, requestBody)
  228. }
  229. }
  230. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  231. switch info.RelayMode {
  232. case constant.RelayModeRealtime:
  233. err, usage = OpenaiRealtimeHandler(c, info)
  234. case constant.RelayModeAudioSpeech:
  235. err, usage = OpenaiTTSHandler(c, resp, info)
  236. case constant.RelayModeAudioTranslation:
  237. fallthrough
  238. case constant.RelayModeAudioTranscription:
  239. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  240. case constant.RelayModeImagesGenerations:
  241. err, usage = OpenaiTTSHandler(c, resp, info)
  242. case constant.RelayModeRerank:
  243. err, usage = common_handler.RerankHandler(c, info, resp)
  244. default:
  245. if info.IsStream {
  246. err, usage = OaiStreamHandler(c, resp, info)
  247. } else {
  248. err, usage = OpenaiHandler(c, resp, info)
  249. }
  250. }
  251. return
  252. }
  253. func (a *Adaptor) GetModelList() []string {
  254. switch a.ChannelType {
  255. case common.ChannelType360:
  256. return ai360.ModelList
  257. case common.ChannelTypeMoonshot:
  258. return moonshot.ModelList
  259. case common.ChannelTypeLingYiWanWu:
  260. return lingyiwanwu.ModelList
  261. case common.ChannelTypeMiniMax:
  262. return minimax.ModelList
  263. case common.ChannelTypeXinference:
  264. return xinference.ModelList
  265. case common.ChannelTypeOpenRouter:
  266. return openrouter.ModelList
  267. default:
  268. return ModelList
  269. }
  270. }
  271. func (a *Adaptor) GetChannelName() string {
  272. switch a.ChannelType {
  273. case common.ChannelType360:
  274. return ai360.ChannelName
  275. case common.ChannelTypeMoonshot:
  276. return moonshot.ChannelName
  277. case common.ChannelTypeLingYiWanWu:
  278. return lingyiwanwu.ChannelName
  279. case common.ChannelTypeMiniMax:
  280. return minimax.ChannelName
  281. case common.ChannelTypeXinference:
  282. return xinference.ChannelName
  283. case common.ChannelTypeOpenRouter:
  284. return openrouter.ChannelName
  285. default:
  286. return ChannelName
  287. }
  288. }