compatible_handler.go 20 KB

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