compatible_handler.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. package relay
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "one-api/common"
  8. "one-api/constant"
  9. "one-api/dto"
  10. "one-api/logger"
  11. "one-api/model"
  12. relaycommon "one-api/relay/common"
  13. "one-api/relay/helper"
  14. "one-api/service"
  15. "one-api/setting/model_setting"
  16. "one-api/setting/operation_setting"
  17. "one-api/types"
  18. "strings"
  19. "time"
  20. "github.com/shopspring/decimal"
  21. "github.com/gin-gonic/gin"
  22. )
  23. func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types.NewAPIError) {
  24. info.InitChannelMeta(c)
  25. textReq, ok := info.Request.(*dto.GeneralOpenAIRequest)
  26. if !ok {
  27. return types.NewErrorWithStatusCode(fmt.Errorf("invalid request type, expected dto.GeneralOpenAIRequest, got %T", info.Request), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  28. }
  29. request, err := common.DeepCopy(textReq)
  30. if err != nil {
  31. return types.NewError(fmt.Errorf("failed to copy request to GeneralOpenAIRequest: %w", err), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
  32. }
  33. if request.WebSearchOptions != nil {
  34. c.Set("chat_completion_web_search_context_size", request.WebSearchOptions.SearchContextSize)
  35. }
  36. err = helper.ModelMappedHelper(c, info, request)
  37. if err != nil {
  38. return types.NewError(err, types.ErrorCodeChannelModelMappedError, types.ErrOptionWithSkipRetry())
  39. }
  40. includeUsage := true
  41. // 判断用户是否需要返回使用情况
  42. if request.StreamOptions != nil {
  43. includeUsage = request.StreamOptions.IncludeUsage
  44. }
  45. // 如果不支持StreamOptions,将StreamOptions设置为nil
  46. if !info.SupportStreamOptions || !request.Stream {
  47. request.StreamOptions = nil
  48. } else {
  49. // 如果支持StreamOptions,且请求中没有设置StreamOptions,根据配置文件设置StreamOptions
  50. if constant.ForceStreamOption {
  51. request.StreamOptions = &dto.StreamOptions{
  52. IncludeUsage: true,
  53. }
  54. }
  55. }
  56. info.ShouldIncludeUsage = includeUsage
  57. adaptor := GetAdaptor(info.ApiType)
  58. if adaptor == nil {
  59. return types.NewError(fmt.Errorf("invalid api type: %d", info.ApiType), types.ErrorCodeInvalidApiType, types.ErrOptionWithSkipRetry())
  60. }
  61. adaptor.Init(info)
  62. var requestBody io.Reader
  63. if model_setting.GetGlobalSettings().PassThroughRequestEnabled || info.ChannelSetting.PassThroughBodyEnabled {
  64. body, err := common.GetRequestBody(c)
  65. if err != nil {
  66. return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  67. }
  68. if common.DebugEnabled {
  69. println("requestBody: ", string(body))
  70. }
  71. requestBody = bytes.NewBuffer(body)
  72. } else {
  73. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
  74. if err != nil {
  75. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  76. }
  77. if info.ChannelSetting.SystemPrompt != "" {
  78. // 如果有系统提示,则将其添加到请求中
  79. request := convertedRequest.(*dto.GeneralOpenAIRequest)
  80. containSystemPrompt := false
  81. for _, message := range request.Messages {
  82. if message.Role == request.GetSystemRoleName() {
  83. containSystemPrompt = true
  84. break
  85. }
  86. }
  87. if !containSystemPrompt {
  88. // 如果没有系统提示,则添加系统提示
  89. systemMessage := dto.Message{
  90. Role: request.GetSystemRoleName(),
  91. Content: info.ChannelSetting.SystemPrompt,
  92. }
  93. request.Messages = append([]dto.Message{systemMessage}, request.Messages...)
  94. } else if info.ChannelSetting.SystemPromptOverride {
  95. common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true)
  96. // 如果有系统提示,且允许覆盖,则拼接到前面
  97. for i, message := range request.Messages {
  98. if message.Role == request.GetSystemRoleName() {
  99. if message.IsStringContent() {
  100. request.Messages[i].SetStringContent(info.ChannelSetting.SystemPrompt + "\n" + message.StringContent())
  101. } else {
  102. contents := message.ParseContent()
  103. contents = append([]dto.MediaContent{
  104. {
  105. Type: dto.ContentTypeText,
  106. Text: info.ChannelSetting.SystemPrompt,
  107. },
  108. }, contents...)
  109. request.Messages[i].Content = contents
  110. }
  111. break
  112. }
  113. }
  114. }
  115. }
  116. jsonData, err := common.Marshal(convertedRequest)
  117. if err != nil {
  118. return types.NewError(err, types.ErrorCodeJsonMarshalFailed, types.ErrOptionWithSkipRetry())
  119. }
  120. // apply param override
  121. if len(info.ParamOverride) > 0 {
  122. jsonData, err = relaycommon.ApplyParamOverride(jsonData, info.ParamOverride)
  123. if err != nil {
  124. return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid, types.ErrOptionWithSkipRetry())
  125. }
  126. }
  127. logger.LogDebug(c, fmt.Sprintf("text request body: %s", string(jsonData)))
  128. requestBody = bytes.NewBuffer(jsonData)
  129. }
  130. var httpResp *http.Response
  131. resp, err := adaptor.DoRequest(c, info, requestBody)
  132. if err != nil {
  133. return types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError)
  134. }
  135. statusCodeMappingStr := c.GetString("status_code_mapping")
  136. if resp != nil {
  137. httpResp = resp.(*http.Response)
  138. info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  139. if httpResp.StatusCode != http.StatusOK {
  140. newApiErr := service.RelayErrorHandler(c.Request.Context(), httpResp, false)
  141. // reset status code 重置状态码
  142. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  143. return newApiErr
  144. }
  145. }
  146. usage, newApiErr := adaptor.DoResponse(c, httpResp, info)
  147. if newApiErr != nil {
  148. // reset status code 重置状态码
  149. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  150. return newApiErr
  151. }
  152. if strings.HasPrefix(info.OriginModelName, "gpt-4o-audio") {
  153. service.PostAudioConsumeQuota(c, info, usage.(*dto.Usage), "")
  154. } else {
  155. postConsumeQuota(c, info, usage.(*dto.Usage), "")
  156. }
  157. return nil
  158. }
  159. func postConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, extraContent string) {
  160. if usage == nil {
  161. usage = &dto.Usage{
  162. PromptTokens: relayInfo.PromptTokens,
  163. CompletionTokens: 0,
  164. TotalTokens: relayInfo.PromptTokens,
  165. }
  166. extraContent += "(可能是请求出错)"
  167. }
  168. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  169. promptTokens := usage.PromptTokens
  170. cacheTokens := usage.PromptTokensDetails.CachedTokens
  171. imageTokens := usage.PromptTokensDetails.ImageTokens
  172. audioTokens := usage.PromptTokensDetails.AudioTokens
  173. completionTokens := usage.CompletionTokens
  174. cachedCreationTokens := usage.PromptTokensDetails.CachedCreationTokens
  175. modelName := relayInfo.OriginModelName
  176. tokenName := ctx.GetString("token_name")
  177. completionRatio := relayInfo.PriceData.CompletionRatio
  178. cacheRatio := relayInfo.PriceData.CacheRatio
  179. imageRatio := relayInfo.PriceData.ImageRatio
  180. modelRatio := relayInfo.PriceData.ModelRatio
  181. groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
  182. modelPrice := relayInfo.PriceData.ModelPrice
  183. cachedCreationRatio := relayInfo.PriceData.CacheCreationRatio
  184. // Convert values to decimal for precise calculation
  185. dPromptTokens := decimal.NewFromInt(int64(promptTokens))
  186. dCacheTokens := decimal.NewFromInt(int64(cacheTokens))
  187. dImageTokens := decimal.NewFromInt(int64(imageTokens))
  188. dAudioTokens := decimal.NewFromInt(int64(audioTokens))
  189. dCompletionTokens := decimal.NewFromInt(int64(completionTokens))
  190. dCachedCreationTokens := decimal.NewFromInt(int64(cachedCreationTokens))
  191. dCompletionRatio := decimal.NewFromFloat(completionRatio)
  192. dCacheRatio := decimal.NewFromFloat(cacheRatio)
  193. dImageRatio := decimal.NewFromFloat(imageRatio)
  194. dModelRatio := decimal.NewFromFloat(modelRatio)
  195. dGroupRatio := decimal.NewFromFloat(groupRatio)
  196. dModelPrice := decimal.NewFromFloat(modelPrice)
  197. dCachedCreationRatio := decimal.NewFromFloat(cachedCreationRatio)
  198. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  199. ratio := dModelRatio.Mul(dGroupRatio)
  200. // openai web search 工具计费
  201. var dWebSearchQuota decimal.Decimal
  202. var webSearchPrice float64
  203. // response api 格式工具计费
  204. if relayInfo.ResponsesUsageInfo != nil {
  205. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
  206. // 计算 web search 调用的配额 (配额 = 价格 * 调用次数 / 1000 * 分组倍率)
  207. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, webSearchTool.SearchContextSize)
  208. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  209. Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
  210. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  211. extraContent += fmt.Sprintf("Web Search 调用 %d 次,上下文大小 %s,调用花费 %s",
  212. webSearchTool.CallCount, webSearchTool.SearchContextSize, dWebSearchQuota.String())
  213. }
  214. } else if strings.HasSuffix(modelName, "search-preview") {
  215. // search-preview 模型不支持 response api
  216. searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
  217. if searchContextSize == "" {
  218. searchContextSize = "medium"
  219. }
  220. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, searchContextSize)
  221. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  222. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  223. extraContent += fmt.Sprintf("Web Search 调用 1 次,上下文大小 %s,调用花费 %s",
  224. searchContextSize, dWebSearchQuota.String())
  225. }
  226. // claude web search tool 计费
  227. var dClaudeWebSearchQuota decimal.Decimal
  228. var claudeWebSearchPrice float64
  229. claudeWebSearchCallCount := ctx.GetInt("claude_web_search_requests")
  230. if claudeWebSearchCallCount > 0 {
  231. claudeWebSearchPrice = operation_setting.GetClaudeWebSearchPricePerThousand()
  232. dClaudeWebSearchQuota = decimal.NewFromFloat(claudeWebSearchPrice).
  233. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit).Mul(decimal.NewFromInt(int64(claudeWebSearchCallCount)))
  234. extraContent += fmt.Sprintf("Claude Web Search 调用 %d 次,调用花费 %s",
  235. claudeWebSearchCallCount, dClaudeWebSearchQuota.String())
  236. }
  237. // file search tool 计费
  238. var dFileSearchQuota decimal.Decimal
  239. var fileSearchPrice float64
  240. if relayInfo.ResponsesUsageInfo != nil {
  241. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
  242. fileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
  243. dFileSearchQuota = decimal.NewFromFloat(fileSearchPrice).
  244. Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
  245. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  246. extraContent += fmt.Sprintf("File Search 调用 %d 次,调用花费 %s",
  247. fileSearchTool.CallCount, dFileSearchQuota.String())
  248. }
  249. }
  250. var quotaCalculateDecimal decimal.Decimal
  251. var audioInputQuota decimal.Decimal
  252. var audioInputPrice float64
  253. if !relayInfo.PriceData.UsePrice {
  254. baseTokens := dPromptTokens
  255. // 减去 cached tokens
  256. var cachedTokensWithRatio decimal.Decimal
  257. if !dCacheTokens.IsZero() {
  258. baseTokens = baseTokens.Sub(dCacheTokens)
  259. cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
  260. }
  261. var dCachedCreationTokensWithRatio decimal.Decimal
  262. if !dCachedCreationTokens.IsZero() {
  263. baseTokens = baseTokens.Sub(dCachedCreationTokens)
  264. dCachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCachedCreationRatio)
  265. }
  266. // 减去 image tokens
  267. var imageTokensWithRatio decimal.Decimal
  268. if !dImageTokens.IsZero() {
  269. baseTokens = baseTokens.Sub(dImageTokens)
  270. imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
  271. }
  272. // 减去 Gemini audio tokens
  273. if !dAudioTokens.IsZero() {
  274. audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
  275. if audioInputPrice > 0 {
  276. // 重新计算 base tokens
  277. baseTokens = baseTokens.Sub(dAudioTokens)
  278. audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  279. extraContent += fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String())
  280. }
  281. }
  282. promptQuota := baseTokens.Add(cachedTokensWithRatio).
  283. Add(imageTokensWithRatio).
  284. Add(dCachedCreationTokensWithRatio)
  285. completionQuota := dCompletionTokens.Mul(dCompletionRatio)
  286. quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
  287. if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
  288. quotaCalculateDecimal = decimal.NewFromInt(1)
  289. }
  290. } else {
  291. quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
  292. }
  293. // 添加 responses tools call 调用的配额
  294. quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
  295. quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
  296. // 添加 audio input 独立计费
  297. quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
  298. quota := int(quotaCalculateDecimal.Round(0).IntPart())
  299. totalTokens := promptTokens + completionTokens
  300. var logContent string
  301. // record all the consume log even if quota is 0
  302. if totalTokens == 0 {
  303. // in this case, must be some error happened
  304. // we cannot just return, because we may have to return the pre-consumed quota
  305. quota = 0
  306. logContent += fmt.Sprintf("(可能是上游超时)")
  307. logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  308. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
  309. } else {
  310. if !ratio.IsZero() && quota == 0 {
  311. quota = 1
  312. }
  313. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  314. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  315. }
  316. quotaDelta := quota - relayInfo.FinalPreConsumedQuota
  317. //logger.LogInfo(ctx, fmt.Sprintf("request quota delta: %s", logger.FormatQuota(quotaDelta)))
  318. if quotaDelta > 0 {
  319. logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
  320. logger.FormatQuota(quotaDelta),
  321. logger.FormatQuota(quota),
  322. logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
  323. ))
  324. } else if quotaDelta < 0 {
  325. logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
  326. logger.FormatQuota(-quotaDelta),
  327. logger.FormatQuota(quota),
  328. logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
  329. ))
  330. }
  331. if quotaDelta != 0 {
  332. err := service.PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
  333. if err != nil {
  334. logger.LogError(ctx, "error consuming token remain quota: "+err.Error())
  335. }
  336. }
  337. logModel := modelName
  338. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  339. logModel = "gpt-4-gizmo-*"
  340. logContent += fmt.Sprintf(",模型 %s", modelName)
  341. }
  342. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  343. logModel = "gpt-4o-gizmo-*"
  344. logContent += fmt.Sprintf(",模型 %s", modelName)
  345. }
  346. if extraContent != "" {
  347. logContent += ", " + extraContent
  348. }
  349. other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
  350. if imageTokens != 0 {
  351. other["image"] = true
  352. other["image_ratio"] = imageRatio
  353. other["image_output"] = imageTokens
  354. }
  355. if cachedCreationTokens != 0 {
  356. other["cache_creation_tokens"] = cachedCreationTokens
  357. other["cache_creation_ratio"] = cachedCreationRatio
  358. }
  359. if !dWebSearchQuota.IsZero() {
  360. if relayInfo.ResponsesUsageInfo != nil {
  361. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
  362. other["web_search"] = true
  363. other["web_search_call_count"] = webSearchTool.CallCount
  364. other["web_search_price"] = webSearchPrice
  365. }
  366. } else if strings.HasSuffix(modelName, "search-preview") {
  367. other["web_search"] = true
  368. other["web_search_call_count"] = 1
  369. other["web_search_price"] = webSearchPrice
  370. }
  371. } else if !dClaudeWebSearchQuota.IsZero() {
  372. other["web_search"] = true
  373. other["web_search_call_count"] = claudeWebSearchCallCount
  374. other["web_search_price"] = claudeWebSearchPrice
  375. }
  376. if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
  377. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
  378. other["file_search"] = true
  379. other["file_search_call_count"] = fileSearchTool.CallCount
  380. other["file_search_price"] = fileSearchPrice
  381. }
  382. }
  383. if !audioInputQuota.IsZero() {
  384. other["audio_input_seperate_price"] = true
  385. other["audio_input_token_count"] = audioTokens
  386. other["audio_input_price"] = audioInputPrice
  387. }
  388. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  389. ChannelId: relayInfo.ChannelId,
  390. PromptTokens: promptTokens,
  391. CompletionTokens: completionTokens,
  392. ModelName: logModel,
  393. TokenName: tokenName,
  394. Quota: quota,
  395. Content: logContent,
  396. TokenId: relayInfo.TokenId,
  397. UseTimeSeconds: int(useTimeSeconds),
  398. IsStream: relayInfo.IsStream,
  399. Group: relayInfo.UsingGroup,
  400. Other: other,
  401. })
  402. }