adaptor.go 5.6 KB

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