compatible_handler.go 19 KB

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