Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix: support emoji in tokenizer (#956)

Max Deichmannc0ed93132f11
diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.ts
index 60c0548d27..ab58bfdcff 100644
--- a/src/__tests__/usage.servertest.ts
+++ b/src/__tests__/usage.servertest.ts
@@ -70,7 +70,8 @@ describe("Token Count Functions", () => {
},
{
id: "some id",
- content: "some test",
+ content:
+ "Hey Simon! 😊 How's your day going? Have you been up to anything interesting lately?",
role: "user",
timestamp: "2024-01-24T10:00:00.929Z",
isPersisted: true,
@@ -91,7 +92,7 @@ describe("Token Count Functions", () => {
},
],
});
- expect(result).toBe(137);
+ expect(result).toBe(155);
});
it("should return for invalid text type", () => {
diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.ts
index 1861053435..5d65f2df54 100644
--- a/src/features/ingest/lib/usage.ts
+++ b/src/features/ingest/lib/usage.ts
@@ -151,8 +151,8 @@ const getTokensByModel = (model: TiktokenModel, text: string) => {
console.log("Warning: model not found. Using cl100k_base encoding.");
encoding = get_encoding("cl100k_base");
}
-
- return encoding.encode(text).length;
+ const cleandedText = unicodeToBytesInString(text);
+ return encoding.encode(cleandedText).length;
};
function isString(value: unknown): value is string {
@@ -175,3 +175,23 @@ function isChatMessageArray(value: unknown): value is ChatMessage[] {
(!("name" in item) || typeof item.name === "string"),
);
}
+
+function unicodeToBytesInString(input: string): string {
+ let result = "";
+ for (let i = 0; i < input.length; i++) {
+ const char = input[i];
+ if (char && /[\u{10000}-\u{10FFFF}]/u.test(char)) {
+ const bytes = unicodeToBytes(char);
+ result += Array.from(bytes)
+ .map((b) => b.toString(16))
+ .join("");
+ } else {
+ result += char;
+ }
+ }
+ return result;
+}
+function unicodeToBytes(input: string): Uint8Array {
+ const encoder = new TextEncoder();
+ return encoder.encode(input);
+}