relay-text.go 16 KB

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