relay-text.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. reqMap := make(map[string]interface{})
  120. _ = common.Unmarshal(jsonData, &reqMap)
  121. for key, value := range info.ParamOverride {
  122. reqMap[key] = value
  123. }
  124. jsonData, err = common.Marshal(reqMap)
  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(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. modelName := relayInfo.OriginModelName
  177. tokenName := ctx.GetString("token_name")
  178. completionRatio := relayInfo.PriceData.CompletionRatio
  179. cacheRatio := relayInfo.PriceData.CacheRatio
  180. imageRatio := relayInfo.PriceData.ImageRatio
  181. modelRatio := relayInfo.PriceData.ModelRatio
  182. groupRatio := relayInfo.PriceData.GroupRatioInfo.GroupRatio
  183. modelPrice := relayInfo.PriceData.ModelPrice
  184. // Convert values to decimal for precise calculation
  185. dPromptTokens := decimal.NewFromInt(int64(promptTokens))
  186. dCacheTokens := decimal.NewFromInt(int64(cacheTokens))
  187. dImageTokens := decimal.NewFromInt(int64(imageTokens))
  188. dAudioTokens := decimal.NewFromInt(int64(audioTokens))
  189. dCompletionTokens := decimal.NewFromInt(int64(completionTokens))
  190. dCompletionRatio := decimal.NewFromFloat(completionRatio)
  191. dCacheRatio := decimal.NewFromFloat(cacheRatio)
  192. dImageRatio := decimal.NewFromFloat(imageRatio)
  193. dModelRatio := decimal.NewFromFloat(modelRatio)
  194. dGroupRatio := decimal.NewFromFloat(groupRatio)
  195. dModelPrice := decimal.NewFromFloat(modelPrice)
  196. dQuotaPerUnit := decimal.NewFromFloat(common.QuotaPerUnit)
  197. ratio := dModelRatio.Mul(dGroupRatio)
  198. // openai web search 工具计费
  199. var dWebSearchQuota decimal.Decimal
  200. var webSearchPrice float64
  201. // response api 格式工具计费
  202. if relayInfo.ResponsesUsageInfo != nil {
  203. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists && webSearchTool.CallCount > 0 {
  204. // 计算 web search 调用的配额 (配额 = 价格 * 调用次数 / 1000 * 分组倍率)
  205. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, webSearchTool.SearchContextSize)
  206. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  207. Mul(decimal.NewFromInt(int64(webSearchTool.CallCount))).
  208. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  209. extraContent += fmt.Sprintf("Web Search 调用 %d 次,上下文大小 %s,调用花费 %s",
  210. webSearchTool.CallCount, webSearchTool.SearchContextSize, dWebSearchQuota.String())
  211. }
  212. } else if strings.HasSuffix(modelName, "search-preview") {
  213. // search-preview 模型不支持 response api
  214. searchContextSize := ctx.GetString("chat_completion_web_search_context_size")
  215. if searchContextSize == "" {
  216. searchContextSize = "medium"
  217. }
  218. webSearchPrice = operation_setting.GetWebSearchPricePerThousand(modelName, searchContextSize)
  219. dWebSearchQuota = decimal.NewFromFloat(webSearchPrice).
  220. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  221. extraContent += fmt.Sprintf("Web Search 调用 1 次,上下文大小 %s,调用花费 %s",
  222. searchContextSize, dWebSearchQuota.String())
  223. }
  224. // claude web search tool 计费
  225. var dClaudeWebSearchQuota decimal.Decimal
  226. var claudeWebSearchPrice float64
  227. claudeWebSearchCallCount := ctx.GetInt("claude_web_search_requests")
  228. if claudeWebSearchCallCount > 0 {
  229. claudeWebSearchPrice = operation_setting.GetClaudeWebSearchPricePerThousand()
  230. dClaudeWebSearchQuota = decimal.NewFromFloat(claudeWebSearchPrice).
  231. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit).Mul(decimal.NewFromInt(int64(claudeWebSearchCallCount)))
  232. extraContent += fmt.Sprintf("Claude Web Search 调用 %d 次,调用花费 %s",
  233. claudeWebSearchCallCount, dClaudeWebSearchQuota.String())
  234. }
  235. // file search tool 计费
  236. var dFileSearchQuota decimal.Decimal
  237. var fileSearchPrice float64
  238. if relayInfo.ResponsesUsageInfo != nil {
  239. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists && fileSearchTool.CallCount > 0 {
  240. fileSearchPrice = operation_setting.GetFileSearchPricePerThousand()
  241. dFileSearchQuota = decimal.NewFromFloat(fileSearchPrice).
  242. Mul(decimal.NewFromInt(int64(fileSearchTool.CallCount))).
  243. Div(decimal.NewFromInt(1000)).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  244. extraContent += fmt.Sprintf("File Search 调用 %d 次,调用花费 %s",
  245. fileSearchTool.CallCount, dFileSearchQuota.String())
  246. }
  247. }
  248. var quotaCalculateDecimal decimal.Decimal
  249. var audioInputQuota decimal.Decimal
  250. var audioInputPrice float64
  251. if !relayInfo.PriceData.UsePrice {
  252. baseTokens := dPromptTokens
  253. // 减去 cached tokens
  254. var cachedTokensWithRatio decimal.Decimal
  255. if !dCacheTokens.IsZero() {
  256. baseTokens = baseTokens.Sub(dCacheTokens)
  257. cachedTokensWithRatio = dCacheTokens.Mul(dCacheRatio)
  258. }
  259. // 减去 image tokens
  260. var imageTokensWithRatio decimal.Decimal
  261. if !dImageTokens.IsZero() {
  262. baseTokens = baseTokens.Sub(dImageTokens)
  263. imageTokensWithRatio = dImageTokens.Mul(dImageRatio)
  264. }
  265. // 减去 Gemini audio tokens
  266. if !dAudioTokens.IsZero() {
  267. audioInputPrice = operation_setting.GetGeminiInputAudioPricePerMillionTokens(modelName)
  268. if audioInputPrice > 0 {
  269. // 重新计算 base tokens
  270. baseTokens = baseTokens.Sub(dAudioTokens)
  271. audioInputQuota = decimal.NewFromFloat(audioInputPrice).Div(decimal.NewFromInt(1000000)).Mul(dAudioTokens).Mul(dGroupRatio).Mul(dQuotaPerUnit)
  272. extraContent += fmt.Sprintf("Audio Input 花费 %s", audioInputQuota.String())
  273. }
  274. }
  275. promptQuota := baseTokens.Add(cachedTokensWithRatio).Add(imageTokensWithRatio)
  276. completionQuota := dCompletionTokens.Mul(dCompletionRatio)
  277. quotaCalculateDecimal = promptQuota.Add(completionQuota).Mul(ratio)
  278. if !ratio.IsZero() && quotaCalculateDecimal.LessThanOrEqual(decimal.Zero) {
  279. quotaCalculateDecimal = decimal.NewFromInt(1)
  280. }
  281. } else {
  282. quotaCalculateDecimal = dModelPrice.Mul(dQuotaPerUnit).Mul(dGroupRatio)
  283. }
  284. // 添加 responses tools call 调用的配额
  285. quotaCalculateDecimal = quotaCalculateDecimal.Add(dWebSearchQuota)
  286. quotaCalculateDecimal = quotaCalculateDecimal.Add(dFileSearchQuota)
  287. // 添加 audio input 独立计费
  288. quotaCalculateDecimal = quotaCalculateDecimal.Add(audioInputQuota)
  289. quota := int(quotaCalculateDecimal.Round(0).IntPart())
  290. totalTokens := promptTokens + completionTokens
  291. var logContent string
  292. // record all the consume log even if quota is 0
  293. if totalTokens == 0 {
  294. // in this case, must be some error happened
  295. // we cannot just return, because we may have to return the pre-consumed quota
  296. quota = 0
  297. logContent += fmt.Sprintf("(可能是上游超时)")
  298. logger.LogError(ctx, fmt.Sprintf("total tokens is 0, cannot consume quota, userId %d, channelId %d, "+
  299. "tokenId %d, model %s, pre-consumed quota %d", relayInfo.UserId, relayInfo.ChannelId, relayInfo.TokenId, modelName, relayInfo.FinalPreConsumedQuota))
  300. } else {
  301. if !ratio.IsZero() && quota == 0 {
  302. quota = 1
  303. }
  304. model.UpdateUserUsedQuotaAndRequestCount(relayInfo.UserId, quota)
  305. model.UpdateChannelUsedQuota(relayInfo.ChannelId, quota)
  306. }
  307. quotaDelta := quota - relayInfo.FinalPreConsumedQuota
  308. //logger.LogInfo(ctx, fmt.Sprintf("request quota delta: %s", logger.FormatQuota(quotaDelta)))
  309. if quotaDelta > 0 {
  310. logger.LogInfo(ctx, fmt.Sprintf("预扣费后补扣费:%s(实际消耗:%s,预扣费:%s)",
  311. logger.FormatQuota(quotaDelta),
  312. logger.FormatQuota(quota),
  313. logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
  314. ))
  315. } else if quotaDelta < 0 {
  316. logger.LogInfo(ctx, fmt.Sprintf("预扣费后返还扣费:%s(实际消耗:%s,预扣费:%s)",
  317. logger.FormatQuota(-quotaDelta),
  318. logger.FormatQuota(quota),
  319. logger.FormatQuota(relayInfo.FinalPreConsumedQuota),
  320. ))
  321. }
  322. if quotaDelta != 0 {
  323. err := service.PostConsumeQuota(relayInfo, quotaDelta, relayInfo.FinalPreConsumedQuota, true)
  324. if err != nil {
  325. logger.LogError(ctx, "error consuming token remain quota: "+err.Error())
  326. }
  327. }
  328. logModel := modelName
  329. if strings.HasPrefix(logModel, "gpt-4-gizmo") {
  330. logModel = "gpt-4-gizmo-*"
  331. logContent += fmt.Sprintf(",模型 %s", modelName)
  332. }
  333. if strings.HasPrefix(logModel, "gpt-4o-gizmo") {
  334. logModel = "gpt-4o-gizmo-*"
  335. logContent += fmt.Sprintf(",模型 %s", modelName)
  336. }
  337. if extraContent != "" {
  338. logContent += ", " + extraContent
  339. }
  340. other := service.GenerateTextOtherInfo(ctx, relayInfo, modelRatio, groupRatio, completionRatio, cacheTokens, cacheRatio, modelPrice, relayInfo.PriceData.GroupRatioInfo.GroupSpecialRatio)
  341. if imageTokens != 0 {
  342. other["image"] = true
  343. other["image_ratio"] = imageRatio
  344. other["image_output"] = imageTokens
  345. }
  346. if !dWebSearchQuota.IsZero() {
  347. if relayInfo.ResponsesUsageInfo != nil {
  348. if webSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolWebSearchPreview]; exists {
  349. other["web_search"] = true
  350. other["web_search_call_count"] = webSearchTool.CallCount
  351. other["web_search_price"] = webSearchPrice
  352. }
  353. } else if strings.HasSuffix(modelName, "search-preview") {
  354. other["web_search"] = true
  355. other["web_search_call_count"] = 1
  356. other["web_search_price"] = webSearchPrice
  357. }
  358. } else if !dClaudeWebSearchQuota.IsZero() {
  359. other["web_search"] = true
  360. other["web_search_call_count"] = claudeWebSearchCallCount
  361. other["web_search_price"] = claudeWebSearchPrice
  362. }
  363. if !dFileSearchQuota.IsZero() && relayInfo.ResponsesUsageInfo != nil {
  364. if fileSearchTool, exists := relayInfo.ResponsesUsageInfo.BuiltInTools[dto.BuildInToolFileSearch]; exists {
  365. other["file_search"] = true
  366. other["file_search_call_count"] = fileSearchTool.CallCount
  367. other["file_search_price"] = fileSearchPrice
  368. }
  369. }
  370. if !audioInputQuota.IsZero() {
  371. other["audio_input_seperate_price"] = true
  372. other["audio_input_token_count"] = audioTokens
  373. other["audio_input_price"] = audioInputPrice
  374. }
  375. model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{
  376. ChannelId: relayInfo.ChannelId,
  377. PromptTokens: promptTokens,
  378. CompletionTokens: completionTokens,
  379. ModelName: logModel,
  380. TokenName: tokenName,
  381. Quota: quota,
  382. Content: logContent,
  383. TokenId: relayInfo.TokenId,
  384. UseTimeSeconds: int(useTimeSeconds),
  385. IsStream: relayInfo.IsStream,
  386. Group: relayInfo.UsingGroup,
  387. Other: other,
  388. })
  389. }