Skip to content
Open
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
30 changes: 15 additions & 15 deletions pkg/tokenusage/tokenusage.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package tokenusage

import (
"bytes"
"encoding/json"
"slices"

"github.com/higress-group/wasm-go/pkg/wrapper"
Expand Down Expand Up @@ -88,7 +89,6 @@ const (
OutputTokenDetailsKeyGeminiThoughtsTokenCount = "thoughts_token_count"

ctxKeyDeltaSSEMessage = "delta_sse_message"
ctxKeyDeltaBeginning = "delta_beginning"
)

type TokenUsage struct {
Expand Down Expand Up @@ -132,24 +132,24 @@ func GetTokenUsage(ctx wrapper.HttpContext, body []byte) TokenUsage {
}

func mergeLargeResponseAPIChunks(ctx wrapper.HttpContext, chunk []byte) []byte {
if bytes.Contains(chunk, []byte(`"response.completed"`)) && !bytes.Contains(chunk, []byte(`"usage"`)) {
ctx.SetContext(ctxKeyDeltaBeginning, true)
pending := ctx.GetByteSliceContext(ctxKeyDeltaSSEMessage, nil)
if len(pending) == 0 {
// response.completed may appear only in the final transport fragment.
jsonStart := bytes.IndexByte(chunk, '{')
if jsonStart == -1 {
return chunk
}
chunk = chunk[jsonStart:]
}

if ctx.GetBoolContext(ctxKeyDeltaBeginning, false) {
// end of streaming
if len(bytes.TrimSpace(chunk)) == 0 {
ctx.SetContext(ctxKeyDeltaBeginning, false)
chunk = ctx.GetByteSliceContext(ctxKeyDeltaSSEMessage, chunk)
ctx.SetContext(ctxKeyDeltaSSEMessage, nil)
} else {
deltaMessage := ctx.GetByteSliceContext(ctxKeyDeltaSSEMessage, []byte{})
deltaMessage = append(deltaMessage, chunk...)
ctx.SetContext(ctxKeyDeltaSSEMessage, deltaMessage)
}
message := append(pending, chunk...)
if !json.Valid(message) {
ctx.SetContext(ctxKeyDeltaSSEMessage, bytes.Clone(message))
return nil
}

return chunk
ctx.SetContext(ctxKeyDeltaSSEMessage, nil)
return message
}

func ExtractModel(ctx wrapper.HttpContext, body []byte, u *TokenUsage) {
Expand Down
74 changes: 74 additions & 0 deletions pkg/tokenusage/tokenusage_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tokenusage

import (
"testing"

"github.com/higress-group/wasm-go/pkg/iface"
"github.com/stretchr/testify/require"
)

type tokenUsageTestContext struct {
iface.HttpContext
context map[string]interface{}
userAttributes map[string]interface{}
}

func newTokenUsageTestContext() *tokenUsageTestContext {
return &tokenUsageTestContext{
context: make(map[string]interface{}),
userAttributes: make(map[string]interface{}),
}
}

func (c *tokenUsageTestContext) SetContext(key string, value interface{}) {
c.context[key] = value
}

func (c *tokenUsageTestContext) GetByteSliceContext(key string, defaultValue []byte) []byte {
value, ok := c.context[key].([]byte)
if !ok {
return defaultValue
}
return value
}

func (c *tokenUsageTestContext) GetUserAttribute(key string) interface{} {
return c.userAttributes[key]
}

func (c *tokenUsageTestContext) SetUserAttribute(key string, value interface{}) {
c.userAttributes[key] = value
}

func TestGetTokenUsageMergesFragmentedResponsesCompletedEvent(t *testing.T) {
ctx := newTokenUsageTestContext()
fragments := [][]byte{
[]byte(`{"response":{"id":"resp_123","model":"gpt-5.6-sol","tools":[{"parameters":{"properties":{"model":{"description":"not the response model"}}}}],`),
[]byte(`"usage":{"input_tokens":10,"output_tokens":2,"total_tokens":12}},"sequence_number":1,`),
[]byte("\"type\":\"response.completed\"}\n\n"),
}

var usage TokenUsage
for _, fragment := range fragments {
usage = GetTokenUsage(ctx, fragment)
}

require.Equal(t, "gpt-5.6-sol", usage.Model)
require.EqualValues(t, 10, usage.InputToken)
require.EqualValues(t, 2, usage.OutputToken)
require.EqualValues(t, 12, usage.TotalToken)
}