feat(translators): add token counting support for Claude and Gemini responses

- Implemented `TokenCount` transform method across translators to calculate token usage.
- Integrated token counting logic into executor pipelines for Claude, Gemini, and CLI translators.
- Added corresponding API endpoints and handlers (`/messages/count_tokens`) for token usage retrieval.
- Enhanced translation registry to support `TokenCount` functionality alongside existing response types.
This commit is contained in:
Luis Pater
2025-09-24 11:59:38 +08:00
parent 582677d067
commit 3dd5095792
22 changed files with 192 additions and 25 deletions

View File

@@ -3,6 +3,7 @@ package gemini
import (
"bytes"
"context"
"fmt"
)
// PassthroughGeminiResponseStream forwards Gemini responses unchanged.
@@ -22,3 +23,7 @@ func PassthroughGeminiResponseStream(_ context.Context, _ string, originalReques
func PassthroughGeminiResponseNonStream(_ context.Context, _ string, originalRequestRawJSON, requestRawJSON, rawJSON []byte, _ *any) string {
return string(rawJSON)
}
func GeminiTokenCount(ctx context.Context, count int64) string {
return fmt.Sprintf(`{"totalTokens":%d,"promptTokensDetails":[{"modality":"TEXT","tokenCount":%d}]}`, count, count)
}

View File

@@ -14,8 +14,9 @@ func init() {
Gemini,
ConvertGeminiRequestToGemini,
interfaces.TranslateResponse{
Stream: PassthroughGeminiResponseStream,
NonStream: PassthroughGeminiResponseNonStream,
Stream: PassthroughGeminiResponseStream,
NonStream: PassthroughGeminiResponseNonStream,
TokenCount: GeminiTokenCount,
},
)
}