adaptor.go 8.9 KB

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