compatible_handler.go 20 KB

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