relay_info.go 28 KB

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