upstream_response_model.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. package service
  2. import (
  3. "strings"
  4. "github.com/gin-gonic/gin"
  5. "github.com/tidwall/gjson"
  6. )
  7. const (
  8. upstreamResponseModelObserverContextKey = "upstream_response_model_observer"
  9. upstreamResponseModelMaxLength = 200
  10. )
  11. // upstreamResponseModelObserver tracks one forwarding attempt (or one WS turn).
  12. // A terminal declaration wins over an earlier declaration; otherwise the first
  13. // declaration is retained. Observation never affects the forwarding path.
  14. //
  15. // Billing normally ignores the observed model as well; the only exception is a
  16. // channel explicitly configured with billing_model_source = response_model,
  17. // where a conflict flag makes billing fall back to the baseline model
  18. // (see responseModelBillingDeclaration).
  19. //
  20. // The same observer also records the service tier the upstream reports having
  21. // used (OpenAI service_tier, Anthropic usage.speed). The observed tier stays
  22. // separate from the final outbound request tier until usage recording resolves
  23. // the billable tier for the selected credential protocol.
  24. type upstreamResponseModelObserver struct {
  25. first string
  26. terminal string
  27. conflict bool
  28. // firstTier holds the first non-terminal tier declaration; it is discarded
  29. // when later non-terminal declarations disagree. terminalTier comes from a
  30. // terminal event and always wins.
  31. firstTier string
  32. firstTierConflict bool
  33. terminalTier string
  34. }
  35. func (o *upstreamResponseModelObserver) Observe(model string, terminal bool) {
  36. model = normalizeObservedUpstreamResponseModel(model)
  37. if model == "" {
  38. return
  39. }
  40. current := o.Model()
  41. if current != "" && !strings.EqualFold(current, model) {
  42. o.conflict = true
  43. }
  44. if terminal {
  45. o.terminal = model
  46. return
  47. }
  48. if o.first == "" {
  49. o.first = model
  50. }
  51. }
  52. func normalizeObservedUpstreamResponseModel(model string) string {
  53. model = strings.TrimSpace(model)
  54. if model == "" {
  55. return ""
  56. }
  57. runes := []rune(model)
  58. if len(runes) > upstreamResponseModelMaxLength {
  59. model = string(runes[:upstreamResponseModelMaxLength])
  60. }
  61. return model
  62. }
  63. func (o *upstreamResponseModelObserver) ObserveOpenAI(payload []byte, eventType string) {
  64. model := firstValidTrimmedGJSONString(payload, "response.model", "model")
  65. terminal := isUpstreamResponseModelTerminalEvent(eventType)
  66. o.Observe(model, terminal)
  67. // Every payload that declares a service tier also declares a model, so
  68. // model-free delta frames skip the extra lookups entirely.
  69. if model == "" {
  70. return
  71. }
  72. // Non-terminal Responses API events echo the requested tier rather than the
  73. // tier actually used. Only terminal events and untyped payloads (chat
  74. // completions chunks, non-streaming bodies) report the processing tier.
  75. if !terminal && strings.TrimSpace(eventType) != "" {
  76. return
  77. }
  78. tier := normalizeObservedOpenAIServiceTier(firstValidTrimmedGJSONString(payload, "response.service_tier", "service_tier"))
  79. o.ObserveServiceTier(tier, terminal)
  80. }
  81. func (o *upstreamResponseModelObserver) ObserveAnthropic(payload []byte) {
  82. model := firstValidTrimmedGJSONString(payload, "message.model", "model")
  83. o.Observe(model, false)
  84. // usage.speed travels with the message object (message_start in streams,
  85. // the top-level body otherwise), i.e. only in payloads that declare a model.
  86. if model == "" {
  87. return
  88. }
  89. tier := normalizeObservedAnthropicSpeed(firstValidTrimmedGJSONString(payload, "message.usage.speed", "usage.speed"))
  90. o.ObserveServiceTier(tier, false)
  91. }
  92. // ObserveServiceTier records a tier declared by the upstream response. A
  93. // terminal declaration always wins; non-terminal declarations are only trusted
  94. // when they agree with each other.
  95. func (o *upstreamResponseModelObserver) ObserveServiceTier(tier string, terminal bool) {
  96. if o == nil || tier == "" {
  97. return
  98. }
  99. if terminal {
  100. o.terminalTier = tier
  101. return
  102. }
  103. if o.firstTier == "" {
  104. o.firstTier = tier
  105. return
  106. }
  107. if o.firstTier != tier {
  108. o.firstTierConflict = true
  109. }
  110. }
  111. // ServiceTier returns the tier the upstream reports having used, or "" when the
  112. // response never declared one unambiguously.
  113. func (o *upstreamResponseModelObserver) ServiceTier() string {
  114. if o == nil {
  115. return ""
  116. }
  117. if o.terminalTier != "" {
  118. return o.terminalTier
  119. }
  120. if o.firstTierConflict {
  121. return ""
  122. }
  123. return o.firstTier
  124. }
  125. // normalizeObservedOpenAIServiceTier maps a tier reported by an OpenAI response
  126. // onto the billing vocabulary. "auto" never describes a processing tier and
  127. // unknown values are ignored rather than guessed at.
  128. func normalizeObservedOpenAIServiceTier(raw string) string {
  129. switch value := strings.ToLower(strings.TrimSpace(raw)); value {
  130. case "priority", "fast":
  131. return OpenAIFastTierPriority
  132. case "default", "flex", "scale":
  133. return value
  134. default:
  135. return ""
  136. }
  137. }
  138. // normalizeObservedAnthropicSpeed maps Anthropic usage.speed onto the billing
  139. // vocabulary: "fast" is the billable fast-mode tier, "standard" the base rate.
  140. func normalizeObservedAnthropicSpeed(raw string) string {
  141. switch value := strings.ToLower(strings.TrimSpace(raw)); value {
  142. case "fast", "standard":
  143. return value
  144. default:
  145. return ""
  146. }
  147. }
  148. func (o *upstreamResponseModelObserver) ObserveGemini(payload []byte) {
  149. model := firstValidTrimmedGJSONString(
  150. payload,
  151. "modelVersion",
  152. "response.modelVersion",
  153. "response.response.modelVersion",
  154. )
  155. // Gemini streaming has no universal terminal event carrying modelVersion;
  156. // treating each declaration as terminal retains the latest chunk.
  157. o.Observe(model, true)
  158. }
  159. func (o *upstreamResponseModelObserver) Model() string {
  160. if o == nil {
  161. return ""
  162. }
  163. if o.terminal != "" {
  164. return o.terminal
  165. }
  166. return o.first
  167. }
  168. func (o *upstreamResponseModelObserver) Conflict() bool {
  169. return o != nil && o.conflict
  170. }
  171. func beginUpstreamResponseModelObservation(c *gin.Context) *upstreamResponseModelObserver {
  172. observer := &upstreamResponseModelObserver{}
  173. if c != nil {
  174. c.Set(upstreamResponseModelObserverContextKey, observer)
  175. }
  176. return observer
  177. }
  178. func upstreamResponseModelObserverFromContext(c *gin.Context) *upstreamResponseModelObserver {
  179. if c == nil {
  180. return nil
  181. }
  182. value, ok := c.Get(upstreamResponseModelObserverContextKey)
  183. if !ok {
  184. return nil
  185. }
  186. observer, _ := value.(*upstreamResponseModelObserver)
  187. return observer
  188. }
  189. func observedUpstreamResponseModel(c *gin.Context) string {
  190. return upstreamResponseModelObserverFromContext(c).Model()
  191. }
  192. func observedUpstreamResponseModelConflict(c *gin.Context) bool {
  193. return upstreamResponseModelObserverFromContext(c).Conflict()
  194. }
  195. func observedUpstreamResponseServiceTier(c *gin.Context) string {
  196. return upstreamResponseModelObserverFromContext(c).ServiceTier()
  197. }
  198. // resolvedOpenAIUpstreamServiceTierFromObserver preserves the final outbound
  199. // request tier. The observed response tier remains separate on
  200. // OpenAIForwardResult.UpstreamResponseServiceTier and is reconciled once, at
  201. // usage time, where the account protocol is available. In particular, the
  202. // private ChatGPT Codex backend commonly reports default even for effective
  203. // Fast turns, while public API response tiers remain authoritative.
  204. func resolvedOpenAIUpstreamServiceTierFromObserver(_ *upstreamResponseModelObserver, outboundBodyTier *string) *string {
  205. return outboundBodyTier
  206. }
  207. func resolvedOpenAIUpstreamServiceTier(c *gin.Context, outboundBodyTier *string) *string {
  208. return resolvedOpenAIUpstreamServiceTierFromObserver(upstreamResponseModelObserverFromContext(c), outboundBodyTier)
  209. }
  210. func observeOpenAISSEBody(observer *upstreamResponseModelObserver, body string) {
  211. if observer == nil || strings.TrimSpace(body) == "" {
  212. return
  213. }
  214. forEachOpenAISSEFrame(body, func(eventType string, payload []byte) {
  215. observer.ObserveOpenAI(payload, eventType)
  216. })
  217. }
  218. func firstValidTrimmedGJSONString(payload []byte, paths ...string) string {
  219. if len(payload) == 0 {
  220. return ""
  221. }
  222. for _, path := range paths {
  223. value := gjson.GetBytes(payload, path)
  224. if !value.Exists() || value.Type != gjson.String {
  225. continue
  226. }
  227. if text := strings.TrimSpace(value.String()); text != "" {
  228. // Validate only after finding a candidate. This avoids a full validation
  229. // pass on the common model-free delta path while still rejecting malformed
  230. // payloads that appear to declare a value.
  231. if !gjson.ValidBytes(payload) {
  232. return ""
  233. }
  234. return text
  235. }
  236. }
  237. return ""
  238. }
  239. func isUpstreamResponseModelTerminalEvent(eventType string) bool {
  240. switch strings.TrimSpace(eventType) {
  241. case "response.completed", "response.done", "response.failed", "response.incomplete", "response.cancelled", "response.canceled":
  242. return true
  243. default:
  244. return false
  245. }
  246. }
  247. func upstreamModelMismatch(sentModel, responseModel string) *bool {
  248. responseModel = strings.TrimSpace(responseModel)
  249. if responseModel == "" {
  250. return nil
  251. }
  252. sentModel = strings.TrimSpace(sentModel)
  253. mismatch := sentModel == "" || !upstreamModelsMatchForAudit(sentModel, responseModel)
  254. return &mismatch
  255. }
  256. func upstreamModelsMatchForAudit(sentModel, responseModel string) bool {
  257. if strings.EqualFold(sentModel, responseModel) {
  258. return true
  259. }
  260. // xAI reports the runtime build ID for these supported public aliases.
  261. // Canonicalize only for mismatch auditing; keep the raw response model for
  262. // observability and for the separate response-model billing safeguards.
  263. sentGrokModel := canonicalGrokBuildRuntimeModel(sentModel)
  264. return sentGrokModel != "" && sentGrokModel == canonicalGrokBuildRuntimeModel(responseModel)
  265. }
  266. func canonicalGrokBuildRuntimeModel(model string) string {
  267. switch strings.ToLower(strings.TrimSpace(model)) {
  268. case "grok-4.5", "grok-4.5-latest", "grok-4.5-build":
  269. return "grok-4.5-build"
  270. case "grok-4.6", "grok-4.6-latest", "grok-4.6-build":
  271. return "grok-4.6-build"
  272. default:
  273. return ""
  274. }
  275. }
  276. func upstreamSentModel(requestedModel, upstreamModel string) string {
  277. sentModel := strings.TrimSpace(upstreamModel)
  278. if sentModel == "" {
  279. sentModel = strings.TrimSpace(requestedModel)
  280. }
  281. return sentModel
  282. }