relay-text.go 16 KB

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