Skip to content

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

fix claude models (#284)

Maximilian Deichmann29121dce590a
diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.ts
index eaeb9fad39..38078e1b75 100644
--- a/src/__tests__/usage.servertest.ts
+++ b/src/__tests__/usage.servertest.ts
@@ -5,6 +5,7 @@ describe("Token Count Functions", () => {
[
{ model: "gpt-3.5", tokens: 114 },
{ model: "claude", tokens: 118 },
+ { model: "claude-instant-1.2", tokens: 118 },
].forEach(({ model, tokens }) => {
it(`should return token count ${tokens} for ${model}`, () => {
const result = tokenCount({
@@ -12,7 +13,7 @@ describe("Token Count Functions", () => {
text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
});
expect(result).toBeDefined();
- expect(result).toBe(tokens); // You can replace with the actual expected count if known
+ expect(result).toBe(tokens);
});
});
@@ -28,12 +29,46 @@ describe("Token Count Functions", () => {
const result = tokenCount({ model: "gpt-4", text: 1234 });
expect(result).toBe(2);
});
+
+ it("should return correct token count for empty string", () => {
+ const result = tokenCount({
+ model: "gpt-4",
+ text: "",
+ });
+ expect(result).toBe(0);
+ });
+
+ it("should return correct token count for very long string", () => {
+ const longString = "A".repeat(10000);
+ const result = tokenCount({
+ model: "gpt-4",
+ text: longString,
+ });
+ expect(result).toBeDefined();
+ expect(result).toBe(1250);
+ });
+
+ it("should return undefined for null text input", () => {
+ const result = tokenCount({
+ model: "gpt-4",
+ text: null,
+ });
+ expect(result).toBeUndefined();
+ });
+ it("should return undefined for undefined text input", () => {
+ const result = tokenCount({
+ model: "gpt-4",
+ text: undefined,
+ });
+ expect(result).toBeUndefined();
+ });
});
describe("token count for chat messages", () => {
[
{ model: "gpt-4", tokens: 44 },
- { model: "gpt-3.5-turbo-16k-0613", tokens: 47 },
+ { model: "gpt-3.5-turbo-16k-0613", tokens: 44 },
+ { model: "claude-instant-1.2", tokens: 48 },
].forEach(({ model, tokens }) => {
it(`should return token count ${tokens} for ${model}`, () => {
const result = tokenCount({
@@ -48,7 +83,7 @@ describe("Token Count Functions", () => {
],
});
expect(result).toBeDefined();
- expect(result).toBe(44);
+ expect(result).toBe(tokens);
});
});
@@ -60,6 +95,14 @@ describe("Token Count Functions", () => {
expect(result).toBe(7);
});
+ it("should return for empty array", () => {
+ const result = tokenCount({
+ model: "gpt-4",
+ text: [],
+ });
+ expect(result).toBeUndefined();
+ });
+
it("should return for array of invalid object", () => {
const result = tokenCount({
model: "gpt-4",
diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.ts
index 786d2321fc..b4564aafdd 100644
--- a/src/features/ingest/lib/usage.ts
+++ b/src/features/ingest/lib/usage.ts
@@ -9,30 +9,6 @@ import { countTokens } from "@anthropic-ai/tokenizer";
import { type Pricing } from "@prisma/client";
import { Decimal } from "decimal.js";
-export function tokenCount(p: {
- model: string;
- text: unknown;
-}): number | undefined {
- if (isString(p.text)) {
- return stringTokenCount({ model: p.model, text: p.text });
- } else if (isChatMessageArray(p.text)) {
- console.log("isChatMessageArray");
- if (!isValidModel(p.model)) {
- console.log(`Unknown model ${p.model} for chat model`);
- return undefined;
- }
- return numTokensFromMessages({
- model: p.model,
- messages: p.text,
- });
- } else {
- console.log(
- "It is neither a string nor a ChatMessage array, converting into string",
- );
- return stringTokenCount({ model: p.model, text: JSON.stringify(p.text) });
- }
-}
-
type ChatMessage = {
role: string;
name?: string;
@@ -44,7 +20,42 @@ type TokenCalculationParams = {
model: TiktokenModel;
};
-function numTokensFromMessages(params: TokenCalculationParams) {
+export function tokenCount(p: {
+ model: string;
+ text: unknown;
+}): number | undefined {
+ if (
+ p.text === null ||
+ p.text === undefined ||
+ (Array.isArray(p.text) && p.text.length === 0)
+ ) {
+ return undefined;
+ } else if (isOpenAiModel(p.model)) {
+ return isChatMessageArray(p.text)
+ ? openAiChatTokenCount({
+ model: p.model,
+ messages: p.text,
+ })
+ : isString(p.text)
+ ? openAiStringTokenCount({ model: p.model, text: p.text })
+ : openAiStringTokenCount({
+ model: p.model,
+ text: JSON.stringify(p.text),
+ });
+ } else if (isClaudeModel(p.model)) {
+ return isString(p.text)
+ ? claudeStringTokenCount({ model: p.model, text: p.text })
+ : claudeStringTokenCount({
+ model: p.model,
+ text: JSON.stringify(p.text),
+ });
+ } else {
+ console.log("Unknown model provider", p.model);
+ return undefined;
+ }
+}
+
+function openAiChatTokenCount(params: TokenCalculationParams) {
let encoding: Tiktoken;
try {
encoding = encoding_for_model(params.model);
@@ -70,10 +81,13 @@ function numTokensFromMessages(params: TokenCalculationParams) {
} else if (params.model === "gpt-3.5-turbo-0301") {
tokens_per_message = 4; // every message follows <|start|>{role/name}\n{content}<|end|>\n
tokens_per_name = -1; // if there's a name, the role is omitted
- } else if (params.model.includes("gpt-3.5-turbo")) {
- return numTokensFromMessages({ ...params, model: "gpt-3.5-turbo-0613" });
+ } else if (
+ params.model.includes("gpt-3.5-turbo") ||
+ params.model.startsWith("gpt-3.5")
+ ) {
+ return openAiChatTokenCount({ ...params, model: "gpt-3.5-turbo-0613" });
} else if (params.model.includes("gpt-4")) {
- return numTokensFromMessages({ ...params, model: "gpt-4-0613" });
+ return openAiChatTokenCount({ ...params, model: "gpt-4-0613" });
} else {
console.error(`Not implemented for model ${params.model}`);
throw new Error(`Not implemented for model ${params.model}`);
@@ -96,22 +110,20 @@ function numTokensFromMessages(params: TokenCalculationParams) {
return num_tokens;
}
-export function stringTokenCount(p: {
- model: string;
- text: string;
-}): number | undefined {
+const openAiStringTokenCount = (p: { model: string; text: string }) => {
if (p.model.toLowerCase().startsWith("gpt")) {
return getTokens("cl100k_base", p.text);
}
if (p.model.toLowerCase().startsWith("text-davinci")) {
return getTokens("p50k_base", p.text);
}
- if (p.model.toLowerCase().startsWith("claude")) {
- return countTokens(p.text);
- }
console.log("Unknown model", p.model);
return undefined;
-}
+};
+
+const claudeStringTokenCount = (p: { model: string; text: string }) => {
+ return countTokens(p.text);
+};
const getTokens = (name: TiktokenEncoding, text: string) => {
const encoding = get_encoding(name);
@@ -124,7 +136,11 @@ function isString(value: unknown): value is string {
return typeof value === "string";
}
-function isValidModel(model: string): model is TiktokenModel {
+function isClaudeModel(model: string) {
+ return model.toLowerCase().startsWith("claude");
+}
+
+function isOpenAiModel(model: string): model is TiktokenModel {
return (
[
"text-davinci-003",
@@ -163,6 +179,7 @@ function isValidModel(model: string): model is TiktokenModel {
"gpt-4-32k",
"gpt-4-32k-0314",
"gpt-4-32k-0613",
+ "gpt-3.5",
"gpt-3.5-turbo",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0613",