compatible_handler.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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: only determines quota, logging continues through normal path
  208. isClaudeUsageSemantic := relayInfo.GetFinalRequestRelayFormat() == types.RelayFormatClaude
  209. var tieredUsedVars map[string]bool
  210. if snap := relayInfo.TieredBillingSnapshot; snap != nil {
  211. tieredUsedVars = billingexpr.UsedVars(snap.ExprString)
  212. }
  213. var tieredResult *billingexpr.TieredResult
  214. tieredOk, tieredQuota, tieredRes := service.TryTieredSettle(relayInfo, service.BuildTieredTokenParams(usage, isClaudeUsageSemantic, tieredUsedVars))
  215. if tieredOk {
  216. tieredResult = tieredRes
  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. if !relayInfo.PriceData.UsePrice {
  312. baseTokens := dPromptTokens
  313. // 减去 cached tokens
  314. // Anthropic API 的 input_tokens 已经不包含缓存 tokens,不需要减去
  315. // OpenAI/OpenRouter 等 API 的 prompt_tokens 包含缓存 tokens,需要减去
  316. var cachedTokensWithRatio decimal.Decimal
  317. if !dCacheTokens.IsZero() {
  318. if !isClaudeUsageSemantic {
  319. baseTokens = baseTokens.Sub(dCacheTokens)
  320. }
  321. cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
  322. }
  323. var dCachedCreationTokensWithRatio decimal.Decimal
  324. if !dCachedCreationTokens.IsZero() {
  325. if !isClaudeUsageSemantic {
  326. baseTokens = baseTokens.Sub(dCachedCreationTokens)
  327. }
  328. dCachedCreationTokensWithRatio = dCachedCreationTokens.Mul(dCachedCreationRatio)
  329. }
  330. // 减去 image tokens
  331. var imageTokensWithRatio decimal.Decimal
  332. if !dImageTokens.IsZero() {
  333. baseTokens = baseTokens.Sub(dImageTokens)
  334. imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
  335. }
  336. // 减去 Gemini audio tokens
  337. if !dAudioTokens.IsZero() {
  338. audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
  339. if audioInputPrice > 0 {
  340. // 重新计算 base tokens
  341. baseTokens = baseTokens.Sub(dAudioTokens)
  342. audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  343. extraContent = append(extraContent, fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String()))
  344. }
  345. }
  346. promptQuota := baseTokens.Add(cachedTokensWithRatio).
  347. Add(imageTokensWithRatio).
  348. Add(dCachedCreationTokensWithRatio)
  349. completionQuota := dCompletionTokens.Mul(dCompletionRatio)
  350. quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
  351. if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
  352. quotaCalculateDecimal = decimal.NewFromInt(1)
  353. }
  354. } else {
  355. quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
  356. }
  357. // 添加 responses tools call 调用的配额
  358. quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
  359. quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
  360. // 添加 audio input 独立计费
  361. quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
  362. // 添加 image generation call 计费
  363. quotaCalculateDecimal = quotaCalculateDecimal.Add(dImageGenerationCallQuota)
  364. if len(relayInfo.PriceData.OtherRatios) > 0 {
  365. for key, otherRatio := range relayInfo.PriceData.OtherRatios {
  366. dOtherRatio := decimal.NewFromFloat(otherRatio)
  367. quotaCalculateDecimal = quotaCalculateDecimal.Mul(dOtherRatio)
  368. extraContent = append(extraContent, fmt.Sprintf("其他倍率 %s: %f", key, otherRatio))
  369. }
  370. }
  371. quota := int(quotaCalculateDecimal.Round(0).IntPart())
  372. if tieredOk {
  373. quota = tieredQuota
  374. }
  375. totalTokens := promptTokens + completionTokens
  376. // record all the consume log even if quota is 0
  377. if totalTokens == 0 {
  378. // in this case, must be some error happened
  379. // we cannot just return, because we may have to return the pre-consumed quota
  380. quota = 0
  381. extraContent = append(extraContent, "上游没有返回计费信息,无法扣费(可能是上游超时)")
  382. logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  383. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
  384. } else {
  385. if !ratio.IsZero() && quota == 0 {
  386. quota = 1
  387. }
  388. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  389. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  390. }
  391. if err := service.SettleBilling(ctx, relayInfo, quota); err != nil {
  392. logger.LogError(ctx, "error settling billing: "+err.Error())
  393. }
  394. logModel := modelName
  395. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  396. logModel = "gpt-4-gizmo-*"
  397. extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
  398. }
  399. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  400. logModel = "gpt-4o-gizmo-*"
  401. extraContent = append(extraContent, fmt.Sprintf("模型 %s", modelName))
  402. }
  403. logContent := strings.Join(extraContent, ", ")
  404. other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
  405. if adminRejectReason != "" {
  406. other["reject_reason"] = adminRejectReason
  407. }
  408. // For chat-based calls to the Claude model, tagging is required. Using Claude's rendering logs, the two approaches handle input rendering differently.
  409. if isClaudeUsageSemantic {
  410. other["claude"] = true
  411. other["usage_semantic"] = "anthropic"
  412. }
  413. if imageTokens != 0 {
  414. other["image"] = true
  415. other["image_ratio"] = imageRatio
  416. other["image_output"] = imageTokens
  417. }
  418. if cachedCreationTokens != 0 {
  419. other["cache_creation_tokens"] = cachedCreationTokens
  420. other["cache_creation_ratio"] = cachedCreationRatio
  421. }
  422. if !dWebSearchQuota.IsZero() {
  423. if relayInfo.ResponsesUsageInfo != nil {
  424. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
  425. other["web_search"] = true
  426. other["web_search_call_count"] = webSearchTool.CallCount
  427. other["web_search_price"] = webSearchPrice
  428. }
  429. } else if strings.HasSuffix(modelName, "search-preview") {
  430. other["web_search"] = true
  431. other["web_search_call_count"] = 1
  432. other["web_search_price"] = webSearchPrice
  433. }
  434. } else if !dClaudeWebSearchQuota.IsZero() {
  435. other["web_search"] = true
  436. other["web_search_call_count"] = claudeWebSearchCallCount
  437. other["web_search_price"] = claudeWebSearchPrice
  438. }
  439. if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
  440. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
  441. other["file_search"] = true
  442. other["file_search_call_count"] = fileSearchTool.CallCount
  443. other["file_search_price"] = fileSearchPrice
  444. }
  445. }
  446. if !audioInputQuota.IsZero() {
  447. other["audio_input_seperate_price"] = true
  448. other["audio_input_token_count"] = audioTokens
  449. other["audio_input_price"] = audioInputPrice
  450. }
  451. if !dImageGenerationCallQuota.IsZero() {
  452. other["image_generation_call"] = true
  453. other["image_generation_call_price"] = imageGenerationCallPrice
  454. }
  455. if tieredResult != nil {
  456. service.InjectTieredBillingInfo(other, relayInfo, tieredResult)
  457. }
  458. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  459. ChannelId: relayInfo.ChannelId,
  460. PromptTokens: promptTokens,
  461. CompletionTokens: completionTokens,
  462. ModelName: logModel,
  463. TokenName: tokenName,
  464. Quota: quota,
  465. Content: logContent,
  466. TokenId: relayInfo.TokenId,
  467. UseTimeSeconds: int(useTimeSeconds),
  468. IsStream: relayInfo.IsStream,
  469. Group: relayInfo.UsingGroup,
  470. Other: other,
  471. })
  472. }