compatible_handler.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. package relay
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/QuantumNous/new-api/common"
  10. "github.com/QuantumNous/new-api/constant"
  11. "github.com/QuantumNous/new-api/dto"
  12. "github.com/QuantumNous/new-api/logger"
  13. "github.com/QuantumNous/new-api/model"
  14. "github.com/QuantumNous/new-api/pkg/billingexpr"
  15. relaycommon "github.com/QuantumNous/new-api/relay/common"
  16. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  17. "github.com/QuantumNous/new-api/relay/helper"
  18. "github.com/QuantumNous/new-api/service"
  19. "github.com/QuantumNous/new-api/setting/model_setting"
  20. "github.com/QuantumNous/new-api/setting/operation_setting"
  21. "github.com/QuantumNous/new-api/setting/ratio_setting"
  22. "github.com/QuantumNous/new-api/types"
  23. "github.com/samber/lo"
  24. "github.com/shopspring/decimal"
  25. "github.com/gin-gonic/gin"
  26. )
  27. func TextHelper(c *gin.Context, info *relaycommon.RelayInfo) (newAPIError *types.NewAPIError) {
  28. info.InitChannelMeta(c)
  29. textReq, ok := info.Request.(*dto.GeneralOpenAIRequest)
  30. if !ok {
  31. return types.NewErrorWithStatusCode(fmt.Errorf("invalid request type, expected dto.GeneralOpenAIRequest, got %T", info.Request), types.ErrorCodeInvalidRequest, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  32. }
  33. request, err := common.DeepCopy(textReq)
  34. if err != nil {
  35. return types.NewError(fmt.Errorf("failed to copy request to GeneralOpenAIRequest: %w", err), types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
  36. }
  37. if request.WebSearchOptions != nil {
  38. c.Set("chat_completion_web_search_context_size", request.WebSearchOptions.SearchContextSize)
  39. }
  40. err = helper.ModelMappedHelper(c, info, request)
  41. if err != nil {
  42. return types.NewError(err, types.ErrorCodeChannelModelMappedError, types.ErrOptionWithSkipRetry())
  43. }
  44. includeUsage := true
  45. // 判断用户是否需要返回使用情况
  46. if request.StreamOptions != nil {
  47. includeUsage = request.StreamOptions.IncludeUsage
  48. }
  49. // 如果不支持StreamOptions,将StreamOptions设置为nil
  50. if !info.SupportStreamOptions || !lo.FromPtrOr(request.Stream, false) {
  51. request.StreamOptions = nil
  52. } else {
  53. // 如果支持StreamOptions,且请求中没有设置StreamOptions,根据配置文件设置StreamOptions
  54. if constant.ForceStreamOption {
  55. request.StreamOptions = &dto.StreamOptions{
  56. IncludeUsage: true,
  57. }
  58. }
  59. }
  60. info.ShouldIncludeUsage = includeUsage
  61. adaptor := GetAdaptor(info.ApiType)
  62. if adaptor == nil {
  63. return types.NewError(fmt.Errorf("invalid api type: %d", info.ApiType), types.ErrorCodeInvalidApiType, types.ErrOptionWithSkipRetry())
  64. }
  65. adaptor.Init(info)
  66. passThroughGlobal := model_setting.GetGlobalSettings().PassThroughRequestEnabled
  67. if info.RelayMode == relayconstant.RelayModeChatCompletions &&
  68. !passThroughGlobal &&
  69. !info.ChannelSetting.PassThroughBodyEnabled &&
  70. service.ShouldChatCompletionsUseResponsesGlobal(info.ChannelId, info.ChannelType, info.OriginModelName) {
  71. applySystemPromptIfNeeded(c, info, request)
  72. usage, newApiErr := chatCompletionsViaResponses(c, info, adaptor, request)
  73. if newApiErr != nil {
  74. return newApiErr
  75. }
  76. var containAudioTokens = usage.CompletionTokenDetails.AudioTokens > 0 || usage.PromptTokensDetails.AudioTokens > 0
  77. var containsAudioRatios = ratio_setting.ContainsAudioRatio(info.OriginModelName) || ratio_setting.ContainsAudioCompletionRatio(info.OriginModelName)
  78. if containAudioTokens && containsAudioRatios {
  79. service.PostAudioConsumeQuota(c, info, usage, "")
  80. } else {
  81. postConsumeQuota(c, info, usage)
  82. }
  83. return nil
  84. }
  85. var requestBody io.Reader
  86. if passThroughGlobal || info.ChannelSetting.PassThroughBodyEnabled {
  87. storage, err := common.GetBodyStorage(c)
  88. if err != nil {
  89. return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest, types.ErrOptionWithSkipRetry())
  90. }
  91. if common.DebugEnabled {
  92. if debugBytes, bErr := storage.Bytes(); bErr == nil {
  93. println("requestBody: ", string(debugBytes))
  94. }
  95. }
  96. requestBody = common.ReaderOnly(storage)
  97. } else {
  98. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, info, request)
  99. if err != nil {
  100. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  101. }
  102. relaycommon.AppendRequestConversionFromRequest(info, convertedRequest)
  103. if info.ChannelSetting.SystemPrompt != "" {
  104. // 如果有系统提示,则将其添加到请求中
  105. request, ok := convertedRequest.(*dto.GeneralOpenAIRequest)
  106. if ok {
  107. containSystemPrompt := false
  108. for _, message := range request.Messages {
  109. if message.Role == request.GetSystemRoleName() {
  110. containSystemPrompt = true
  111. break
  112. }
  113. }
  114. if !containSystemPrompt {
  115. // 如果没有系统提示,则添加系统提示
  116. systemMessage := dto.Message{
  117. Role: request.GetSystemRoleName(),
  118. Content: info.ChannelSetting.SystemPrompt,
  119. }
  120. request.Messages = append([]dto.Message{systemMessage}, request.Messages...)
  121. } else if info.ChannelSetting.SystemPromptOverride {
  122. common.SetContextKey(c, constant.ContextKeySystemPromptOverride, true)
  123. // 如果有系统提示,且允许覆盖,则拼接到前面
  124. for i, message := range request.Messages {
  125. if message.Role == request.GetSystemRoleName() {
  126. if message.IsStringContent() {
  127. request.Messages[i].SetStringContent(info.ChannelSetting.SystemPrompt + "\n" + message.StringContent())
  128. } else {
  129. contents := message.ParseContent()
  130. contents = append([]dto.MediaContent{
  131. {
  132. Type: dto.ContentTypeText,
  133. Text: info.ChannelSetting.SystemPrompt,
  134. },
  135. }, contents...)
  136. request.Messages[i].Content = contents
  137. }
  138. break
  139. }
  140. }
  141. }
  142. }
  143. }
  144. jsonData, err := common.Marshal(convertedRequest)
  145. if err != nil {
  146. return types.NewError(err, types.ErrorCodeJsonMarshalFailed, types.ErrOptionWithSkipRetry())
  147. }
  148. // remove disabled fields for OpenAI API
  149. jsonData, err = relaycommon.RemoveDisabledFields(jsonData, info.ChannelOtherSettings, info.ChannelSetting.PassThroughBodyEnabled)
  150. if err != nil {
  151. return types.NewError(err, types.ErrorCodeConvertRequestFailed, types.ErrOptionWithSkipRetry())
  152. }
  153. // apply param override
  154. if len(info.ParamOverride) > 0 {
  155. jsonData, err = relaycommon.ApplyParamOverrideWithRelayInfo(jsonData, info)
  156. if err != nil {
  157. return newAPIErrorFromParamOverride(err)
  158. }
  159. }
  160. logger.LogDebug(c, fmt.Sprintf("text request body: %s", string(jsonData)))
  161. requestBody = bytes.NewBuffer(jsonData)
  162. }
  163. var httpResp *http.Response
  164. resp, err := adaptor.DoRequest(c, info, requestBody)
  165. if err != nil {
  166. return types.NewOpenAIError(err, types.ErrorCodeDoRequestFailed, http.StatusInternalServerError)
  167. }
  168. statusCodeMappingStr := c.GetString("status_code_mapping")
  169. if resp != nil {
  170. httpResp = resp.(*http.Response)
  171. info.IsStream = info.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  172. if httpResp.StatusCode != http.StatusOK {
  173. newApiErr := service.RelayErrorHandler(c.Request.Context(), httpResp, false)
  174. // reset status code 重置状态码
  175. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  176. return newApiErr
  177. }
  178. }
  179. usage, newApiErr := adaptor.DoResponse(c, httpResp, info)
  180. if newApiErr != nil {
  181. // reset status code 重置状态码
  182. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  183. return newApiErr
  184. }
  185. var containAudioTokens = usage.(*dto.Usage).CompletionTokenDetails.AudioTokens > 0 || usage.(*dto.Usage).PromptTokensDetails.AudioTokens > 0
  186. var containsAudioRatios = ratio_setting.ContainsAudioRatio(info.OriginModelName) || ratio_setting.ContainsAudioCompletionRatio(info.OriginModelName)
  187. if containAudioTokens && containsAudioRatios {
  188. service.PostAudioConsumeQuota(c, info, usage.(*dto.Usage), "")
  189. } else {
  190. postConsumeQuota(c, info, usage.(*dto.Usage))
  191. }
  192. return nil
  193. }
  194. func postConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, extraContent ...string) {
  195. originUsage := usage
  196. if usage == nil {
  197. usage = &dto.Usage{
  198. PromptTokens: relayInfo.GetEstimatePromptTokens(),
  199. CompletionTokens: 0,
  200. TotalTokens: relayInfo.GetEstimatePromptTokens(),
  201. }
  202. extraContent = append(extraContent, "上游无计费信息")
  203. }
  204. if originUsage != nil {
  205. service.ObserveChannelAffinityUsageCacheByRelayFormat(ctx, usage, relayInfo.GetFinalRequestRelayFormat())
  206. }
  207. // Tiered billing early return
  208. if ok, tieredQuota, tieredResult := service.TryTieredSettle(relayInfo, billingexpr.TokenParams{
  209. P: float64(usage.PromptTokens),
  210. C: float64(usage.CompletionTokens),
  211. CR: float64(usage.PromptTokensDetails.CachedTokens),
  212. CC: float64(usage.PromptTokensDetails.CachedCreationTokens - usage.ClaudeCacheCreation1hTokens),
  213. CC1h: float64(usage.ClaudeCacheCreation1hTokens),
  214. }); ok {
  215. postConsumeQuotaTiered(ctx, relayInfo, usage, tieredQuota, tieredResult, extraContent...)
  216. return
  217. }
  218. adminRejectReason := common.GetContextKeyString(ctx, constant.ContextKeyAdminRejectReason)
  219. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  220. promptTokens := usage.PromptTokens
  221. cacheTokens := usage.PromptTokensDetails.CachedTokens
  222. imageTokens := usage.PromptTokensDetails.ImageTokens
  223. audioTokens := usage.PromptTokensDetails.AudioTokens
  224. completionTokens := usage.CompletionTokens
  225. cachedCreationTokens := usage.PromptTokensDetails.CachedCreationTokens
  226. modelName := relayInfo.OriginModelName
  227. tokenName := ctx.GetString("token_name")
  228. completionRatio := relayInfo.PriceData.CompletionRatio
  229. cacheRatio := relayInfo.PriceData.CacheRatio
  230. imageRatio := relayInfo.PriceData.ImageRatio
  231. modelRatio := relayInfo.PriceData.ModelRatio
  232. groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
  233. modelPrice := relayInfo.PriceData.ModelPrice
  234. cachedCreationRatio := relayInfo.PriceData.CacheCreationRatio
  235. // Convert values to decimal for precise calculation
  236. dPromptTokens := decimal.NewFromInt(int64(promptTokens))
  237. dCacheTokens := decimal.NewFromInt(int64(cacheTokens))
  238. dImageTokens := decimal.NewFromInt(int64(imageTokens))
  239. dAudioTokens := decimal.NewFromInt(int64(audioTokens))
  240. dCompletionTokens := decimal.NewFromInt(int64(completionTokens))
  241. dCachedCreationTokens := decimal.NewFromInt(int64(cachedCreationTokens))
  242. dCompletionRatio := decimal.NewFromFloat(completionRatio)
  243. dCacheRatio := decimal.NewFromFloat(cacheRatio)
  244. dImageRatio := decimal.NewFromFloat(imageRatio)
  245. dModelRatio := decimal.NewFromFloat(modelRatio)
  246. dGroupRatio := decimal.NewFromFloat(groupRatio)
  247. dModelPrice := decimal.NewFromFloat(modelPrice)
  248. dCachedCreationRatio := decimal.NewFromFloat(cachedCreationRatio)
  249. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  250. ratio := dModelRatio.Mul(dGroupRatio)
  251. // openai web search 工具计费
  252. var dWebSearchQuota decimal.Decimal
  253. var webSearchPrice float64
  254. // response api 格式工具计费
  255. if relayInfo.ResponsesUsageInfo != nil {
  256. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
  257. // 计算 web search 调用的配额 (配额 = 价格 * 调用次数 / 1000 * 分组倍率)
  258. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, webSearchTool.SearchContextSize)
  259. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  260. Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
  261. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  262. extraContent = append(extraContent, fmt.Sprintf("Web Search 调用 %d 次,上下文大小 %s,调用花费 %s",
  263. webSearchTool.CallCount, webSearchTool.SearchContextSize, dWebSearchQuota.String()))
  264. }
  265. } else if strings.HasSuffix(modelName, "search-preview") {
  266. // search-preview 模型不支持 response api
  267. searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
  268. if searchContextSize == "" {
  269. searchContextSize = "medium"
  270. }
  271. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, searchContextSize)
  272. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  273. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  274. extraContent = append(extraContent, fmt.Sprintf("Web Search 调用 1 次,上下文大小 %s,调用花费 %s",
  275. searchContextSize, dWebSearchQuota.String()))
  276. }
  277. // claude web search tool 计费
  278. var dClaudeWebSearchQuota decimal.Decimal
  279. var claudeWebSearchPrice float64
  280. claudeWebSearchCallCount := ctx.GetInt("claude_web_search_requests")
  281. if claudeWebSearchCallCount > 0 {
  282. claudeWebSearchPrice = operation_setting.GetClaudeWebSearchPricePerThousand()
  283. dClaudeWebSearchQuota = decimal.NewFromFloat(claudeWebSearchPrice).
  284. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit).Mul(decimal.NewFromInt(int64(claudeWebSearchCallCount)))
  285. extraContent = append(extraContent, fmt.Sprintf("Claude Web Search 调用 %d 次,调用花费 %s",
  286. claudeWebSearchCallCount, dClaudeWebSearchQuota.String()))
  287. }
  288. // file search tool 计费
  289. var dFileSearchQuota decimal.Decimal
  290. var fileSearchPrice float64
  291. if relayInfo.ResponsesUsageInfo != nil {
  292. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
  293. fileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
  294. dFileSearchQuota = decimal.NewFromFloat(fileSearchPrice).
  295. Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
  296. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  297. extraContent = append(extraContent, fmt.Sprintf("File Search 调用 %d 次,调用花费 %s",
  298. fileSearchTool.CallCount, dFileSearchQuota.String()))
  299. }
  300. }
  301. var dImageGenerationCallQuota decimal.Decimal
  302. var imageGenerationCallPrice float64
  303. if ctx.GetBool("image_generation_call") {
  304. imageGenerationCallPrice = operation_setting.GetGPTImage1PriceOnceCall(ctx.GetString("image_generation_call_quality"), ctx.GetString("image_generation_call_size"))
  305. dImageGenerationCallQuota = decimal.NewFromFloat(imageGenerationCallPrice).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  306. extraContent = append(extraContent, fmt.Sprintf("Image Generation Call 花费 %s", dImageGenerationCallQuota.String()))
  307. }
  308. var quotaCalculateDecimal decimal.Decimal
  309. var audioInputQuota decimal.Decimal
  310. var audioInputPrice float64
  311. isClaudeUsageSemantic := relayInfo.GetFinalRequestRelayFormat() == types.RelayFormatClaude
  312. if !relayInfo.PriceData.UsePrice {
  313. baseTokens := dPromptTokens
  314. // 减去 cached tokens
  315. // Anthropic API 的 input_tokens 已经不包含缓存 tokens,不需要减去
  316. // OpenAI/OpenRouter 等 API 的 prompt_tokens 包含缓存 tokens,需要减去
  317. var cachedTokensWithRatio decimal.Decimal
  318. if !dCacheTokens.IsZero() {
  319. if !isClaudeUsageSemantic {
  320. baseTokens = baseTokens.Sub(dCacheTokens)
  321. }
  322. cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
  323. }
  324. var dCachedCreationTokensWithRatio decimal.Decimal
  325. if !dCachedCreationTokens.IsZero() {
  326. if !isClaudeUsageSemantic {
  327. baseTokens = baseTokens.Sub(dCachedCreationTokens)
  328. }
  329. dCachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCachedCreationRatio)
  330. }
  331. // 减去 image tokens
  332. var imageTokensWithRatio decimal.Decimal
  333. if !dImageTokens.IsZero() {
  334. baseTokens = baseTokens.Sub(dImageTokens)
  335. imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
  336. }
  337. // 减去 Gemini audio tokens
  338. if !dAudioTokens.IsZero() {
  339. audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
  340. if audioInputPrice > 0 {
  341. // 重新计算 base tokens
  342. baseTokens = baseTokens.Sub(dAudioTokens)
  343. audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  344. extraContent = append(extraContent, fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String()))
  345. }
  346. }
  347. promptQuota := baseTokens.Add(cachedTokensWithRatio).
  348. Add(imageTokensWithRatio).
  349. Add(dCachedCreationTokensWithRatio)
  350. completionQuota := dCompletionTokens.Mul(dCompletionRatio)
  351. quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
  352. if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
  353. quotaCalculateDecimal = decimal.NewFromInt(1)
  354. }
  355. } else {
  356. quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
  357. }
  358. // 添加 responses tools call 调用的配额
  359. quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
  360. quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
  361. // 添加 audio input 独立计费
  362. quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
  363. // 添加 image generation call 计费
  364. quotaCalculateDecimal = quotaCalculateDecimal.Add(dImageGenerationCallQuota)
  365. if len(relayInfo.PriceData.OtherRatios) > 0 {
  366. for key, otherRatio := range relayInfo.PriceData.OtherRatios {
  367. dOtherRatio := decimal.NewFromFloat(otherRatio)
  368. quotaCalculateDecimal = quotaCalculateDecimal.Mul(dOtherRatio)
  369. extraContent = append(extraContent, fmt.Sprintf("其他倍率 %s: %f", key, otherRatio))
  370. }
  371. }
  372. quota := int(quotaCalculateDecimal.Round(0).IntPart())
  373. totalTokens := promptTokens + completionTokens
  374. //var logContent string
  375. // record all the consume log even if quota is 0
  376. if totalTokens == 0 {
  377. // in this case, must be some error happened
  378. // we cannot just return, because we may have to return the pre-consumed quota
  379. quota = 0
  380. extraContent = append(extraContent, "上游没有返回计费信息,无法扣费(可能是上游超时)")
  381. logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  382. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
  383. } else {
  384. if !ratio.IsZero() && quota == 0 {
  385. quota = 1
  386. }
  387. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  388. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  389. }
  390. if err := service.SettleBilling(ctx, relayInfo, quota); err != nil {
  391. logger.LogError(ctx, "error settling billing: "+err.Error())
  392. }
  393. logModel := modelName
  394. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  395. logModel = "gpt-4-gizmo-*"
  396. extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
  397. }
  398. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  399. logModel = "gpt-4o-gizmo-*"
  400. extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
  401. }
  402. logContent := strings.Join(extraContent, ", ")
  403. other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
  404. if adminRejectReason != "" {
  405. other["reject_reason"] = adminRejectReason
  406. }
  407. // For chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently.
  408. if isClaudeUsageSemantic {
  409. other["claude"] = true
  410. other["usage_semantic"] = "anthropic"
  411. }
  412. if imageTokens != 0 {
  413. other["image"] = true
  414. other["image_ratio"] = imageRatio
  415. other["image_output"] = imageTokens
  416. }
  417. if cachedCreationTokens != 0 {
  418. other["cache_creation_tokens"] = cachedCreationTokens
  419. other["cache_creation_ratio"] = cachedCreationRatio
  420. }
  421. if !dWebSearchQuota.IsZero() {
  422. if relayInfo.ResponsesUsageInfo != nil {
  423. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
  424. other["web_search"] = true
  425. other["web_search_call_count"] = webSearchTool.CallCount
  426. other["web_search_price"] = webSearchPrice
  427. }
  428. } else if strings.HasSuffix(modelName, "search-preview") {
  429. other["web_search"] = true
  430. other["web_search_call_count"] = 1
  431. other["web_search_price"] = webSearchPrice
  432. }
  433. } else if !dClaudeWebSearchQuota.IsZero() {
  434. other["web_search"] = true
  435. other["web_search_call_count"] = claudeWebSearchCallCount
  436. other["web_search_price"] = claudeWebSearchPrice
  437. }
  438. if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
  439. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
  440. other["file_search"] = true
  441. other["file_search_call_count"] = fileSearchTool.CallCount
  442. other["file_search_price"] = fileSearchPrice
  443. }
  444. }
  445. if !audioInputQuota.IsZero() {
  446. other["audio_input_seperate_price"] = true
  447. other["audio_input_token_count"] = audioTokens
  448. other["audio_input_price"] = audioInputPrice
  449. }
  450. if !dImageGenerationCallQuota.IsZero() {
  451. other["image_generation_call"] = true
  452. other["image_generation_call_price"] = imageGenerationCallPrice
  453. }
  454. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  455. ChannelId: relayInfo.ChannelId,
  456. PromptTokens: promptTokens,
  457. CompletionTokens: completionTokens,
  458. ModelName: logModel,
  459. TokenName: tokenName,
  460. Quota: quota,
  461. Content: logContent,
  462. TokenId: relayInfo.TokenId,
  463. UseTimeSeconds: int(useTimeSeconds),
  464. IsStream: relayInfo.IsStream,
  465. Group: relayInfo.UsingGroup,
  466. Other: other,
  467. })
  468. }
  469. func postConsumeQuotaTiered(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, quota int, tieredResult *service.TieredResultWrapper, extraContent ...string) {
  470. _ = tieredResult // will be used for log enrichment
  471. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  472. modelName := relayInfo.OriginModelName
  473. tokenName := ctx.GetString("token_name")
  474. groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
  475. totalTokens := usage.PromptTokens + usage.CompletionTokens
  476. if totalTokens == 0 {
  477. quota = 0
  478. extraContent = append(extraContent, "上游没有返回计费信息,无法扣费(可能是上游超时)")
  479. logger.LogError(ctx, fmt.Sprintf("tiered billing: total tokens is 0, userId %d, channelId %d, tokenId %d, model %s, pre-consumed %d",
  480. relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
  481. } else {
  482. if groupRatio != 0 && quota == 0 {
  483. quota = 1
  484. }
  485. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  486. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  487. }
  488. if err := service.SettleBilling(ctx, relayInfo, quota); err != nil {
  489. logger.LogError(ctx, "error settling tiered billing: "+err.Error())
  490. }
  491. logModel := modelName
  492. logContent := strings.Join(extraContent, ", ")
  493. other := service.GenerateTieredOtherInfo(ctx, relayInfo, tieredResult)
  494. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  495. ChannelId: relayInfo.ChannelId,
  496. PromptTokens: usage.PromptTokens,
  497. CompletionTokens: usage.CompletionTokens,
  498. ModelName: logModel,
  499. TokenName: tokenName,
  500. Quota: quota,
  501. Content: logContent,
  502. TokenId: relayInfo.TokenId,
  503. UseTimeSeconds: int(useTimeSeconds),
  504. IsStream: relayInfo.IsStream,
  505. Group: relayInfo.UsingGroup,
  506. Other: other,
  507. })
  508. }