Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

878 строки
29 KiB

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