compatible_handler.go 18 KB

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