Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 113 additions & 16 deletions core/providers/gemini/count_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,81 @@ package gemini
import (
"strings"

providerUtils "github.com/maximhq/bifrost/core/providers/utils"
"github.com/maximhq/bifrost/core/schemas"
)

// countTokensEnvelopeField is the only place the Gemini countTokens endpoint reads
// systemInstruction, tools, toolConfig and generationConfig from. They are rejected
// at the top level, and a top-level contents/model is silently ignored once this is
// set, so the body must carry the envelope and nothing beside it.
const countTokensEnvelopeField = "generateContentRequest"

// geminiCountTokensUnsupportedFields lists fields absent from GenerateContentRequest,
// which the endpoint therefore rejects even inside the envelope.
var geminiCountTokensUnsupportedFields = []string{
"labels",
"fallbacks",
}

// wrapGeminiCountTokensBody rewrites a generateContent body into the countTokens
// envelope so the whole prompt is counted, not just contents. Bodies that already
// arrive wrapped (the shape Gemini documents) are reduced to the envelope alone.
func wrapGeminiCountTokensBody(jsonData []byte, model string) []byte {
if len(jsonData) == 0 {
return jsonData
}

inner := jsonData
if envelope := providerUtils.GetJSONField(jsonData, countTokensEnvelopeField); envelope.Exists() {
inner = []byte(envelope.Raw)
}

for _, field := range geminiCountTokensUnsupportedFields {
if updated, err := providerUtils.DeleteJSONField(inner, field); err == nil {
inner = updated
}
}

// generateContentRequest.model is required and must be fully qualified.
if model = NormalizeModelName(model); model != "" {
if updated, err := providerUtils.SetJSONField(inner, "model", "models/"+strings.TrimPrefix(model, "models/")); err == nil {
inner = updated
}
}

wrapped, err := providerUtils.SetRawJSONField([]byte(`{}`), countTokensEnvelopeField, inner)
if err != nil {
return jsonData
}
return wrapped
}

// ToGeminiGenerationRequest flattens a count tokens request into the generation request
// shape. Top-level contents is dropped when the envelope is present, matching the
// endpoint's own precedence rather than silently merging two sources of truth.
func (request *GeminiCountTokensRequest) ToGeminiGenerationRequest() *GeminiGenerationRequest {
if request == nil {
return nil
}

// Copy rather than alias: the routing fields below are ours to set, and the parsed
// request has to come out of this converter unchanged.
generationRequest := request.GeminiGenerationRequest
if request.GenerateContentRequest != nil {
generationRequest = *request.GenerateContentRequest
}
// The path model is authoritative, and fallbacks is a Bifrost field callers set
// beside the envelope rather than inside it.
generationRequest.Model = request.Model
if len(request.Fallbacks) > 0 {
generationRequest.Fallbacks = request.Fallbacks
}
generationRequest.IsCountTokens = true

return &generationRequest
}

// ToBifrostCountTokensResponse converts a Gemini count tokens response to Bifrost format.
func (resp *GeminiCountTokensResponse) ToBifrostCountTokensResponse(model string) *schemas.BifrostCountTokensResponse {
if resp == nil {
Expand All @@ -21,28 +93,21 @@ func (resp *GeminiCountTokensResponse) ToBifrostCountTokensResponse(model string
continue
}
inputTokens += int(m.TokenCount)
mod := strings.ToLower(string(m.Modality))
// handle audio modality
if strings.Contains(mod, "audio") {
inputDetails.AudioTokens += int(m.TokenCount)
}
AddModalityTokens(inputDetails, string(m.Modality), int(m.TokenCount))
}

// Set cached tokens from top-level field if present
// Cached tokens are part of the prompt, not extra: promptTokensDetails already
// counts them, so cacheTokensDetails only says how much of that was cached and
// must not be added to the modality breakdown again.
if resp.CachedContentTokenCount != 0 {
inputDetails.CachedReadTokens = int(resp.CachedContentTokenCount)
} else if resp.CacheTokensDetails != nil {
// If cache tokens details present, sum them
} else {
cachedSum := 0
for _, m := range resp.CacheTokensDetails {
if m == nil {
continue
}
cachedSum += int(m.TokenCount)
if strings.Contains(strings.ToLower(string(m.Modality)), "audio") {
// also populate audio tokens from cache into AudioTokens (additive)
inputDetails.AudioTokens += int(m.TokenCount)
}
}
inputDetails.CachedReadTokens = cachedSum
Comment thread
TejasGhatte marked this conversation as resolved.
Resolved
}
Expand All @@ -59,6 +124,18 @@ func (resp *GeminiCountTokensResponse) ToBifrostCountTokensResponse(model string
}
}

