relay-text.go 23 KB

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