compatible_handler.go 18 KB

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