// AddModalityTokens accumulates a Gemini modality token count into the neutral details.
func AddModalityTokens(details *schemas.ResponsesResponseInputTokens, modality string, count int) {
switch mod := strings.ToLower(modality); {
case strings.Contains(mod, "audio"):
details.AudioTokens += count
case strings.Contains(mod, "image"), strings.Contains(mod, "video"):
details.ImageTokens += count
default:
details.TextTokens += count
}
}

// ToGeminiCountTokensResponse converts a Bifrost count tokens response to Gemini format.
func ToGeminiCountTokensResponse(bifrostResp *schemas.BifrostCountTokensResponse) *GeminiCountTokensResponse {
if bifrostResp == nil {
Expand All @@ -68,12 +145,32 @@ func ToGeminiCountTokensResponse(bifrostResp *schemas.BifrostCountTokensResponse
response := &GeminiCountTokensResponse{
TotalTokens: int32(bifrostResp.InputTokens),
}
if bifrostResp.TotalTokens != nil && *bifrostResp.TotalTokens > 0 {
response.TotalTokens = int32(*bifrostResp.TotalTokens)
}

details := bifrostResp.InputTokensDetails
if details == nil {
return response
}

// Map cached content token count if available
if bifrostResp.InputTokensDetails != nil && bifrostResp.InputTokensDetails.CachedReadTokens > 0 {
response.CachedContentTokenCount = int32(bifrostResp.InputTokensDetails.CachedReadTokens)
} else {
response.CachedContentTokenCount = 0
response.CachedContentTokenCount = int32(details.CachedReadTokens)

for _, m := range []struct {
modality Modality
count int
}{
{ModalityText, details.TextTokens},
{ModalityImage, details.ImageTokens},
{ModalityAudio, details.AudioTokens},
} {
if m.count > 0 {
response.PromptTokensDetails = append(response.PromptTokensDetails, &ModalityTokenCount{
Modality: m.modality,
TokenCount: int32(m.count),
})
}
}

return response
Expand Down
20 changes: 8 additions & 12 deletions core/providers/gemini/gemini.go
Original file line number Diff line number Diff line change
Expand Up @@ -3899,6 +3899,13 @@ func (provider *GeminiProvider) CountTokens(ctx *schemas.BifrostContext, key sch
isLargePayload = true
}

if strings.TrimSpace(request.Model) == "" {
return nil, providerUtils.NewBifrostOperationError("model is required for Gemini count tokens request", fmt.Errorf("missing model"))
}

// Determine native model name (e.g., parse any provider prefix)
_, model := schemas.ParseModelString(request.Model, schemas.Gemini)

var (
jsonData []byte
bifrostErr *schemas.BifrostError
Expand All @@ -3917,25 +3924,14 @@ func (provider *GeminiProvider) CountTokens(ctx *schemas.BifrostContext, key sch
}

jsonData = normalizeRawGenerateContentBody(ctx, jsonData)

// Use sjson to delete fields directly from JSON bytes, preserving key ordering
jsonData, _ = providerUtils.DeleteJSONField(jsonData, "toolConfig")
jsonData, _ = providerUtils.DeleteJSONField(jsonData, "generationConfig")
jsonData, _ = providerUtils.DeleteJSONField(jsonData, "systemInstruction")
jsonData = wrapGeminiCountTokensBody(jsonData, model)
}

req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
defer fasthttp.ReleaseRequest(req)
defer fasthttp.ReleaseResponse(resp)

if strings.TrimSpace(request.Model) == "" {
return nil, providerUtils.NewBifrostOperationError("model is required for Gemini count tokens request", fmt.Errorf("missing model"))
}

// Determine native model name (e.g., parse any provider prefix)
_, model := schemas.ParseModelString(request.Model, schemas.Gemini)

providerUtils.SetExtraHeaders(ctx, req, provider.networkConfig.ExtraHeaders, nil)
path := fmt.Sprintf("/models/%s:countTokens", model)
req.SetRequestURI(provider.networkConfig.BaseURL + providerUtils.GetPathFromContext(ctx, path))
Expand Down
175 changes: 175 additions & 0 deletions core/providers/gemini/payload_ordering_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gemini

import (
"encoding/json"
"testing"

providerUtils "github.com/maximhq/bifrost/core/providers/utils"
Expand Down Expand Up @@ -80,3 +81,177 @@ func TestNormalizeRawGenerateContentRequestForCompatibility(t *testing.T) {
assert.Equal(t, `{"contents":[{"parts":[{"text":"keep"}]}]}`, string(got))
})
}

// TestWrapGeminiCountTokensBody covers the countTokens envelope. The endpoint rejects
// systemInstruction/tools/toolConfig/generationConfig at the top level and silently
// ignores a top-level contents/model once generateContentRequest is set, so the body
// must carry the envelope and nothing beside it.
func TestWrapGeminiCountTokensBody(t *testing.T) {
t.Run("wraps a flat body and keeps every counted field", func(t *testing.T) {
raw := []byte(`{"model":"gemini-3.6-flash","contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]},"tools":[{"functionDeclarations":[{"name":"probe"}]}],"toolConfig":{"functionCallingConfig":{"mode":"AUTO"}},"generationConfig":{"temperature":0.2}}`)

got := wrapGeminiCountTokensBody(raw, "gemini-3.6-flash")

assert.JSONEq(t, `{"generateContentRequest":{"model":"models/gemini-3.6-flash","contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]},"tools":[{"functionDeclarations":[{"name":"probe"}]}],"toolConfig":{"functionCallingConfig":{"mode":"AUTO"}},"generationConfig":{"temperature":0.2}}}`, string(got))
})

t.Run("leaves nothing at the top level besides the envelope", func(t *testing.T) {
got := wrapGeminiCountTokensBody([]byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`), "gemini-3.6-flash")

require.True(t, providerUtils.JSONFieldExists(got, "generateContentRequest"))
assert.False(t, providerUtils.JSONFieldExists(got, "contents"))
assert.False(t, providerUtils.JSONFieldExists(got, "model"))
})

t.Run("does not double wrap an already enveloped body", func(t *testing.T) {
raw := []byte(`{"generateContentRequest":{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]}}}`)

got := wrapGeminiCountTokensBody(raw, "gemini-3.6-flash")

assert.JSONEq(t, `{"generateContentRequest":{"model":"models/gemini-3.6-flash","contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]}}}`, string(got))
assert.False(t, providerUtils.JSONFieldExists(got, "generateContentRequest.generateContentRequest"))
})

t.Run("qualifies the model without doubling the prefix", func(t *testing.T) {
got := wrapGeminiCountTokensBody([]byte(`{"contents":[]}`), "models/gemini-3.6-flash")

assert.Equal(t, "models/gemini-3.6-flash", providerUtils.GetJSONField(got, "generateContentRequest.model").String())
})

t.Run("strips fields GenerateContentRequest does not define", func(t *testing.T) {
raw := []byte(`{"contents":[],"labels":{"a":"b"},"fallbacks":["gemini/other"]}`)

got := wrapGeminiCountTokensBody(raw, "gemini-3.6-flash")

assert.False(t, providerUtils.JSONFieldExists(got, "generateContentRequest.labels"))
assert.False(t, providerUtils.JSONFieldExists(got, "generateContentRequest.fallbacks"))
})

t.Run("handles empty body", func(t *testing.T) {
assert.Empty(t, wrapGeminiCountTokensBody(nil, "gemini-3.6-flash"))
})
}

// TestGeminiCountTokensRequestToGenerationRequest covers the genai ingress. Clients post
// either the generateContentRequest envelope the Gemini API requires or the flat body
// Vertex accepts, so both must survive unmarshalling with every counted field intact.
//
// These go through json.Unmarshal rather than struct literals on purpose: a literal sets
// fields the decoder would never have populated, so it cannot catch a field that the DTO
// forgot to declare — which is exactly how top-level systemInstruction, tools and
// fallbacks were once dropped here.
func TestGeminiCountTokensRequestToGenerationRequest(t *testing.T) {
flatten := func(t *testing.T, body string) *GeminiGenerationRequest {
t.Helper()
var req GeminiCountTokensRequest
require.NoError(t, json.Unmarshal([]byte(body), &req))
req.Model = "gemini-3.6-flash" // the genai route resolves the model from the path
return req.ToGeminiGenerationRequest()
}

t.Run("unwraps the envelope and keeps the system instruction", func(t *testing.T) {
got := flatten(t, `{"generateContentRequest":{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]}}}`)

require.NotNil(t, got.SystemInstruction)
assert.Equal(t, "be terse", got.SystemInstruction.Parts[0].Text)
assert.Equal(t, "gemini-3.6-flash", got.Model)
assert.True(t, got.IsCountTokens)
})

t.Run("keeps every counted field of a flat body", func(t *testing.T) {
got := flatten(t, `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"be terse"}]},"tools":[{"functionDeclarations":[{"name":"probe"}]}],"generationConfig":{"temperature":0.2}}`)

require.Len(t, got.Contents, 1)
assert.Equal(t, "hi", got.Contents[0].Parts[0].Text)
require.NotNil(t, got.SystemInstruction)
assert.Equal(t, "be terse", got.SystemInstruction.Parts[0].Text)
require.Len(t, got.Tools, 1)
require.NotNil(t, got.GenerationConfig.Temperature)
})

t.Run("path model wins over the envelope model", func(t *testing.T) {
got := flatten(t, `{"generateContentRequest":{"model":"models/stale","contents":[]}}`)

assert.Equal(t, "gemini-3.6-flash", got.Model)
})

t.Run("retains the top-level fallback chain", func(t *testing.T) {
got := flatten(t, `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"fallbacks":["vertex/gemini-3.6-flash","openai/gpt-4o"]}`)

assert.Equal(t, []string{"vertex/gemini-3.6-flash", "openai/gpt-4o"}, got.Fallbacks)
require.Len(t, got.ToBifrostResponsesRequest(nil).Fallbacks, 2)
})

t.Run("top-level fallbacks win over the envelope", func(t *testing.T) {
got := flatten(t, `{"fallbacks":["vertex/gemini-3.6-flash"],"generateContentRequest":{"contents":[],"fallbacks":["openai/stale"]}}`)

assert.Equal(t, []string{"vertex/gemini-3.6-flash"}, got.Fallbacks)
})

t.Run("keeps envelope fallbacks when none are set at the top level", func(t *testing.T) {
got := flatten(t, `{"generateContentRequest":{"contents":[],"fallbacks":["openai/gpt-4o"]}}`)

assert.Equal(t, []string{"openai/gpt-4o"}, got.Fallbacks)
})

// Converters are pure transformations, so the parsed request must survive untouched.
t.Run("leaves the parsed request unmutated", func(t *testing.T) {
for _, body := range []string{
`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`,
`{"generateContentRequest":{"model":"models/stale","contents":[],"fallbacks":["openai/stale"]}}`,
} {
var req GeminiCountTokensRequest
require.NoError(t, json.Unmarshal([]byte(body), &req))
req.Model = "gemini-3.6-flash"
req.Fallbacks = []string{"vertex/gemini-3.6-flash"}
before, err := json.Marshal(req)
require.NoError(t, err)

require.NotNil(t, req.ToGeminiGenerationRequest())

after, err := json.Marshal(req)
require.NoError(t, err)
assert.JSONEq(t, string(before), string(after), "converter mutated the request it was given")
assert.False(t, req.IsCountTokens, "converter set IsCountTokens on the source request")
}
})
}

// TestToBifrostCountTokensResponseCachedContent locks the cached-token accounting
// against the real API shape. Verified live: a 7202-token cache plus 9 tokens of
// contents returns totalTokens 7211 with promptTokensDetails already at 7211 and
// cacheTokensDetails at 7202 — the cache is a subset of the prompt, not an addition,
// so its modalities must never be folded into the breakdown a second time.
func TestToBifrostCountTokensResponseCachedContent(t *testing.T) {
t.Run("cached modalities do not inflate the breakdown", func(t *testing.T) {
resp := &GeminiCountTokensResponse{
TotalTokens: 7211,
CachedContentTokenCount: 7202,
PromptTokensDetails: []*ModalityTokenCount{{Modality: ModalityText, TokenCount: 7211}},
CacheTokensDetails: []*ModalityTokenCount{{Modality: ModalityText, TokenCount: 7202}},
}

got := resp.ToBifrostCountTokensResponse("gemini-2.5-flash")

assert.Equal(t, 7211, got.InputTokens)
assert.Equal(t, 7211, got.InputTokensDetails.TextTokens)
assert.Equal(t, 7202, got.InputTokensDetails.CachedReadTokens)
})

t.Run("falls back to summing cache details for the cached total", func(t *testing.T) {
resp := &GeminiCountTokensResponse{
TotalTokens: 100,
PromptTokensDetails: []*ModalityTokenCount{{Modality: ModalityText, TokenCount: 100}},
CacheTokensDetails: []*ModalityTokenCount{
{Modality: ModalityText, TokenCount: 60},
{Modality: ModalityAudio, TokenCount: 15},
},
}

got := resp.ToBifrostCountTokensResponse("gemini-2.5-flash")

assert.Equal(t, 75, got.InputTokensDetails.CachedReadTokens)
assert.Equal(t, 100, got.InputTokensDetails.TextTokens)
assert.Zero(t, got.InputTokensDetails.AudioTokens)
})
}
Loading
Loading