adaptor.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "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. relaycommon "one-api/relay/common"
  19. "one-api/relay/constant"
  20. "strings"
  21. )
  22. type Adaptor struct {
  23. ChannelType int
  24. ResponseFormat string
  25. }
  26. func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
  27. a.ChannelType = info.ChannelType
  28. }
  29. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  30. if info.RelayMode == constant.RelayModeRealtime {
  31. // trim https
  32. baseUrl := strings.TrimPrefix(info.BaseUrl, "https://")
  33. baseUrl = strings.TrimPrefix(baseUrl, "http://")
  34. baseUrl = "wss://" + baseUrl
  35. info.BaseUrl = baseUrl
  36. }
  37. switch info.ChannelType {
  38. case common.ChannelTypeAzure:
  39. // https://learn.microsoft.com/en-us/azure/cognitive-services/openai/chatgpt-quickstart?pivots=rest-api&tabs=command-line#rest-api
  40. requestURL := strings.Split(info.RequestURLPath, "?")[0]
  41. requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, info.ApiVersion)
  42. task := strings.TrimPrefix(requestURL, "/v1/")
  43. model_ := info.UpstreamModelName
  44. model_ = strings.Replace(model_, ".", "", -1)
  45. // https://github.com/songquanpeng/one-api/issues/67
  46. requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)
  47. if info.RelayMode == constant.RelayModeRealtime {
  48. requestURL = fmt.Sprintf("/openai/realtime?deployment=%s&api-version=%s", model_, info.ApiVersion)
  49. }
  50. return relaycommon.GetFullRequestURL(info.BaseUrl, requestURL, info.ChannelType), nil
  51. case common.ChannelTypeMiniMax:
  52. return minimax.GetRequestURL(info)
  53. case common.ChannelTypeCustom:
  54. url := info.BaseUrl
  55. url = strings.Replace(url, "{model}", info.UpstreamModelName, -1)
  56. return url, nil
  57. default:
  58. return relaycommon.GetFullRequestURL(info.BaseUrl, info.RequestURLPath, info.ChannelType), nil
  59. }
  60. }
  61. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Header, info *relaycommon.RelayInfo) error {
  62. channel.SetupApiRequestHeader(info, c, req)
  63. if info.ChannelType == common.ChannelTypeAzure {
  64. req.Set("api-key", info.ApiKey)
  65. return nil
  66. }
  67. if info.ChannelType == common.ChannelTypeOpenAI && "" != info.Organization {
  68. req.Set("OpenAI-Organization", info.Organization)
  69. }
  70. req.Set("Authorization", "Bearer "+info.ApiKey)
  71. if info.RelayMode == constant.RelayModeRealtime {
  72. req.Set("openai-beta", "realtime=v1")
  73. }
  74. //if info.ChannelType == common.ChannelTypeOpenRouter {
  75. // req.Header.Set("HTTP-Referer", "https://github.com/songquanpeng/one-api")
  76. // req.Header.Set("X-Title", "One API")
  77. //}
  78. return nil
  79. }
  80. func (a *Adaptor) ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  81. if request == nil {
  82. return nil, errors.New("request is nil")
  83. }
  84. if info.ChannelType != common.ChannelTypeOpenAI {
  85. request.StreamOptions = nil
  86. }
  87. if strings.HasPrefix(request.Model, "o1-") {
  88. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  89. request.MaxCompletionTokens = request.MaxTokens
  90. request.MaxTokens = 0
  91. }
  92. }
  93. return request, nil
  94. }
  95. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  96. return nil, errors.New("not implemented")
  97. }
  98. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  99. a.ResponseFormat = request.ResponseFormat
  100. if info.RelayMode == constant.RelayModeAudioSpeech {
  101. jsonData, err := json.Marshal(request)
  102. if err != nil {
  103. return nil, fmt.Errorf("error marshalling object: %w", err)
  104. }
  105. return bytes.NewReader(jsonData), nil
  106. } else {
  107. var requestBody bytes.Buffer
  108. writer := multipart.NewWriter(&requestBody)
  109. writer.WriteField("model", request.Model)
  110. // 添加文件字段
  111. file, header, err := c.Request.FormFile("file")
  112. if err != nil {
  113. return nil, errors.New("file is required")
  114. }
  115. defer file.Close()
  116. part, err := writer.CreateFormFile("file", header.Filename)
  117. if err != nil {
  118. return nil, errors.New("create form file failed")
  119. }
  120. if _, err := io.Copy(part, file); err != nil {
  121. return nil, errors.New("copy file failed")
  122. }
  123. // 关闭 multipart 编写器以设置分界线
  124. writer.Close()
  125. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  126. return &requestBody, nil
  127. }
  128. }
  129. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  130. return request, nil
  131. }
  132. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  133. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  134. return channel.DoFormRequest(a, c, info, requestBody)
  135. } else if info.RelayMode == constant.RelayModeRealtime {
  136. return channel.DoWssRequest(a, c, info, requestBody)
  137. } else {
  138. return channel.DoApiRequest(a, c, info, requestBody)
  139. }
  140. }
  141. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  142. switch info.RelayMode {
  143. case constant.RelayModeRealtime:
  144. err, usage = OpenaiRealtimeHandler(c, info)
  145. case constant.RelayModeAudioSpeech:
  146. err, usage = OpenaiTTSHandler(c, resp, info)
  147. case constant.RelayModeAudioTranslation:
  148. fallthrough
  149. case constant.RelayModeAudioTranscription:
  150. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  151. case constant.RelayModeImagesGenerations:
  152. err, usage = OpenaiTTSHandler(c, resp, info)
  153. default:
  154. if info.IsStream {
  155. err, usage = OaiStreamHandler(c, resp, info)
  156. } else {
  157. err, usage = OpenaiHandler(c, resp, info.PromptTokens, info.UpstreamModelName)
  158. }
  159. }
  160. return
  161. }
  162. func (a *Adaptor) GetModelList() []string {
  163. switch a.ChannelType {
  164. case common.ChannelType360:
  165. return ai360.ModelList
  166. case common.ChannelTypeMoonshot:
  167. return moonshot.ModelList
  168. case common.ChannelTypeLingYiWanWu:
  169. return lingyiwanwu.ModelList
  170. case common.ChannelTypeMiniMax:
  171. return minimax.ModelList
  172. default:
  173. return ModelList
  174. }
  175. }
  176. func (a *Adaptor) GetChannelName() string {
  177. switch a.ChannelType {
  178. case common.ChannelType360:
  179. return ai360.ChannelName
  180. case common.ChannelTypeMoonshot:
  181. return moonshot.ChannelName
  182. case common.ChannelTypeLingYiWanWu:
  183. return lingyiwanwu.ChannelName
  184. case common.ChannelTypeMiniMax:
  185. return minimax.ChannelName
  186. default:
  187. return ChannelName
  188. }
  189. }