adaptor.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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, header *http.Header, info *relaycommon.RelayInfo) error {
  62. channel.SetupApiRequestHeader(info, c, header)
  63. if info.ChannelType == common.ChannelTypeAzure {
  64. header.Set("api-key", info.ApiKey)
  65. return nil
  66. }
  67. if info.ChannelType == common.ChannelTypeOpenAI && "" != info.Organization {
  68. header.Set("OpenAI-Organization", info.Organization)
  69. }
  70. if info.RelayMode == constant.RelayModeRealtime {
  71. swp := c.Request.Header.Get("Sec-WebSocket-Protocol")
  72. if swp != "" {
  73. items := []string{
  74. "realtime",
  75. "openai-insecure-api-key." + info.ApiKey,
  76. "openai-beta.realtime-v1",
  77. }
  78. header.Set("Sec-WebSocket-Protocol", strings.Join(items, ","))
  79. //req.Header.Set("Sec-WebSocket-Key", c.Request.Header.Get("Sec-WebSocket-Key"))
  80. //req.Header.Set("Sec-Websocket-Extensions", c.Request.Header.Get("Sec-Websocket-Extensions"))
  81. //req.Header.Set("Sec-Websocket-Version", c.Request.Header.Get("Sec-Websocket-Version"))
  82. } else {
  83. header.Set("openai-beta", "realtime=v1")
  84. header.Set("Authorization", "Bearer "+info.ApiKey)
  85. }
  86. } else {
  87. header.Set("Authorization", "Bearer "+info.ApiKey)
  88. }
  89. //if info.ChannelType == common.ChannelTypeOpenRouter {
  90. // req.Header.Set("HTTP-Referer", "https://github.com/songquanpeng/one-api")
  91. // req.Header.Set("X-Title", "One API")
  92. //}
  93. return nil
  94. }
  95. func (a *Adaptor) ConvertRequest(c *gin.Context, info *relaycommon.RelayInfo, request *dto.GeneralOpenAIRequest) (any, error) {
  96. if request == nil {
  97. return nil, errors.New("request is nil")
  98. }
  99. if info.ChannelType != common.ChannelTypeOpenAI {
  100. request.StreamOptions = nil
  101. }
  102. if strings.HasPrefix(request.Model, "o1-") {
  103. if request.MaxCompletionTokens == 0 && request.MaxTokens != 0 {
  104. request.MaxCompletionTokens = request.MaxTokens
  105. request.MaxTokens = 0
  106. }
  107. }
  108. return request, nil
  109. }
  110. func (a *Adaptor) ConvertRerankRequest(c *gin.Context, relayMode int, request dto.RerankRequest) (any, error) {
  111. return nil, errors.New("not implemented")
  112. }
  113. func (a *Adaptor) ConvertAudioRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.AudioRequest) (io.Reader, error) {
  114. a.ResponseFormat = request.ResponseFormat
  115. if info.RelayMode == constant.RelayModeAudioSpeech {
  116. jsonData, err := json.Marshal(request)
  117. if err != nil {
  118. return nil, fmt.Errorf("error marshalling object: %w", err)
  119. }
  120. return bytes.NewReader(jsonData), nil
  121. } else {
  122. var requestBody bytes.Buffer
  123. writer := multipart.NewWriter(&requestBody)
  124. writer.WriteField("model", request.Model)
  125. // 添加文件字段
  126. file, header, err := c.Request.FormFile("file")
  127. if err != nil {
  128. return nil, errors.New("file is required")
  129. }
  130. defer file.Close()
  131. part, err := writer.CreateFormFile("file", header.Filename)
  132. if err != nil {
  133. return nil, errors.New("create form file failed")
  134. }
  135. if _, err := io.Copy(part, file); err != nil {
  136. return nil, errors.New("copy file failed")
  137. }
  138. // 关闭 multipart 编写器以设置分界线
  139. writer.Close()
  140. c.Request.Header.Set("Content-Type", writer.FormDataContentType())
  141. return &requestBody, nil
  142. }
  143. }
  144. func (a *Adaptor) ConvertImageRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.ImageRequest) (any, error) {
  145. return request, nil
  146. }
  147. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
  148. if info.RelayMode == constant.RelayModeAudioTranscription || info.RelayMode == constant.RelayModeAudioTranslation {
  149. return channel.DoFormRequest(a, c, info, requestBody)
  150. } else if info.RelayMode == constant.RelayModeRealtime {
  151. return channel.DoWssRequest(a, c, info, requestBody)
  152. } else {
  153. return channel.DoApiRequest(a, c, info, requestBody)
  154. }
  155. }
  156. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *dto.OpenAIErrorWithStatusCode) {
  157. switch info.RelayMode {
  158. case constant.RelayModeRealtime:
  159. err, usage = OpenaiRealtimeHandler(c, info)
  160. case constant.RelayModeAudioSpeech:
  161. err, usage = OpenaiTTSHandler(c, resp, info)
  162. case constant.RelayModeAudioTranslation:
  163. fallthrough
  164. case constant.RelayModeAudioTranscription:
  165. err, usage = OpenaiSTTHandler(c, resp, info, a.ResponseFormat)
  166. case constant.RelayModeImagesGenerations:
  167. err, usage = OpenaiTTSHandler(c, resp, info)
  168. default:
  169. if info.IsStream {
  170. err, usage = OaiStreamHandler(c, resp, info)
  171. } else {
  172. err, usage = OpenaiHandler(c, resp, info.PromptTokens, info.UpstreamModelName)
  173. }
  174. }
  175. return
  176. }
  177. func (a *Adaptor) GetModelList() []string {
  178. switch a.ChannelType {
  179. case common.ChannelType360:
  180. return ai360.ModelList
  181. case common.ChannelTypeMoonshot:
  182. return moonshot.ModelList
  183. case common.ChannelTypeLingYiWanWu:
  184. return lingyiwanwu.ModelList
  185. case common.ChannelTypeMiniMax:
  186. return minimax.ModelList
  187. default:
  188. return ModelList
  189. }
  190. }
  191. func (a *Adaptor) GetChannelName() string {
  192. switch a.ChannelType {
  193. case common.ChannelType360:
  194. return ai360.ChannelName
  195. case common.ChannelTypeMoonshot:
  196. return moonshot.ChannelName
  197. case common.ChannelTypeLingYiWanWu:
  198. return lingyiwanwu.ChannelName
  199. case common.ChannelTypeMiniMax:
  200. return minimax.ChannelName
  201. default:
  202. return ChannelName
  203. }
  204. }