mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-12-05 08:03:01 +00:00
fix(gemini): bill audio inlineData by length, not as images, when usage is missing (#8193)
* fix(gemini): bill audio inlineData by length, not as images, when usage is missing When upstream reported no completion tokens (no usageMetadata, or prompt-only usageMetadata), every inlineData part with a non-empty mimeType was counted as an image and backfilled with 1400 completion tokens. A relay that answered a text request with thousands of audio/l16 TTS chunks was billed millions of output tokens. Estimate inline output from the payload instead, on the stream and non-stream paths alike: - image* parts (case-insensitive) keep the 1400-token estimate; - PCM audio (audio/l16 or audio/pcm with a rate) counts 25 tokens per second, Gemini's audio token rate, measured from the decoded byte count of valid base64 holding whole 16-bit samples, and is recorded as audio output so tiered expressions price it with ao; on the prompt-only path it replaces any upstream AUDIO candidate entry; - audio without a measurable length and other media add nothing. Responses that report completion tokens are unchanged. * fix(gemini): harden inline media usage fallback and avoid redundant scan - Parse inlineData MIME types once with mime.ParseMediaType and ignore empty image payloads - Gate BillingUsage AUDIO detail replacement on inline fallback application so stale AUDIO entries are cleared when estimating images - Defer inline media observation in buildUsageFromGeminiResponse until completion tokens are missing - Saturate audio token conversion inside audioTokens via common.QuotaFromFloat without bare int casts - Add regression cases for empty image payloads, stale AUDIO clearing on image fallback, and preserving upstream completion counts --------- Co-authored-by: seefs001 <i@seefs.me>
This commit is contained in:
1 parent
5f8525d83c
commit
3333fc6766
2 files changed
+405
-24
No files matched your search
@@ -5,11 +5,14 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/MoeForge/moego/base64"
|
||||
"github.com/MoeForge/moego/ojson"
|
||||
"github.com/QuantumNous/new-api/common"
|
||||
"github.com/QuantumNous/new-api/constant"
|
||||
@@ -44,23 +47,33 @@ func attachEstimatedGeminiBillingUsage(usage *dto.Usage) *dto.Usage {
|
||||
// content was actually received. Typical case: the client aborts a stream before the
|
||||
// final chunk that carries candidatesTokenCount, leaving prompt-only metadata; without
|
||||
// this patch the output side would settle at zero quota.
|
||||
func patchGeminiZeroCompletionUsage(c *gin.Context, info *relaycommon.RelayInfo, usage *dto.Usage, responseText string, imageCount int) {
|
||||
func patchGeminiZeroCompletionUsage(c *gin.Context, info *relaycommon.RelayInfo, usage *dto.Usage, responseText string, inlineOutput geminiInlineOutput) {
|
||||
if usage == nil || usage.CompletionTokens > 0 {
|
||||
return
|
||||
}
|
||||
if responseText == "" && imageCount == 0 {
|
||||
inlineTokens, _ := inlineOutput.estimate()
|
||||
if responseText == "" && inlineTokens == 0 {
|
||||
return
|
||||
}
|
||||
estimated := service.ResponseText2Usage(c, responseText, info.UpstreamModelName, usage.PromptTokens)
|
||||
usage.CompletionTokens = estimated.CompletionTokens
|
||||
if imageCount != 0 && usage.CompletionTokens == 0 {
|
||||
usage.CompletionTokens = imageCount * 1400
|
||||
}
|
||||
usedInline := inlineOutput.fillZeroCompletion(usage)
|
||||
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
|
||||
// Settlement prefers BillingUsage, so fill the missing completion in the
|
||||
// original upstream dialect without discarding cache or modality details.
|
||||
if usage.BillingUsage != nil {
|
||||
usage.BillingUsage = dto.CloneBillingUsageWithEstimatedCompletion(usage.BillingUsage, usage.CompletionTokens)
|
||||
if usedInline && usage.BillingUsage.GeminiUsageMetadata != nil {
|
||||
// Settlement sums every AUDIO entry, so the inline estimate replaces
|
||||
// any upstream AUDIO entry (or clears it when only images were estimated).
|
||||
metadata := usage.BillingUsage.GeminiUsageMetadata
|
||||
metadata.CandidatesTokensDetails = slices.DeleteFunc(metadata.CandidatesTokensDetails, func(detail dto.GeminiPromptTokensDetails) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(detail.Modality), "AUDIO")
|
||||
})
|
||||
if audioTokens := usage.CompletionTokenDetails.AudioTokens; audioTokens > 0 {
|
||||
metadata.CandidatesTokensDetails = append(metadata.CandidatesTokensDetails, dto.GeminiPromptTokensDetails{Modality: "AUDIO", TokenCount: audioTokens})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
usage.BillingUsage = dto.NewEstimatedGeminiChatBillingUsage(usage)
|
||||
}
|
||||
@@ -149,27 +162,127 @@ func buildUsageFromGeminiResponse(c *gin.Context, info *relaycommon.RelayInfo, r
|
||||
metadata := response.GetUsageMetadata()
|
||||
if dto.HasGeminiUsageMetadataTokens(metadata) {
|
||||
usage := buildUsageFromGeminiMetadata(metadata, info.GetEstimatePromptTokens())
|
||||
patchGeminiZeroCompletionUsage(c, info, &usage, geminiResponseUsageText(response), geminiResponseInlineImageCount(response))
|
||||
if usage.CompletionTokens == 0 {
|
||||
var inlineOutput geminiInlineOutput
|
||||
inlineOutput.observe(response)
|
||||
patchGeminiZeroCompletionUsage(c, info, &usage, geminiResponseUsageText(response), inlineOutput)
|
||||
}
|
||||
return usage
|
||||
}
|
||||
var inlineOutput geminiInlineOutput
|
||||
inlineOutput.observe(response)
|
||||
usage := service.ResponseText2Usage(c, geminiResponseUsageText(response), info.UpstreamModelName, info.GetEstimatePromptTokens())
|
||||
if inlineOutput.fillZeroCompletion(usage) {
|
||||
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
|
||||
}
|
||||
attachEstimatedGeminiBillingUsage(usage)
|
||||
return *usage
|
||||
}
|
||||
|
||||
func geminiResponseInlineImageCount(response *dto.GeminiChatResponse) int {
|
||||
const (
|
||||
// geminiInlineImageCompletionTokens is the completion estimate for one
|
||||
// inline image when upstream reports no completion tokens.
|
||||
geminiInlineImageCompletionTokens = 1400
|
||||
// geminiAudioTokensPerSecond is Gemini's audio token rate: "Audio tokens
|
||||
// correspond to 25 tokens per second of audio"
|
||||
// (ai.google.dev/gemini-api/docs/pricing).
|
||||
geminiAudioTokensPerSecond = 25
|
||||
)
|
||||
|
||||
// geminiInlineOutput estimates the completion tokens of inline media when
|
||||
// upstream usageMetadata does not report them. Each non-empty image/* part
|
||||
// counts geminiInlineImageCompletionTokens. PCM audio (audio/l16 or audio/pcm
|
||||
// with a rate, as Gemini TTS returns) counts geminiAudioTokensPerSecond, with
|
||||
// its length taken from the 16-bit sample count. Other audio has no measurable
|
||||
// length here and other media is not image output, so both add nothing.
|
||||
type geminiInlineOutput struct {
|
||||
images int
|
||||
audio time.Duration
|
||||
}
|
||||
|
||||
func (o *geminiInlineOutput) observe(response *dto.GeminiChatResponse) {
|
||||
if response == nil {
|
||||
return 0
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for _, candidate := range response.Candidates {
|
||||
for _, part := range candidate.Content.Parts {
|
||||
if part.InlineData != nil && part.InlineData.MimeType != "" {
|
||||
count++
|
||||
if part.InlineData == nil {
|
||||
continue
|
||||
}
|
||||
mediaType, params, err := mime.ParseMediaType(part.InlineData.MimeType)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(mediaType, "image/") {
|
||||
if strings.TrimSpace(part.InlineData.Data) != "" {
|
||||
o.images++
|
||||
}
|
||||
continue
|
||||
}
|
||||
o.audio += geminiPCMDuration(mediaType, params, part.InlineData.Data)
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func (o geminiInlineOutput) audioTokens() int {
|
||||
if o.audio <= 0 {
|
||||
return 0
|
||||
}
|
||||
secs := int64(o.audio / time.Second)
|
||||
rem := int64(o.audio % time.Second)
|
||||
remTokens := (rem*geminiAudioTokensPerSecond + int64(time.Second) - 1) / int64(time.Second)
|
||||
return common.QuotaFromFloat(float64(secs)*geminiAudioTokensPerSecond + float64(remTokens))
|
||||
}
|
||||
|
||||
func (o geminiInlineOutput) estimate() (completionTokens int, audioTokens int) {
|
||||
audioTokens = o.audioTokens()
|
||||
completionTokens = common.QuotaFromFloat(float64(o.images)*geminiInlineImageCompletionTokens + float64(audioTokens))
|
||||
audioTokens = min(audioTokens, completionTokens)
|
||||
return completionTokens, audioTokens
|
||||
}
|
||||
|
||||
// fillZeroCompletion uses the inline estimate when usage has no completion
|
||||
// tokens, recording the audio part as audio output so tiered expressions price
|
||||
// it with ao. It reports whether the estimate was applied.
|
||||
func (o geminiInlineOutput) fillZeroCompletion(usage *dto.Usage) bool {
|
||||
completionTokens, audioTokens := o.estimate()
|
||||
if completionTokens == 0 || usage.CompletionTokens != 0 {
|
||||
return false
|
||||
}
|
||||
usage.CompletionTokens = completionTokens
|
||||
usage.CompletionTokenDetails.AudioTokens = audioTokens
|
||||
return true
|
||||
}
|
||||
|
||||
// geminiPCMDuration returns the length of base64 16-bit PCM audio, or 0 when
|
||||
// the mediaType is not PCM, its rate or channel count is implausible, or the
|
||||
// data is not valid base64 holding whole 16-bit samples.
|
||||
func geminiPCMDuration(mediaType string, params map[string]string, data string) time.Duration {
|
||||
if mediaType != "audio/l16" && mediaType != "audio/pcm" {
|
||||
return 0
|
||||
}
|
||||
rate, err := strconv.Atoi(params["rate"])
|
||||
if err != nil || rate < 8000 || rate > 192000 {
|
||||
return 0
|
||||
}
|
||||
channels := 1
|
||||
if value, ok := params["channels"]; ok {
|
||||
channels, err = strconv.Atoi(value)
|
||||
if err != nil || channels < 1 || channels > 8 {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
decodedLen, err := base64.StdEncoding.ValidateString(data)
|
||||
if err != nil || decodedLen == 0 {
|
||||
return 0
|
||||
}
|
||||
pcmBytes := int64(decodedLen)
|
||||
bytesPerSecond := int64(rate * channels * 2)
|
||||
if pcmBytes%int64(channels*2) != 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(pcmBytes/bytesPerSecond)*time.Second +
|
||||
time.Duration(pcmBytes%bytesPerSecond)*time.Second/time.Duration(bytesPerSecond)
|
||||
}
|
||||
|
||||
func responseGeminiChat2OpenAI(c *gin.Context, response *dto.GeminiChatResponse) *dto.OpenAITextResponse {
|
||||
@@ -203,7 +316,7 @@ func handleFinalStream(c *gin.Context, info *relaycommon.RelayInfo, resp *dto.Ch
|
||||
|
||||
func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response, callback func(data string, geminiResponse *dto.GeminiChatResponse) bool) (*dto.Usage, *types.NewAPIError) {
|
||||
var usage = &dto.Usage{}
|
||||
var imageCount int
|
||||
var inlineOutput geminiInlineOutput
|
||||
var hasBillableUsageMetadata bool
|
||||
var streamErr error
|
||||
var accumulatedUsageMetadata *dto.GeminiUsageMetadata
|
||||
@@ -239,14 +352,8 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
|
||||
grounding.commit(info)
|
||||
countGeminiBillableFunctionCalls(info, &geminiResponse)
|
||||
|
||||
// 统计图片数量
|
||||
for _, candidate := range geminiResponse.Candidates {
|
||||
for _, part := range candidate.Content.Parts {
|
||||
if part.InlineData != nil && part.InlineData.MimeType != "" {
|
||||
imageCount++
|
||||
}
|
||||
}
|
||||
}
|
||||
// 统计图片和音频输出
|
||||
inlineOutput.observe(&geminiResponse)
|
||||
responseText.WriteString(geminiResponseUsageText(&geminiResponse))
|
||||
|
||||
// 更新使用量统计
|
||||
@@ -274,14 +381,13 @@ func geminiStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http
|
||||
} else {
|
||||
usage = &dto.Usage{}
|
||||
}
|
||||
if imageCount != 0 && usage.CompletionTokens == 0 {
|
||||
usage.CompletionTokens = imageCount * 1400
|
||||
if inlineOutput.fillZeroCompletion(usage) {
|
||||
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
|
||||
common.SetContextKey(c, constant.ContextKeyLocalCountTokens, true)
|
||||
}
|
||||
attachEstimatedGeminiBillingUsage(usage)
|
||||
} else {
|
||||
patchGeminiZeroCompletionUsage(c, info, usage, responseText.String(), imageCount)
|
||||
patchGeminiZeroCompletionUsage(c, info, usage, responseText.String(), inlineOutput)
|
||||
}
|
||||
|
||||
if streamErr != nil {
|
||||
|
||||
@@ -2,6 +2,7 @@ package gemini
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -654,6 +655,280 @@ func TestGeminiStreamHandlerEmptyUsageMetadataBuildsEstimatedBillingUsage(t *tes
|
||||
require.True(t, common.GetContextKeyBool(c, constant.ContextKeyLocalCountTokens))
|
||||
}
|
||||
|
||||
// geminiInlineFrame is one stream frame carrying a single inlineData part.
|
||||
func geminiInlineFrame(mimeType, data string) string {
|
||||
return `{"candidates":[{"content":{"role":"model","parts":[{"inlineData":{"mimeType":"` + mimeType + `","data":"` + data + `"}}]},"index":0}],"modelVersion":"gemini-3.8-flash-lite-tts"}`
|
||||
}
|
||||
|
||||
// pcm100ms is 4800 bytes of base64 PCM: 100 ms of 16-bit mono audio at 24 kHz.
|
||||
var pcm100ms = strings.Repeat("A", 6400)
|
||||
|
||||
// Without billable usageMetadata, inline output is estimated from the payload:
|
||||
// 1400 tokens per image, and 25 tokens per second of PCM audio (the Gemini TTS
|
||||
// rate) with the length taken from the PCM byte count. Audio whose length
|
||||
// cannot be measured, and non-image media, add nothing. A relay that answered
|
||||
// a text request with audio/l16 chunks must not bill each chunk as an image.
|
||||
func TestGeminiStreamHandlerWithoutUsageMetadataEstimatesInlineOutput(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
oldStreamingTimeout := constant.StreamingTimeout
|
||||
constant.StreamingTimeout = 300
|
||||
t.Cleanup(func() {
|
||||
constant.StreamingTimeout = oldStreamingTimeout
|
||||
})
|
||||
|
||||
l16Chunk := geminiInlineFrame("audio/l16; rate=24000; channels=1", pcm100ms)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
frames []string
|
||||
wantCompletionTokens int
|
||||
wantAudioTokens int
|
||||
}{
|
||||
{
|
||||
// 0.3 s of audio: ceil(0.3 * 25) = 8.
|
||||
name: "pcm audio chunks then in-stream error",
|
||||
frames: []string{
|
||||
l16Chunk,
|
||||
l16Chunk,
|
||||
l16Chunk,
|
||||
`{"error":{"code":504,"message":"context deadline exceeded","status":"DEADLINE_EXCEEDED"}}`,
|
||||
},
|
||||
wantCompletionTokens: 8,
|
||||
wantAudioTokens: 8,
|
||||
},
|
||||
{
|
||||
// 1 s of audio in the Gemini API's own mimeType form.
|
||||
name: "pcm audio with codec parameter",
|
||||
frames: []string{geminiInlineFrame("audio/L16;codec=pcm;rate=24000", strings.Repeat(pcm100ms, 10))},
|
||||
wantCompletionTokens: 25,
|
||||
wantAudioTokens: 25,
|
||||
},
|
||||
{
|
||||
name: "audio without a measurable length",
|
||||
frames: []string{geminiInlineFrame("audio/mpeg", pcm100ms), geminiInlineFrame("audio/l16; rate=1", pcm100ms)},
|
||||
wantCompletionTokens: 0,
|
||||
},
|
||||
{
|
||||
// One byte is not a whole 16-bit sample.
|
||||
name: "pcm audio with a partial sample",
|
||||
frames: []string{geminiInlineFrame("audio/l16; rate=24000; channels=1", "AA==")},
|
||||
wantCompletionTokens: 0,
|
||||
},
|
||||
{
|
||||
// Invalid base64 is not audio, so its length bills nothing.
|
||||
name: "pcm audio with invalid base64",
|
||||
frames: []string{geminiInlineFrame("audio/l16; rate=24000; channels=1", strings.Repeat("A!", 3200))},
|
||||
wantCompletionTokens: 0,
|
||||
},
|
||||
{
|
||||
name: "image chunks",
|
||||
frames: []string{geminiInlineFrame("image/png", "iVBORw0KGgo="), geminiInlineFrame("image/png", "iVBORw0KGgo=")},
|
||||
wantCompletionTokens: 2 * 1400,
|
||||
},
|
||||
{
|
||||
// MIME types are case-insensitive (RFC 2045).
|
||||
name: "uppercase image mimeType",
|
||||
frames: []string{geminiInlineFrame("IMAGE/PNG", "iVBORw0KGgo=")},
|
||||
wantCompletionTokens: 1400,
|
||||
},
|
||||
{
|
||||
// Payload-less image parts bill nothing.
|
||||
name: "image chunk without payload",
|
||||
frames: []string{geminiInlineFrame("image/png", "")},
|
||||
wantCompletionTokens: 0,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
info := &relaycommon.RelayInfo{
|
||||
OriginModelName: "gemini-3.8-flash",
|
||||
ChannelMeta: &relaycommon.ChannelMeta{
|
||||
UpstreamModelName: "gemini-3.8-flash",
|
||||
},
|
||||
}
|
||||
info.SetEstimatePromptTokens(20)
|
||||
|
||||
var streamBody strings.Builder
|
||||
for _, frame := range tc.frames {
|
||||
streamBody.WriteString("data: " + frame + "\n")
|
||||
}
|
||||
resp := &http.Response{
|
||||
Body: io.NopCloser(strings.NewReader(streamBody.String())),
|
||||
}
|
||||
|
||||
usage, newAPIError := geminiStreamHandler(c, info, resp, func(_ string, _ *dto.GeminiChatResponse) bool {
|
||||
return true
|
||||
})
|
||||
require.Nil(t, newAPIError)
|
||||
require.NotNil(t, usage)
|
||||
assert.Equal(t, tc.wantCompletionTokens, usage.CompletionTokens)
|
||||
assert.Equal(t, usage.PromptTokens+usage.CompletionTokens, usage.TotalTokens)
|
||||
require.NotNil(t, usage.BillingUsage)
|
||||
require.NotNil(t, usage.BillingUsage.GeminiUsageMetadata)
|
||||
assert.Equal(t, usage.CompletionTokens, usage.BillingUsage.GeminiUsageMetadata.CandidatesTokenCount)
|
||||
// Tiered expressions price ao from the settled audio output detail.
|
||||
settled, ok := usage.BillingUsage.CanonicalUsage()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, tc.wantAudioTokens, settled.CompletionTokenDetails.AudioTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// When upstream reports no completion tokens, with prompt-only usageMetadata or
|
||||
// none at all, the stream and non-stream paths apply the same inline output
|
||||
// estimate.
|
||||
func TestGeminiHandlersWithoutCompletionUsageEstimateInlineOutput(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
oldStreamingTimeout := constant.StreamingTimeout
|
||||
constant.StreamingTimeout = 300
|
||||
t.Cleanup(func() {
|
||||
constant.StreamingTimeout = oldStreamingTimeout
|
||||
})
|
||||
|
||||
audioPart := dto.GeminiPart{InlineData: &dto.GeminiInlineData{MimeType: "audio/l16; rate=24000; channels=1", Data: pcm100ms}}
|
||||
imagePart := dto.GeminiPart{InlineData: &dto.GeminiInlineData{MimeType: "image/png", Data: "iVBORw0KGgo="}}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
parts []dto.GeminiPart
|
||||
wantCompletionTokens int
|
||||
wantAudioTokens int
|
||||
}{
|
||||
{"audio", []dto.GeminiPart{audioPart, audioPart, audioPart}, 8, 8},
|
||||
{"image", []dto.GeminiPart{imagePart, imagePart}, 2 * 1400, 0},
|
||||
} {
|
||||
for _, metadata := range []struct {
|
||||
name string
|
||||
usageMetadata dto.GeminiUsageMetadata
|
||||
wantPromptTokens int
|
||||
overrideCompletion int
|
||||
hasUpstreamUsageComp bool
|
||||
}{
|
||||
{"prompt-only usage", dto.GeminiUsageMetadata{PromptTokenCount: 151, TotalTokenCount: 151}, 151, 0, false},
|
||||
{"no usage", dto.GeminiUsageMetadata{}, 20, 0, false},
|
||||
{"upstream completion usage", dto.GeminiUsageMetadata{PromptTokenCount: 151, CandidatesTokenCount: 42, TotalTokenCount: 193}, 151, 42, true},
|
||||
} {
|
||||
payload := dto.GeminiChatResponse{
|
||||
Candidates: []dto.GeminiChatCandidate{
|
||||
{Content: dto.GeminiChatContent{Role: "model", Parts: tc.parts}},
|
||||
},
|
||||
UsageMetadata: metadata.usageMetadata,
|
||||
}
|
||||
body, err := common.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/%s/stream=%t", tc.name, metadata.name, stream), func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
info := &relaycommon.RelayInfo{
|
||||
RelayFormat: types.RelayFormatGemini,
|
||||
OriginModelName: "gemini-3.8-flash",
|
||||
ChannelMeta: &relaycommon.ChannelMeta{
|
||||
UpstreamModelName: "gemini-3.8-flash",
|
||||
},
|
||||
}
|
||||
info.SetEstimatePromptTokens(20)
|
||||
|
||||
var usage *dto.Usage
|
||||
var newAPIError *types.NewAPIError
|
||||
if stream {
|
||||
resp := &http.Response{
|
||||
Body: io.NopCloser(strings.NewReader("data: " + string(body) + "\n" + "data: [DONE]\n")),
|
||||
}
|
||||
usage, newAPIError = geminiStreamHandler(c, info, resp, func(_ string, _ *dto.GeminiChatResponse) bool {
|
||||
return true
|
||||
})
|
||||
} else {
|
||||
resp := &http.Response{
|
||||
Body: io.NopCloser(bytes.NewReader(body)),
|
||||
}
|
||||
usage, newAPIError = GeminiChatHandler(c, info, resp)
|
||||
}
|
||||
require.Nil(t, newAPIError)
|
||||
require.NotNil(t, usage)
|
||||
wantCompletion := tc.wantCompletionTokens
|
||||
wantAudio := tc.wantAudioTokens
|
||||
if metadata.hasUpstreamUsageComp {
|
||||
wantCompletion = metadata.overrideCompletion
|
||||
wantAudio = 0
|
||||
}
|
||||
assert.Equal(t, metadata.wantPromptTokens, usage.PromptTokens)
|
||||
assert.Equal(t, wantCompletion, usage.CompletionTokens)
|
||||
assert.Equal(t, usage.PromptTokens+usage.CompletionTokens, usage.TotalTokens)
|
||||
require.NotNil(t, usage.BillingUsage)
|
||||
require.NotNil(t, usage.BillingUsage.GeminiUsageMetadata)
|
||||
assert.Equal(t, usage.CompletionTokens, usage.BillingUsage.GeminiUsageMetadata.CandidatesTokenCount)
|
||||
settled, ok := usage.BillingUsage.CanonicalUsage()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, wantAudio, settled.CompletionTokenDetails.AudioTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prompt-only usageMetadata that already lists an AUDIO candidate detail
|
||||
// without a candidate token count settles with the inline estimate once
|
||||
// (replacing it for audio, or clearing it when only images were estimated).
|
||||
func TestGeminiChatHandlerPromptOnlyUsageReplacesAudioCandidateDetail(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
audioPart := dto.GeminiPart{InlineData: &dto.GeminiInlineData{MimeType: "audio/l16; rate=24000; channels=1", Data: pcm100ms}}
|
||||
imagePart := dto.GeminiPart{InlineData: &dto.GeminiInlineData{MimeType: "image/png", Data: "iVBORw0KGgo="}}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
parts []dto.GeminiPart
|
||||
wantCompletionTokens int
|
||||
wantAudioTokens int
|
||||
}{
|
||||
{"audio replaces stale detail", []dto.GeminiPart{audioPart, audioPart, audioPart}, 8, 8},
|
||||
{"image clears stale audio detail", []dto.GeminiPart{imagePart}, 1400, 0},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
c, _ := gin.CreateTestContext(httptest.NewRecorder())
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil)
|
||||
|
||||
info := &relaycommon.RelayInfo{
|
||||
RelayFormat: types.RelayFormatGemini,
|
||||
OriginModelName: "gemini-3.8-flash",
|
||||
ChannelMeta: &relaycommon.ChannelMeta{
|
||||
UpstreamModelName: "gemini-3.8-flash",
|
||||
},
|
||||
}
|
||||
|
||||
payload := dto.GeminiChatResponse{
|
||||
Candidates: []dto.GeminiChatCandidate{
|
||||
{Content: dto.GeminiChatContent{Role: "model", Parts: tc.parts}},
|
||||
},
|
||||
UsageMetadata: dto.GeminiUsageMetadata{
|
||||
PromptTokenCount: 151,
|
||||
TotalTokenCount: 151,
|
||||
CandidatesTokensDetails: []dto.GeminiPromptTokensDetails{{Modality: "audio", TokenCount: 5}},
|
||||
},
|
||||
}
|
||||
body, err := common.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
|
||||
usage, newAPIError := GeminiChatHandler(c, info, &http.Response{Body: io.NopCloser(bytes.NewReader(body))})
|
||||
require.Nil(t, newAPIError)
|
||||
require.NotNil(t, usage)
|
||||
assert.Equal(t, tc.wantCompletionTokens, usage.CompletionTokens)
|
||||
assert.Equal(t, tc.wantAudioTokens, usage.CompletionTokenDetails.AudioTokens)
|
||||
require.NotNil(t, usage.BillingUsage)
|
||||
settled, ok := usage.BillingUsage.CanonicalUsage()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, tc.wantCompletionTokens, settled.CompletionTokens)
|
||||
assert.Equal(t, tc.wantAudioTokens, settled.CompletionTokenDetails.AudioTokens)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Google Search grounding records the unique trimmed non-empty queries
|
||||
// (webSearchQueries and imageSearchQueries of every candidate, across every
|
||||
// stream frame) under google_search and one grounded prompt when any query
|
||||
|
||||
Reference in new issue
Block a user