From e0df2a255522d1aee1f4aebd31474bf089079e02 Mon Sep 17 00:00:00 2001 From: Luca Steeb Date: Wed, 11 Feb 2026 00:36:15 +0700 Subject: [PATCH] fix: return 0 completion tokens for empty content Co-Authored-By: Claude Opus 4.6 --- .../src/chat/tools/estimate-tokens-from-content.ts | 3 +++ apps/gateway/src/lib/prompt-tokens.spec.ts | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/apps/gateway/src/chat/tools/estimate-tokens-from-content.ts b/apps/gateway/src/chat/tools/estimate-tokens-from-content.ts index 674f5218a3..b998ba530c 100644 --- a/apps/gateway/src/chat/tools/estimate-tokens-from-content.ts +++ b/apps/gateway/src/chat/tools/estimate-tokens-from-content.ts @@ -2,5 +2,8 @@ * Estimates tokens from content length using simple division */ export function estimateTokensFromContent(content: string): number { + if (!content) { + return 0; + } return Math.max(1, Math.round(content.length / 4)); } diff --git a/apps/gateway/src/lib/prompt-tokens.spec.ts b/apps/gateway/src/lib/prompt-tokens.spec.ts index 0768ace500..a1d2912e1b 100644 --- a/apps/gateway/src/lib/prompt-tokens.spec.ts +++ b/apps/gateway/src/lib/prompt-tokens.spec.ts @@ -8,7 +8,7 @@ describe("Prompt token calculation", () => { describe("estimateTokensFromContent", () => { it("should estimate tokens from content length", () => { expect(estimateTokensFromContent("Hello world")).toBe(3); // 11 chars / 4 = 2.75, rounded to 3 - expect(estimateTokensFromContent("")).toBe(1); // Always at least 1 + expect(estimateTokensFromContent("")).toBe(0); // Empty content = 0 tokens expect( estimateTokensFromContent( "A very long message that should result in more tokens", @@ -16,8 +16,11 @@ describe("Prompt token calculation", () => { ).toBe(13); // 53 chars / 4 = 13.25, rounded to 13 }); - it("should always return at least 1 token", () => { - expect(estimateTokensFromContent("")).toBe(1); + it("should return 0 for empty content", () => { + expect(estimateTokensFromContent("")).toBe(0); + }); + + it("should return at least 1 token for non-empty content", () => { expect(estimateTokensFromContent("A")).toBe(1); }); });