adaptor.go 8.7 KB

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