relay-text.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. package relay
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "net/http"
  10. "one-api/common"
  11. "one-api/constant"
  12. "one-api/dto"
  13. "one-api/model"
  14. relaycommon "one-api/relay/common"
  15. relayconstant "one-api/relay/constant"
  16. "one-api/relay/helper"
  17. "one-api/service"
  18. "one-api/setting"
  19. "one-api/setting/model_setting"
  20. "one-api/setting/operation_setting"
  21. "one-api/types"
  22. "strings"
  23. "time"
  24. "github.com/bytedance/gopkg/util/gopool"
  25. "github.com/shopspring/decimal"
  26. "github.com/gin-gonic/gin"
  27. )
  28. func getAndValidateTextRequest(c *gin.Context, relayInfo *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error) {
  29. textRequest := &dto.GeneralOpenAIRequest{}
  30. err := common.UnmarshalBodyReusable(c, textRequest)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if relayInfo.RelayMode == relayconstant.RelayModeModerations && textRequest.Model == "" {
  35. textRequest.Model = "text-moderation-latest"
  36. }
  37. if relayInfo.RelayMode == relayconstant.RelayModeEmbeddings && textRequest.Model == "" {
  38. textRequest.Model = c.Param("model")
  39. }
  40. if textRequest.MaxTokens > math.MaxInt32/2 {
  41. return nil, errors.New("max_tokens is invalid")
  42. }
  43. if textRequest.Model == "" {
  44. return nil, errors.New("model is required")
  45. }
  46. if textRequest.WebSearchOptions != nil {
  47. if textRequest.WebSearchOptions.SearchContextSize != "" {
  48. validSizes := map[string]bool{
  49. "high": true,
  50. "medium": true,
  51. "low": true,
  52. }
  53. if !validSizes[textRequest.WebSearchOptions.SearchContextSize] {
  54. return nil, errors.New("invalid search_context_size, must be one of: high, medium, low")
  55. }
  56. } else {
  57. textRequest.WebSearchOptions.SearchContextSize = "medium"
  58. }
  59. }
  60. switch relayInfo.RelayMode {
  61. case relayconstant.RelayModeCompletions:
  62. if textRequest.Prompt == "" {
  63. return nil, errors.New("field prompt is required")
  64. }
  65. case relayconstant.RelayModeChatCompletions:
  66. if len(textRequest.Messages) == 0 {
  67. return nil, errors.New("field messages is required")
  68. }
  69. case relayconstant.RelayModeEmbeddings:
  70. case relayconstant.RelayModeModerations:
  71. if textRequest.Input == nil || textRequest.Input == "" {
  72. return nil, errors.New("field input is required")
  73. }
  74. case relayconstant.RelayModeEdits:
  75. if textRequest.Instruction == "" {
  76. return nil, errors.New("field instruction is required")
  77. }
  78. }
  79. relayInfo.IsStream = textRequest.Stream
  80. return textRequest, nil
  81. }
  82. func TextHelper(c *gin.Context) (newAPIError *types.NewAPIError) {
  83. relayInfo := relaycommon.GenRelayInfo(c)
  84. // get & validate textRequest 获取并验证文本请求
  85. textRequest, err := getAndValidateTextRequest(c, relayInfo)
  86. if err != nil {
  87. return types.NewError(err, types.ErrorCodeInvalidRequest)
  88. }
  89. if textRequest.WebSearchOptions != nil {
  90. c.Set("chat_completion_web_search_context_size", textRequest.WebSearchOptions.SearchContextSize)
  91. }
  92. if setting.ShouldCheckPromptSensitive() {
  93. words, err := checkRequestSensitive(textRequest, relayInfo)
  94. if err != nil {
  95. common.LogWarn(c, fmt.Sprintf("user sensitive words detected: %s", strings.Join(words, ", ")))
  96. return types.NewError(err, types.ErrorCodeSensitiveWordsDetected)
  97. }
  98. }
  99. err = helper.ModelMappedHelper(c, relayInfo, textRequest)
  100. if err != nil {
  101. return types.NewError(err, types.ErrorCodeChannelModelMappedError)
  102. }
  103. // 获取 promptTokens,如果上下文中已经存在,则直接使用
  104. var promptTokens int
  105. if value, exists := c.Get("prompt_tokens"); exists {
  106. promptTokens = value.(int)
  107. relayInfo.PromptTokens = promptTokens
  108. } else {
  109. promptTokens, err = getPromptTokens(textRequest, relayInfo)
  110. // count messages token error 计算promptTokens错误
  111. if err != nil {
  112. return types.NewError(err, types.ErrorCodeCountTokenFailed)
  113. }
  114. c.Set("prompt_tokens", promptTokens)
  115. }
  116. priceData, err := helper.ModelPriceHelper(c, relayInfo, promptTokens, int(math.Max(float64(textRequest.MaxTokens), float64(textRequest.MaxCompletionTokens))))
  117. if err != nil {
  118. return types.NewError(err, types.ErrorCodeModelPriceError)
  119. }
  120. // pre-consume quota 预消耗配额
  121. preConsumedQuota, userQuota, newApiErr := preConsumeQuota(c, priceData.ShouldPreConsumedQuota, relayInfo)
  122. if newApiErr != nil {
  123. return newApiErr
  124. }
  125. defer func() {
  126. if newApiErr != nil {
  127. returnPreConsumedQuota(c, relayInfo, userQuota, preConsumedQuota)
  128. }
  129. }()
  130. includeUsage := false
  131. // 判断用户是否需要返回使用情况
  132. if textRequest.StreamOptions != nil && textRequest.StreamOptions.IncludeUsage {
  133. includeUsage = true
  134. }
  135. // 如果不支持StreamOptions,将StreamOptions设置为nil
  136. if !relayInfo.SupportStreamOptions || !textRequest.Stream {
  137. textRequest.StreamOptions = nil
  138. } else {
  139. // 如果支持StreamOptions,且请求中没有设置StreamOptions,根据配置文件设置StreamOptions
  140. if constant.ForceStreamOption {
  141. textRequest.StreamOptions = &dto.StreamOptions{
  142. IncludeUsage: true,
  143. }
  144. }
  145. }
  146. if includeUsage {
  147. relayInfo.ShouldIncludeUsage = true
  148. }
  149. adaptor := GetAdaptor(relayInfo.ApiType)
  150. if adaptor == nil {
  151. return types.NewError(fmt.Errorf("invalid api type: %d", relayInfo.ApiType), types.ErrorCodeInvalidApiType)
  152. }
  153. adaptor.Init(relayInfo)
  154. var requestBody io.Reader
  155. if model_setting.GetGlobalSettings().PassThroughRequestEnabled {
  156. body, err := common.GetRequestBody(c)
  157. if err != nil {
  158. return types.NewErrorWithStatusCode(err, types.ErrorCodeReadRequestBodyFailed, http.StatusBadRequest)
  159. }
  160. requestBody = bytes.NewBuffer(body)
  161. } else {
  162. convertedRequest, err := adaptor.ConvertOpenAIRequest(c, relayInfo, textRequest)
  163. if err != nil {
  164. return types.NewError(err, types.ErrorCodeConvertRequestFailed)
  165. }
  166. jsonData, err := json.Marshal(convertedRequest)
  167. if err != nil {
  168. return types.NewError(err, types.ErrorCodeConvertRequestFailed)
  169. }
  170. // apply param override
  171. if len(relayInfo.ParamOverride) > 0 {
  172. reqMap := make(map[string]interface{})
  173. _ = common.Unmarshal(jsonData, &reqMap)
  174. for key, value := range relayInfo.ParamOverride {
  175. reqMap[key] = value
  176. }
  177. jsonData, err = common.Marshal(reqMap)
  178. if err != nil {
  179. return types.NewError(err, types.ErrorCodeChannelParamOverrideInvalid)
  180. }
  181. }
  182. if common.DebugEnabled {
  183. println("requestBody: ", string(jsonData))
  184. }
  185. requestBody = bytes.NewBuffer(jsonData)
  186. }
  187. var httpResp *http.Response
  188. resp, err := adaptor.DoRequest(c, relayInfo, requestBody)
  189. if err != nil {
  190. return types.NewError(err, types.ErrorCodeDoRequestFailed)
  191. }
  192. statusCodeMappingStr := c.GetString("status_code_mapping")
  193. if resp != nil {
  194. httpResp = resp.(*http.Response)
  195. relayInfo.IsStream = relayInfo.IsStream || strings.HasPrefix(httpResp.Header.Get("Content-Type"), "text/event-stream")
  196. if httpResp.StatusCode != http.StatusOK {
  197. newApiErr = service.RelayErrorHandler(httpResp, false)
  198. // reset status code 重置状态码
  199. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  200. return newApiErr
  201. }
  202. }
  203. usage, newApiErr := adaptor.DoResponse(c, httpResp, relayInfo)
  204. if newApiErr != nil {
  205. // reset status code 重置状态码
  206. service.ResetStatusCode(newApiErr, statusCodeMappingStr)
  207. return newApiErr
  208. }
  209. if strings.HasPrefix(relayInfo.OriginModelName, "gpt-4o-audio") {
  210. service.PostAudioConsumeQuota(c, relayInfo, usage.(*dto.Usage), preConsumedQuota, userQuota, priceData, "")
  211. } else {
  212. postConsumeQuota(c, relayInfo, usage.(*dto.Usage), preConsumedQuota, userQuota, priceData, "")
  213. }
  214. return nil
  215. }
  216. func getPromptTokens(textRequest *dto.GeneralOpenAIRequest, info *relaycommon.RelayInfo) (int, error) {
  217. var promptTokens int
  218. var err error
  219. switch info.RelayMode {
  220. case relayconstant.RelayModeChatCompletions:
  221. promptTokens, err = service.CountTokenChatRequest(info, *textRequest)
  222. case relayconstant.RelayModeCompletions:
  223. promptTokens = service.CountTokenInput(textRequest.Prompt, textRequest.Model)
  224. case relayconstant.RelayModeModerations:
  225. promptTokens = service.CountTokenInput(textRequest.Input, textRequest.Model)
  226. case relayconstant.RelayModeEmbeddings:
  227. promptTokens = service.CountTokenInput(textRequest.Input, textRequest.Model)
  228. default:
  229. err = errors.New("unknown relay mode")
  230. promptTokens = 0
  231. }
  232. info.PromptTokens = promptTokens
  233. return promptTokens, err
  234. }
  235. func checkRequestSensitive(textRequest *dto.GeneralOpenAIRequest, info *relaycommon.RelayInfo) ([]string, error) {
  236. var err error
  237. var words []string
  238. switch info.RelayMode {
  239. case relayconstant.RelayModeChatCompletions:
  240. words, err = service.CheckSensitiveMessages(textRequest.Messages)
  241. case relayconstant.RelayModeCompletions:
  242. words, err = service.CheckSensitiveInput(textRequest.Prompt)
  243. case relayconstant.RelayModeModerations:
  244. words, err = service.CheckSensitiveInput(textRequest.Input)
  245. case relayconstant.RelayModeEmbeddings:
  246. words, err = service.CheckSensitiveInput(textRequest.Input)
  247. }
  248. return words, err
  249. }
  250. // 预扣费并返回用户剩余配额
  251. func preConsumeQuota(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) (int, int, *types.NewAPIError) {
  252. userQuota, err := model.GetUserQuota(relayInfo.UserId, false)
  253. if err != nil {
  254. return 0, 0, types.NewError(err, types.ErrorCodeQueryDataError)
  255. }
  256. if userQuota <= 0 {
  257. return 0, 0, types.NewErrorWithStatusCode(errors.New("user quota is not enough"), types.ErrorCodeInsufficientUserQuota, http.StatusForbidden)
  258. }
  259. if userQuota-preConsumedQuota < 0 {
  260. return 0, 0, types.NewErrorWithStatusCode(fmt.Errorf("pre-consume quota failed, user quota: %s, need quota: %s", common.FormatQuota(userQuota), common.FormatQuota(preConsumedQuota)), types.ErrorCodeInsufficientUserQuota, http.StatusForbidden)
  261. }
  262. relayInfo.UserQuota = userQuota
  263. if userQuota > 100*preConsumedQuota {
  264. // 用户额度充足,判断令牌额度是否充足
  265. if !relayInfo.TokenUnlimited {
  266. // 非无限令牌,判断令牌额度是否充足
  267. tokenQuota := c.GetInt("token_quota")
  268. if tokenQuota > 100*preConsumedQuota {
  269. // 令牌额度充足,信任令牌
  270. preConsumedQuota = 0
  271. common.LogInfo(c, fmt.Sprintf("user %d quota %s and token %d quota %d are enough, trusted and no need to pre-consume", relayInfo.UserId, common.FormatQuota(userQuota), relayInfo.TokenId, tokenQuota))
  272. }
  273. } else {
  274. // in this case, we do not pre-consume quota
  275. // because the user has enough quota
  276. preConsumedQuota = 0
  277. common.LogInfo(c, fmt.Sprintf("user %d with unlimited token has enough quota %s, trusted and no need to pre-consume", relayInfo.UserId, common.FormatQuota(userQuota)))
  278. }
  279. }
  280. if preConsumedQuota > 0 {
  281. err := service.PreConsumeTokenQuota(relayInfo, preConsumedQuota)
  282. if err != nil {
  283. return 0, 0, types.NewErrorWithStatusCode(err, types.ErrorCodePreConsumeTokenQuotaFailed, http.StatusForbidden)
  284. }
  285. err = model.DecreaseUserQuota(relayInfo.UserId, preConsumedQuota)
  286. if err != nil {
  287. return 0, 0, types.NewError(err, types.ErrorCodeUpdateDataError)
  288. }
  289. }
  290. return preConsumedQuota, userQuota, nil
  291. }
  292. func returnPreConsumedQuota(c *gin.Context, relayInfo *relaycommon.RelayInfo, userQuota int, preConsumedQuota int) {
  293. if preConsumedQuota != 0 {
  294. gopool.Go(func() {
  295. relayInfoCopy := *relayInfo
  296. err := service.PostConsumeQuota(&relayInfoCopy, -preConsumedQuota, 0, false)
  297. if err != nil {
  298. common.SysError("error return pre-consumed quota: " + err.Error())
  299. }
  300. })
  301. }
  302. }
  303. func postConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo,
  304. usage *dto.Usage, preConsumedQuota int, userQuota int, priceData helper.PriceData, extraContent string) {
  305. if usage == nil {
  306. usage = &dto.Usage{
  307. PromptTokens: relayInfo.PromptTokens,
  308. CompletionTokens: 0,
  309. TotalTokens: relayInfo.PromptTokens,
  310. }
  311. extraContent += "(可能是请求出错)"
  312. }
  313. useTimeSeconds := time.Now().Unix() - relayInfo.StartTime.Unix()
  314. promptTokens := usage.PromptTokens
  315. cacheTokens := usage.PromptTokensDetails.CachedTokens
  316. imageTokens := usage.PromptTokensDetails.ImageTokens
  317. audioTokens := usage.PromptTokensDetails.AudioTokens
  318. completionTokens := usage.CompletionTokens
  319. modelName := relayInfo.OriginModelName
  320. tokenName := ctx.GetString("token_name")
  321. completionRatio := priceData.CompletionRatio
  322. cacheRatio := priceData.CacheRatio
  323. imageRatio := priceData.ImageRatio
  324. modelRatio := priceData.ModelRatio
  325. groupRatio := priceData.GroupRatioInfo.GroupRatio
  326. modelPrice := priceData.ModelPrice
  327. // Convert values to decimal for precise calculation
  328. dPromptTokens := decimal.NewFromInt(int64(promptTokens))
  329. dCacheTokens := decimal.NewFromInt(int64(cacheTokens))
  330. dImageTokens := decimal.NewFromInt(int64(imageTokens))
  331. dAudioTokens := decimal.NewFromInt(int64(audioTokens))
  332. dCompletionTokens := decimal.NewFromInt(int64(completionTokens))
  333. dCompletionRatio := decimal.NewFromFloat(completionRatio)
  334. dCacheRatio := decimal.NewFromFloat(cacheRatio)
  335. dImageRatio := decimal.NewFromFloat(imageRatio)
  336. dModelRatio := decimal.NewFromFloat(modelRatio)
  337. dGroupRatio := decimal.NewFromFloat(groupRatio)
  338. dModelPrice := decimal.NewFromFloat(modelPrice)
  339. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  340. ratio := dModelRatio.Mul(dGroupRatio)
  341. // openai web search 工具计费
  342. var dWebSearchQuota decimal.Decimal
  343. var webSearchPrice float64
  344. if relayInfo.ResponsesUsageInfo != nil {
  345. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
  346. // 计算 web search 调用的配额 (配额 = 价格 * 调用次数 / 1000 * 分组倍率)
  347. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, webSearchTool.SearchContextSize)
  348. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  349. Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
  350. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  351. extraContent += fmt.Sprintf("Web Search 调用 %d 次,上下文大小 %s,调用花费 %s",
  352. webSearchTool.CallCount, webSearchTool.SearchContextSize, dWebSearchQuota.String())
  353. }
  354. } else if strings.HasSuffix(modelName, "search-preview") {
  355. // search-preview 模型不支持 response api
  356. searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
  357. if searchContextSize == "" {
  358. searchContextSize = "medium"
  359. }
  360. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, searchContextSize)
  361. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  362. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  363. extraContent += fmt.Sprintf("Web Search 调用 1 次,上下文大小 %s,调用花费 %s",
  364. searchContextSize, dWebSearchQuota.String())
  365. }
  366. // file search tool 计费
  367. var dFileSearchQuota decimal.Decimal
  368. var fileSearchPrice float64
  369. if relayInfo.ResponsesUsageInfo != nil {
  370. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
  371. fileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
  372. dFileSearchQuota = decimal.NewFromFloat(fileSearchPrice).
  373. Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
  374. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  375. extraContent += fmt.Sprintf("File Search 调用 %d 次,调用花费 %s",
  376. fileSearchTool.CallCount, dFileSearchQuota.String())
  377. }
  378. }
  379. var quotaCalculateDecimal decimal.Decimal
  380. var audioInputQuota decimal.Decimal
  381. var audioInputPrice float64
  382. if !priceData.UsePrice {
  383. baseTokens := dPromptTokens
  384. // 减去 cached tokens
  385. var cachedTokensWithRatio decimal.Decimal
  386. if !dCacheTokens.IsZero() {
  387. baseTokens = baseTokens.Sub(dCacheTokens)
  388. cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
  389. }
  390. // 减去 image tokens
  391. var imageTokensWithRatio decimal.Decimal
  392. if !dImageTokens.IsZero() {
  393. baseTokens = baseTokens.Sub(dImageTokens)
  394. imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
  395. }
  396. // 减去 Gemini audio tokens
  397. if !dAudioTokens.IsZero() {
  398. audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
  399. if audioInputPrice > 0 {
  400. // 重新计算 base tokens
  401. baseTokens = baseTokens.Sub(dAudioTokens)
  402. audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  403. extraContent += fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String())
  404. }
  405. }
  406. promptQuota := baseTokens.Add(cachedTokensWithRatio).Add(imageTokensWithRatio)
  407. completionQuota := dCompletionTokens.Mul(dCompletionRatio)
  408. quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
  409. if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
  410. quotaCalculateDecimal = decimal.NewFromInt(1)
  411. }
  412. } else {
  413. quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
  414. }
  415. // 添加 responses tools call 调用的配额
  416. quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
  417. quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
  418. // 添加 audio input 独立计费
  419. quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
  420. quota := int(quotaCalculateDecimal.Round(0).IntPart())
  421. totalTokens := promptTokens + completionTokens
  422. var logContent string
  423. if !priceData.UsePrice {
  424. logContent = fmt.Sprintf("模型倍率 %.2f,补全倍率 %.2f,分组倍率 %.2f", modelRatio, completionRatio, groupRatio)
  425. } else {
  426. logContent = fmt.Sprintf("模型价格 %.2f,分组倍率 %.2f", modelPrice, groupRatio)
  427. }
  428. // record all the consume log even if quota is 0
  429. if totalTokens == 0 {
  430. // in this case, must be some error happened
  431. // we cannot just return, because we may have to return the pre-consumed quota
  432. quota = 0
  433. logContent += fmt.Sprintf("(可能是上游超时)")
  434. common.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  435. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, preConsumedQuota))
  436. } else {
  437. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  438. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  439. }
  440. quotaDelta := quota - preConsumedQuota
  441. if quotaDelta != 0 {
  442. err := service.PostConsumeQuota(relayInfo, quotaDelta, preConsumedQuota, true)
  443. if err != nil {
  444. common.LogError(ctx, "error consuming token remain quota: "+err.Error())
  445. }
  446. }
  447. logModel := modelName
  448. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  449. logModel = "gpt-4-gizmo-*"
  450. logContent += fmt.Sprintf(",模型 %s", modelName)
  451. }
  452. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  453. logModel = "gpt-4o-gizmo-*"
  454. logContent += fmt.Sprintf(",模型 %s", modelName)
  455. }
  456. if extraContent != "" {
  457. logContent += ", " + extraContent
  458. }
  459. other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, priceData.GroupRatioInfo.GroupSpecialRatio)
  460. if imageTokens != 0 {
  461. other["image"] = true
  462. other["image_ratio"] = imageRatio
  463. other["image_output"] = imageTokens
  464. }
  465. if !dWebSearchQuota.IsZero() {
  466. if relayInfo.ResponsesUsageInfo != nil {
  467. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
  468. other["web_search"] = true
  469. other["web_search_call_count"] = webSearchTool.CallCount
  470. other["web_search_price"] = webSearchPrice
  471. }
  472. } else if strings.HasSuffix(modelName, "search-preview") {
  473. other["web_search"] = true
  474. other["web_search_call_count"] = 1
  475. other["web_search_price"] = webSearchPrice
  476. }
  477. }
  478. if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
  479. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
  480. other["file_search"] = true
  481. other["file_search_call_count"] = fileSearchTool.CallCount
  482. other["file_search_price"] = fileSearchPrice
  483. }
  484. }
  485. if !audioInputQuota.IsZero() {
  486. other["audio_input_seperate_price"] = true
  487. other["audio_input_token_count"] = audioTokens
  488. other["audio_input_price"] = audioInputPrice
  489. }
  490. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  491. ChannelId: relayInfo.ChannelId,
  492. PromptTokens: promptTokens,
  493. CompletionTokens: completionTokens,
  494. ModelName: logModel,
  495. TokenName: tokenName,
  496. Quota: quota,
  497. Content: logContent,
  498. TokenId: relayInfo.TokenId,
  499. UserQuota: userQuota,
  500. UseTimeSeconds: int(useTimeSeconds),
  501. IsStream: relayInfo.IsStream,
  502. Group: relayInfo.UsingGroup,
  503. Other: other,
  504. })
  505. }