relay_info.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. package common
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "time"
  8. "github.com/QuantumNous/new-api/common"
  9. "github.com/QuantumNous/new-api/constant"
  10. "github.com/QuantumNous/new-api/dto"
  11. relayconstant "github.com/QuantumNous/new-api/relay/constant"
  12. "github.com/QuantumNous/new-api/setting/model_setting"
  13. "github.com/QuantumNous/new-api/types"
  14. "github.com/gin-gonic/gin"
  15. "github.com/gorilla/websocket"
  16. )
  17. type ThinkingContentInfo struct {
  18. IsFirstThinkingContent bool
  19. SendLastThinkingContent bool
  20. HasSentThinkingContent bool
  21. }
  22. const (
  23. LastMessageTypeNone = "none"
  24. LastMessageTypeText = "text"
  25. LastMessageTypeTools = "tools"
  26. LastMessageTypeThinking = "thinking"
  27. )
  28. type ClaudeConvertInfo struct {
  29. LastMessagesType string
  30. Index int
  31. Usage *dto.Usage
  32. FinishReason string
  33. Done bool
  34. ToolCallBaseIndex int
  35. ToolCallMaxIndexOffset int
  36. }
  37. type RerankerInfo struct {
  38. Documents []any
  39. ReturnDocuments bool
  40. }
  41. type BuildInToolInfo struct {
  42. ToolName string
  43. CallCount int
  44. SearchContextSize string
  45. }
  46. type ResponsesUsageInfo struct {
  47. BuiltInTools map[string]*BuildInToolInfo
  48. }
  49. type ChannelMeta struct {
  50. ChannelType int
  51. ChannelId int
  52. ChannelIsMultiKey bool
  53. ChannelMultiKeyIndex int
  54. ChannelBaseUrl string
  55. ApiType int
  56. ApiVersion string
  57. ApiKey string
  58. Organization string
  59. ChannelCreateTime int64
  60. ParamOverride map[string]interface{}
  61. HeadersOverride map[string]interface{}
  62. ChannelSetting dto.ChannelSettings
  63. ChannelOtherSettings dto.ChannelOtherSettings
  64. UpstreamModelName string
  65. IsModelMapped bool
  66. SupportStreamOptions bool // 是否支持流式选项
  67. }
  68. type TokenCountMeta struct {
  69. //promptTokens int
  70. estimatePromptTokens int
  71. }
  72. type RelayInfo struct {
  73. TokenId int
  74. TokenKey string
  75. TokenGroup string
  76. UserId int
  77. UsingGroup string // 使用的分组,当auto跨分组重试时,会变动
  78. UserGroup string // 用户所在分组
  79. TokenUnlimited bool
  80. StartTime time.Time
  81. FirstResponseTime time.Time
  82. isFirstResponse bool
  83. //SendLastReasoningResponse bool
  84. IsStream bool
  85. IsGeminiBatchEmbedding bool
  86. IsPlayground bool
  87. UsePrice bool
  88. RelayMode int
  89. OriginModelName string
  90. RequestURLPath string
  91. ShouldIncludeUsage bool
  92. DisablePing bool // 是否禁止向下游发送自定义 Ping
  93. ClientWs *websocket.Conn
  94. TargetWs *websocket.Conn
  95. InputAudioFormat string
  96. OutputAudioFormat string
  97. RealtimeTools []dto.RealTimeTool
  98. IsFirstRequest bool
  99. AudioUsage bool
  100. ReasoningEffort string
  101. UserSetting dto.UserSetting
  102. UserEmail string
  103. UserQuota int
  104. RelayFormat types.RelayFormat
  105. SendResponseCount int
  106. ReceivedResponseCount int
  107. FinalPreConsumedQuota int // 最终预消耗的配额
  108. // ForcePreConsume 为 true 时禁用 BillingSession 的信任额度旁路,
  109. // 强制预扣全额。用于异步任务(视频/音乐生成等),因为请求返回后任务仍在运行,
  110. // 必须在提交前锁定全额。
  111. ForcePreConsume bool
  112. // Billing 是计费会话,封装了预扣费/结算/退款的统一生命周期。
  113. // 免费模型时为 nil。
  114. Billing BillingSettler
  115. // BillingSource indicates whether this request is billed from wallet quota or subscription.
  116. // "" or "wallet" => wallet; "subscription" => subscription
  117. BillingSource string
  118. // SubscriptionId is the user_subscriptions.id used when BillingSource == "subscription"
  119. SubscriptionId int
  120. // SubscriptionPreConsumed is the amount pre-consumed on subscription item (quota units or 1)
  121. SubscriptionPreConsumed int64
  122. // SubscriptionPostDelta is the post-consume delta applied to amount_used (quota units; can be negative).
  123. SubscriptionPostDelta int64
  124. // SubscriptionPlanId / SubscriptionPlanTitle are used for logging/UI display.
  125. SubscriptionPlanId int
  126. SubscriptionPlanTitle string
  127. // RequestId is used for idempotent pre-consume/refund
  128. RequestId string
  129. // SubscriptionAmountTotal / SubscriptionAmountUsedAfterPreConsume are used to compute remaining in logs.
  130. SubscriptionAmountTotal int64
  131. SubscriptionAmountUsedAfterPreConsume int64
  132. IsClaudeBetaQuery bool // /v1/messages?beta=true
  133. IsChannelTest bool // channel test request
  134. PriceData types.PriceData
  135. Request dto.Request
  136. // RequestConversionChain records request format conversions in order, e.g.
  137. // ["openai", "openai_responses"] or ["openai", "claude"].
  138. RequestConversionChain []types.RelayFormat
  139. // 最终请求到上游的格式 TODO: 当前仅设置了Claude
  140. FinalRequestRelayFormat types.RelayFormat
  141. ThinkingContentInfo
  142. TokenCountMeta
  143. *ClaudeConvertInfo
  144. *RerankerInfo
  145. *ResponsesUsageInfo
  146. *ChannelMeta
  147. *TaskRelayInfo
  148. }
  149. func (info *RelayInfo) InitChannelMeta(c *gin.Context) {
  150. channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
  151. paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
  152. headerOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelHeaderOverride)
  153. apiType, _ := common.ChannelType2APIType(channelType)
  154. channelMeta := &ChannelMeta{
  155. ChannelType: channelType,
  156. ChannelId: common.GetContextKeyInt(c, constant.ContextKeyChannelId),
  157. ChannelIsMultiKey: common.GetContextKeyBool(c, constant.ContextKeyChannelIsMultiKey),
  158. ChannelMultiKeyIndex: common.GetContextKeyInt(c, constant.ContextKeyChannelMultiKeyIndex),
  159. ChannelBaseUrl: common.GetContextKeyString(c, constant.ContextKeyChannelBaseUrl),
  160. ApiType: apiType,
  161. ApiVersion: c.GetString("api_version"),
  162. ApiKey: common.GetContextKeyString(c, constant.ContextKeyChannelKey),
  163. Organization: c.GetString("channel_organization"),
  164. ChannelCreateTime: c.GetInt64("channel_create_time"),
  165. ParamOverride: paramOverride,
  166. HeadersOverride: headerOverride,
  167. UpstreamModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  168. IsModelMapped: false,
  169. SupportStreamOptions: false,
  170. }
  171. if channelType == constant.ChannelTypeAzure {
  172. channelMeta.ApiVersion = GetAPIVersion(c)
  173. }
  174. if channelType == constant.ChannelTypeVertexAi {
  175. channelMeta.ApiVersion = c.GetString("region")
  176. }
  177. channelSetting, ok := common.GetContextKeyType[dto.ChannelSettings](c, constant.ContextKeyChannelSetting)
  178. if ok {
  179. channelMeta.ChannelSetting = channelSetting
  180. }
  181. channelOtherSettings, ok := common.GetContextKeyType[dto.ChannelOtherSettings](c, constant.ContextKeyChannelOtherSetting)
  182. if ok {
  183. channelMeta.ChannelOtherSettings = channelOtherSettings
  184. }
  185. if streamSupportedChannels[channelMeta.ChannelType] {
  186. channelMeta.SupportStreamOptions = true
  187. }
  188. info.ChannelMeta = channelMeta
  189. // reset some fields based on channel meta
  190. // 重置某些字段,例如模型名称等
  191. if info.Request != nil {
  192. info.Request.SetModelName(info.OriginModelName)
  193. }
  194. }
  195. func (info *RelayInfo) ToString() string {
  196. if info == nil {
  197. return "RelayInfo<nil>"
  198. }
  199. // Basic info
  200. b := &strings.Builder{}
  201. fmt.Fprintf(b, "RelayInfo{ ")
  202. fmt.Fprintf(b, "RelayFormat: %s, ", info.RelayFormat)
  203. fmt.Fprintf(b, "RelayMode: %d, ", info.RelayMode)
  204. fmt.Fprintf(b, "IsStream: %t, ", info.IsStream)
  205. fmt.Fprintf(b, "IsPlayground: %t, ", info.IsPlayground)
  206. fmt.Fprintf(b, "RequestURLPath: %q, ", info.RequestURLPath)
  207. fmt.Fprintf(b, "OriginModelName: %q, ", info.OriginModelName)
  208. fmt.Fprintf(b, "EstimatePromptTokens: %d, ", info.estimatePromptTokens)
  209. fmt.Fprintf(b, "ShouldIncludeUsage: %t, ", info.ShouldIncludeUsage)
  210. fmt.Fprintf(b, "DisablePing: %t, ", info.DisablePing)
  211. fmt.Fprintf(b, "SendResponseCount: %d, ", info.SendResponseCount)
  212. fmt.Fprintf(b, "FinalPreConsumedQuota: %d, ", info.FinalPreConsumedQuota)
  213. // User & token info (mask secrets)
  214. fmt.Fprintf(b, "User{ Id: %d, Email: %q, Group: %q, UsingGroup: %q, Quota: %d }, ",
  215. info.UserId, common.MaskEmail(info.UserEmail), info.UserGroup, info.UsingGroup, info.UserQuota)
  216. fmt.Fprintf(b, "Token{ Id: %d, Unlimited: %t, Key: ***masked*** }, ", info.TokenId, info.TokenUnlimited)
  217. // Time info
  218. latencyMs := info.FirstResponseTime.Sub(info.StartTime).Milliseconds()
  219. fmt.Fprintf(b, "Timing{ Start: %s, FirstResponse: %s, LatencyMs: %d }, ",
  220. info.StartTime.Format(time.RFC3339Nano), info.FirstResponseTime.Format(time.RFC3339Nano), latencyMs)
  221. // Audio / realtime
  222. if info.InputAudioFormat != "" || info.OutputAudioFormat != "" || len(info.RealtimeTools) > 0 || info.AudioUsage {
  223. fmt.Fprintf(b, "Realtime{ AudioUsage: %t, InFmt: %q, OutFmt: %q, Tools: %d }, ",
  224. info.AudioUsage, info.InputAudioFormat, info.OutputAudioFormat, len(info.RealtimeTools))
  225. }
  226. // Reasoning
  227. if info.ReasoningEffort != "" {
  228. fmt.Fprintf(b, "ReasoningEffort: %q, ", info.ReasoningEffort)
  229. }
  230. // Price data (non-sensitive)
  231. if info.PriceData.UsePrice {
  232. fmt.Fprintf(b, "PriceData{ %s }, ", info.PriceData.ToSetting())
  233. }
  234. // Channel metadata (mask ApiKey)
  235. if info.ChannelMeta != nil {
  236. cm := info.ChannelMeta
  237. fmt.Fprintf(b, "ChannelMeta{ Type: %d, Id: %d, IsMultiKey: %t, MultiKeyIndex: %d, BaseURL: %q, ApiType: %d, ApiVersion: %q, Organization: %q, CreateTime: %d, UpstreamModelName: %q, IsModelMapped: %t, SupportStreamOptions: %t, ApiKey: ***masked*** }, ",
  238. cm.ChannelType, cm.ChannelId, cm.ChannelIsMultiKey, cm.ChannelMultiKeyIndex, cm.ChannelBaseUrl, cm.ApiType, cm.ApiVersion, cm.Organization, cm.ChannelCreateTime, cm.UpstreamModelName, cm.IsModelMapped, cm.SupportStreamOptions)
  239. }
  240. // Responses usage info (non-sensitive)
  241. if info.ResponsesUsageInfo != nil && len(info.ResponsesUsageInfo.BuiltInTools) > 0 {
  242. fmt.Fprintf(b, "ResponsesTools{ ")
  243. first := true
  244. for name, tool := range info.ResponsesUsageInfo.BuiltInTools {
  245. if !first {
  246. fmt.Fprintf(b, ", ")
  247. }
  248. first = false
  249. if tool != nil {
  250. fmt.Fprintf(b, "%s: calls=%d", name, tool.CallCount)
  251. } else {
  252. fmt.Fprintf(b, "%s: calls=0", name)
  253. }
  254. }
  255. fmt.Fprintf(b, " }, ")
  256. }
  257. fmt.Fprintf(b, "}")
  258. return b.String()
  259. }
  260. // 定义支持流式选项的通道类型
  261. var streamSupportedChannels = map[int]bool{
  262. constant.ChannelTypeOpenAI: true,
  263. constant.ChannelTypeAnthropic: true,
  264. constant.ChannelTypeAws: true,
  265. constant.ChannelTypeGemini: true,
  266. constant.ChannelCloudflare: true,
  267. constant.ChannelTypeAzure: true,
  268. constant.ChannelTypeVolcEngine: true,
  269. constant.ChannelTypeOllama: true,
  270. constant.ChannelTypeXai: true,
  271. constant.ChannelTypeDeepSeek: true,
  272. constant.ChannelTypeBaiduV2: true,
  273. constant.ChannelTypeZhipu_v4: true,
  274. constant.ChannelTypeAli: true,
  275. constant.ChannelTypeSubmodel: true,
  276. constant.ChannelTypeCodex: true,
  277. constant.ChannelTypeMoonshot: true,
  278. constant.ChannelTypeMiniMax: true,
  279. constant.ChannelTypeSiliconFlow: true,
  280. }
  281. func GenRelayInfoWs(c *gin.Context, ws *websocket.Conn) *RelayInfo {
  282. info := genBaseRelayInfo(c, nil)
  283. info.RelayFormat = types.RelayFormatOpenAIRealtime
  284. info.ClientWs = ws
  285. info.InputAudioFormat = "pcm16"
  286. info.OutputAudioFormat = "pcm16"
  287. info.IsFirstRequest = true
  288. return info
  289. }
  290. func GenRelayInfoClaude(c *gin.Context, request dto.Request) *RelayInfo {
  291. info := genBaseRelayInfo(c, request)
  292. info.RelayFormat = types.RelayFormatClaude
  293. info.ShouldIncludeUsage = false
  294. info.ClaudeConvertInfo = &ClaudeConvertInfo{
  295. LastMessagesType: LastMessageTypeNone,
  296. }
  297. info.IsClaudeBetaQuery = c.Query("beta") == "true" || isClaudeBetaForced(c)
  298. return info
  299. }
  300. func isClaudeBetaForced(c *gin.Context) bool {
  301. channelOtherSettings, ok := common.GetContextKeyType[dto.ChannelOtherSettings](c, constant.ContextKeyChannelOtherSetting)
  302. return ok && channelOtherSettings.ClaudeBetaQuery
  303. }
  304. func GenRelayInfoRerank(c *gin.Context, request *dto.RerankRequest) *RelayInfo {
  305. info := genBaseRelayInfo(c, request)
  306. info.RelayMode = relayconstant.RelayModeRerank
  307. info.RelayFormat = types.RelayFormatRerank
  308. info.RerankerInfo = &RerankerInfo{
  309. Documents: request.Documents,
  310. ReturnDocuments: request.GetReturnDocuments(),
  311. }
  312. return info
  313. }
  314. func GenRelayInfoOpenAIAudio(c *gin.Context, request dto.Request) *RelayInfo {
  315. info := genBaseRelayInfo(c, request)
  316. info.RelayFormat = types.RelayFormatOpenAIAudio
  317. return info
  318. }
  319. func GenRelayInfoEmbedding(c *gin.Context, request dto.Request) *RelayInfo {
  320. info := genBaseRelayInfo(c, request)
  321. info.RelayFormat = types.RelayFormatEmbedding
  322. return info
  323. }
  324. func GenRelayInfoResponses(c *gin.Context, request *dto.OpenAIResponsesRequest) *RelayInfo {
  325. info := genBaseRelayInfo(c, request)
  326. info.RelayMode = relayconstant.RelayModeResponses
  327. info.RelayFormat = types.RelayFormatOpenAIResponses
  328. info.ResponsesUsageInfo = &ResponsesUsageInfo{
  329. BuiltInTools: make(map[string]*BuildInToolInfo),
  330. }
  331. if len(request.Tools) > 0 {
  332. for _, tool := range request.GetToolsMap() {
  333. toolType := common.Interface2String(tool["type"])
  334. info.ResponsesUsageInfo.BuiltInTools[toolType] = &BuildInToolInfo{
  335. ToolName: toolType,
  336. CallCount: 0,
  337. }
  338. switch toolType {
  339. case dto.BuildInToolWebSearchPreview:
  340. searchContextSize := common.Interface2String(tool["search_context_size"])
  341. if searchContextSize == "" {
  342. searchContextSize = "medium"
  343. }
  344. info.ResponsesUsageInfo.BuiltInTools[toolType].SearchContextSize = searchContextSize
  345. }
  346. }
  347. }
  348. return info
  349. }
  350. func GenRelayInfoGemini(c *gin.Context, request dto.Request) *RelayInfo {
  351. info := genBaseRelayInfo(c, request)
  352. info.RelayFormat = types.RelayFormatGemini
  353. info.ShouldIncludeUsage = false
  354. return info
  355. }
  356. func GenRelayInfoImage(c *gin.Context, request dto.Request) *RelayInfo {
  357. info := genBaseRelayInfo(c, request)
  358. info.RelayFormat = types.RelayFormatOpenAIImage
  359. return info
  360. }
  361. func GenRelayInfoOpenAI(c *gin.Context, request dto.Request) *RelayInfo {
  362. info := genBaseRelayInfo(c, request)
  363. info.RelayFormat = types.RelayFormatOpenAI
  364. return info
  365. }
  366. func genBaseRelayInfo(c *gin.Context, request dto.Request) *RelayInfo {
  367. //channelType := common.GetContextKeyInt(c, constant.ContextKeyChannelType)
  368. //channelId := common.GetContextKeyInt(c, constant.ContextKeyChannelId)
  369. //paramOverride := common.GetContextKeyStringMap(c, constant.ContextKeyChannelParamOverride)
  370. tokenGroup := common.GetContextKeyString(c, constant.ContextKeyTokenGroup)
  371. // 当令牌分组为空时,表示使用用户分组
  372. if tokenGroup == "" {
  373. tokenGroup = common.GetContextKeyString(c, constant.ContextKeyUserGroup)
  374. }
  375. startTime := common.GetContextKeyTime(c, constant.ContextKeyRequestStartTime)
  376. if startTime.IsZero() {
  377. startTime = time.Now()
  378. }
  379. isStream := false
  380. if request != nil {
  381. isStream = request.IsStream(c)
  382. }
  383. // firstResponseTime = time.Now() - 1 second
  384. reqId := common.GetContextKeyString(c, common.RequestIdKey)
  385. if reqId == "" {
  386. reqId = common.GetTimeString() + common.GetRandomString(8)
  387. }
  388. info := &RelayInfo{
  389. Request: request,
  390. RequestId: reqId,
  391. UserId: common.GetContextKeyInt(c, constant.ContextKeyUserId),
  392. UsingGroup: common.GetContextKeyString(c, constant.ContextKeyUsingGroup),
  393. UserGroup: common.GetContextKeyString(c, constant.ContextKeyUserGroup),
  394. UserQuota: common.GetContextKeyInt(c, constant.ContextKeyUserQuota),
  395. UserEmail: common.GetContextKeyString(c, constant.ContextKeyUserEmail),
  396. OriginModelName: common.GetContextKeyString(c, constant.ContextKeyOriginalModel),
  397. TokenId: common.GetContextKeyInt(c, constant.ContextKeyTokenId),
  398. TokenKey: common.GetContextKeyString(c, constant.ContextKeyTokenKey),
  399. TokenUnlimited: common.GetContextKeyBool(c, constant.ContextKeyTokenUnlimited),
  400. TokenGroup: tokenGroup,
  401. isFirstResponse: true,
  402. RelayMode: relayconstant.Path2RelayMode(c.Request.URL.Path),
  403. RequestURLPath: c.Request.URL.String(),
  404. IsStream: isStream,
  405. StartTime: startTime,
  406. FirstResponseTime: startTime.Add(-time.Second),
  407. ThinkingContentInfo: ThinkingContentInfo{
  408. IsFirstThinkingContent: true,
  409. SendLastThinkingContent: false,
  410. },
  411. TokenCountMeta: TokenCountMeta{
  412. //promptTokens: common.GetContextKeyInt(c, constant.ContextKeyPromptTokens),
  413. estimatePromptTokens: common.GetContextKeyInt(c, constant.ContextKeyEstimatedTokens),
  414. },
  415. }
  416. if info.RelayMode == relayconstant.RelayModeUnknown {
  417. info.RelayMode = c.GetInt("relay_mode")
  418. }
  419. if strings.HasPrefix(c.Request.URL.Path, "/pg") {
  420. info.IsPlayground = true
  421. info.RequestURLPath = strings.TrimPrefix(info.RequestURLPath, "/pg")
  422. info.RequestURLPath = "/v1" + info.RequestURLPath
  423. }
  424. userSetting, ok := common.GetContextKeyType[dto.UserSetting](c, constant.ContextKeyUserSetting)
  425. if ok {
  426. info.UserSetting = userSetting
  427. }
  428. return info
  429. }
  430. func GenRelayInfo(c *gin.Context, relayFormat types.RelayFormat, request dto.Request, ws *websocket.Conn) (*RelayInfo, error) {
  431. var info *RelayInfo
  432. var err error
  433. switch relayFormat {
  434. case types.RelayFormatOpenAI:
  435. info = GenRelayInfoOpenAI(c, request)
  436. case types.RelayFormatOpenAIAudio:
  437. info = GenRelayInfoOpenAIAudio(c, request)
  438. case types.RelayFormatOpenAIImage:
  439. info = GenRelayInfoImage(c, request)
  440. case types.RelayFormatOpenAIRealtime:
  441. info = GenRelayInfoWs(c, ws)
  442. case types.RelayFormatClaude:
  443. info = GenRelayInfoClaude(c, request)
  444. case types.RelayFormatRerank:
  445. if request, ok := request.(*dto.RerankRequest); ok {
  446. info = GenRelayInfoRerank(c, request)
  447. break
  448. }
  449. err = errors.New("request is not a RerankRequest")
  450. case types.RelayFormatGemini:
  451. info = GenRelayInfoGemini(c, request)
  452. case types.RelayFormatEmbedding:
  453. info = GenRelayInfoEmbedding(c, request)
  454. case types.RelayFormatOpenAIResponses:
  455. if request, ok := request.(*dto.OpenAIResponsesRequest); ok {
  456. info = GenRelayInfoResponses(c, request)
  457. break
  458. }
  459. err = errors.New("request is not a OpenAIResponsesRequest")
  460. case types.RelayFormatOpenAIResponsesCompaction:
  461. if request, ok := request.(*dto.OpenAIResponsesCompactionRequest); ok {
  462. return GenRelayInfoResponsesCompaction(c, request), nil
  463. }
  464. return nil, errors.New("request is not a OpenAIResponsesCompactionRequest")
  465. case types.RelayFormatTask:
  466. info = genBaseRelayInfo(c, nil)
  467. info.TaskRelayInfo = &TaskRelayInfo{}
  468. case types.RelayFormatMjProxy:
  469. info = genBaseRelayInfo(c, nil)
  470. info.TaskRelayInfo = &TaskRelayInfo{}
  471. default:
  472. err = errors.New("invalid relay format")
  473. }
  474. if err != nil {
  475. return nil, err
  476. }
  477. if info == nil {
  478. return nil, errors.New("failed to build relay info")
  479. }
  480. info.InitRequestConversionChain()
  481. return info, nil
  482. }
  483. func (info *RelayInfo) InitRequestConversionChain() {
  484. if info == nil {
  485. return
  486. }
  487. if len(info.RequestConversionChain) > 0 {
  488. return
  489. }
  490. if info.RelayFormat == "" {
  491. return
  492. }
  493. info.RequestConversionChain = []types.RelayFormat{info.RelayFormat}
  494. }
  495. func (info *RelayInfo) AppendRequestConversion(format types.RelayFormat) {
  496. if info == nil {
  497. return
  498. }
  499. if format == "" {
  500. return
  501. }
  502. if len(info.RequestConversionChain) == 0 {
  503. info.RequestConversionChain = []types.RelayFormat{format}
  504. return
  505. }
  506. last := info.RequestConversionChain[len(info.RequestConversionChain)-1]
  507. if last == format {
  508. return
  509. }
  510. info.RequestConversionChain = append(info.RequestConversionChain, format)
  511. }
  512. func GenRelayInfoResponsesCompaction(c *gin.Context, request *dto.OpenAIResponsesCompactionRequest) *RelayInfo {
  513. info := genBaseRelayInfo(c, request)
  514. if info.RelayMode == relayconstant.RelayModeUnknown {
  515. info.RelayMode = relayconstant.RelayModeResponsesCompact
  516. }
  517. info.RelayFormat = types.RelayFormatOpenAIResponsesCompaction
  518. return info
  519. }
  520. //func (info *RelayInfo) SetPromptTokens(promptTokens int) {
  521. // info.promptTokens = promptTokens
  522. //}
  523. func (info *RelayInfo) SetEstimatePromptTokens(promptTokens int) {
  524. info.estimatePromptTokens = promptTokens
  525. }
  526. func (info *RelayInfo) GetEstimatePromptTokens() int {
  527. return info.estimatePromptTokens
  528. }
  529. func (info *RelayInfo) SetFirstResponseTime() {
  530. if info.isFirstResponse {
  531. info.FirstResponseTime = time.Now()
  532. info.isFirstResponse = false
  533. }
  534. }
  535. func (info *RelayInfo) HasSendResponse() bool {
  536. return info.FirstResponseTime.After(info.StartTime)
  537. }
  538. type TaskRelayInfo struct {
  539. Action string
  540. OriginTaskID string
  541. // PublicTaskID 是提交时预生成的 task_xxxx 格式公开 ID,
  542. // 供 DoResponse 在返回给客户端时使用(避免暴露上游真实 ID)。
  543. PublicTaskID string
  544. ConsumeQuota bool
  545. }
  546. type TaskSubmitReq struct {
  547. Prompt string `json:"prompt"`
  548. Model string `json:"model,omitempty"`
  549. Mode string `json:"mode,omitempty"`
  550. Image string `json:"image,omitempty"`
  551. Images []string `json:"images,omitempty"`
  552. Size string `json:"size,omitempty"`
  553. Duration int `json:"duration,omitempty"`
  554. Seconds string `json:"seconds,omitempty"`
  555. InputReference string `json:"input_reference,omitempty"`
  556. Metadata map[string]interface{} `json:"metadata,omitempty"`
  557. }
  558. func (t *TaskSubmitReq) GetPrompt() string {
  559. return t.Prompt
  560. }
  561. func (t *TaskSubmitReq) HasImage() bool {
  562. return len(t.Images) > 0
  563. }
  564. func (t *TaskSubmitReq) UnmarshalJSON(data []byte) error {
  565. type Alias TaskSubmitReq
  566. aux := &struct {
  567. Metadata json.RawMessage `json:"metadata,omitempty"`
  568. *Alias
  569. }{
  570. Alias: (*Alias)(t),
  571. }
  572. if err := common.Unmarshal(data, &aux); err != nil {
  573. return err
  574. }
  575. if len(aux.Metadata) > 0 {
  576. var metadataStr string
  577. if err := common.Unmarshal(aux.Metadata, &metadataStr); err == nil && metadataStr != "" {
  578. var metadataObj map[string]interface{}
  579. if err := common.Unmarshal([]byte(metadataStr), &metadataObj); err == nil {
  580. t.Metadata = metadataObj
  581. return nil
  582. }
  583. }
  584. var metadataObj map[string]interface{}
  585. if err := common.Unmarshal(aux.Metadata, &metadataObj); err == nil {
  586. t.Metadata = metadataObj
  587. }
  588. }
  589. return nil
  590. }
  591. func (t *TaskSubmitReq) UnmarshalMetadata(v any) error {
  592. metadata := t.Metadata
  593. if metadata != nil {
  594. metadataBytes, err := common.Marshal(metadata)
  595. if err != nil {
  596. return fmt.Errorf("marshal metadata failed: %w", err)
  597. }
  598. err = common.Unmarshal(metadataBytes, v)
  599. if err != nil {
  600. return fmt.Errorf("unmarshal metadata to target failed: %w", err)
  601. }
  602. }
  603. return nil
  604. }
  605. type TaskInfo struct {
  606. Code int `json:"code"`
  607. TaskID string `json:"task_id"`
  608. Status string `json:"status"`
  609. Reason string `json:"reason,omitempty"`
  610. Url string `json:"url,omitempty"`
  611. RemoteUrl string `json:"remote_url,omitempty"`
  612. Progress string `json:"progress,omitempty"`
  613. CompletionTokens int `json:"completion_tokens,omitempty"` // 用于按倍率计费
  614. TotalTokens int `json:"total_tokens,omitempty"` // 用于按倍率计费
  615. }
  616. func FailTaskInfo(reason string) *TaskInfo {
  617. return &TaskInfo{
  618. Status: "FAILURE",
  619. Reason: reason,
  620. }
  621. }
  622. // RemoveDisabledFields 从请求 JSON 数据中移除渠道设置中禁用的字段
  623. // service_tier: 服务层级字段,可能导致额外计费(OpenAI、Claude、Responses API 支持)
  624. // store: 数据存储授权字段,涉及用户隐私(仅 OpenAI、Responses API 支持,默认允许透传,禁用后可能导致 Codex 无法使用)
  625. // safety_identifier: 安全标识符,用于向 OpenAI 报告违规用户(仅 OpenAI 支持,涉及用户隐私)
  626. func RemoveDisabledFields(jsonData []byte, channelOtherSettings dto.ChannelOtherSettings) ([]byte, error) {
  627. var data map[string]interface{}
  628. if err := common.Unmarshal(jsonData, &data); err != nil {
  629. common.SysError("RemoveDisabledFields Unmarshal error :" + err.Error())
  630. return jsonData, nil
  631. }
  632. // 默认移除 service_tier,除非明确允许(避免额外计费风险)
  633. if !channelOtherSettings.AllowServiceTier {
  634. if _, exists := data["service_tier"]; exists {
  635. delete(data, "service_tier")
  636. }
  637. }
  638. // 默认允许 store 透传,除非明确禁用(禁用可能影响 Codex 使用)
  639. if channelOtherSettings.DisableStore {
  640. if _, exists := data["store"]; exists {
  641. delete(data, "store")
  642. }
  643. }
  644. // 默认移除 safety_identifier,除非明确允许(保护用户隐私,避免向 OpenAI 报告用户信息)
  645. if !channelOtherSettings.AllowSafetyIdentifier {
  646. if _, exists := data["safety_identifier"]; exists {
  647. delete(data, "safety_identifier")
  648. }
  649. }
  650. jsonDataAfter, err := common.Marshal(data)
  651. if err != nil {
  652. common.SysError("RemoveDisabledFields Marshal error :" + err.Error())
  653. return jsonData, nil
  654. }
  655. return jsonDataAfter, nil
  656. }
  657. // RemoveGeminiDisabledFields removes disabled fields from Gemini request JSON data
  658. // Currently supports removing functionResponse.id field which Vertex AI does not support
  659. func RemoveGeminiDisabledFields(jsonData []byte) ([]byte, error) {
  660. if !model_setting.GetGeminiSettings().RemoveFunctionResponseIdEnabled {
  661. return jsonData, nil
  662. }
  663. var data map[string]interface{}
  664. if err := common.Unmarshal(jsonData, &data); err != nil {
  665. common.SysError("RemoveGeminiDisabledFields Unmarshal error: " + err.Error())
  666. return jsonData, nil
  667. }
  668. // Process contents array
  669. // Handle both camelCase (functionResponse) and snake_case (function_response)
  670. if contents, ok := data["contents"].([]interface{}); ok {
  671. for _, content := range contents {
  672. if contentMap, ok := content.(map[string]interface{}); ok {
  673. if parts, ok := contentMap["parts"].([]interface{}); ok {
  674. for _, part := range parts {
  675. if partMap, ok := part.(map[string]interface{}); ok {
  676. // Check functionResponse (camelCase)
  677. if funcResp, ok := partMap["functionResponse"].(map[string]interface{}); ok {
  678. delete(funcResp, "id")
  679. }
  680. // Check function_response (snake_case)
  681. if funcResp, ok := partMap["function_response"].(map[string]interface{}); ok {
  682. delete(funcResp, "id")
  683. }
  684. }
  685. }
  686. }
  687. }
  688. }
  689. }
  690. jsonDataAfter, err := common.Marshal(data)
  691. if err != nil {
  692. common.SysError("RemoveGeminiDisabledFields Marshal error: " + err.Error())
  693. return jsonData, nil
  694. }
  695. return jsonDataAfter, nil
  696. }