🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
Accurate token calculation (#139)
Maximilian Deichmann89e084e5b88e
diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.tsnew file mode 100644index 0000000000..eaeb9fad39--- /dev/null+++ b/src/__tests__/usage.servertest.ts@@ -0,0 +1,71 @@+import { tokenCount } from "@/src/features/ingest/lib/usage";++describe("Token Count Functions", () => {+ describe("token count for strings", () => {+ [+ { model: "gpt-3.5", tokens: 114 },+ { model: "claude", tokens: 118 },+ ].forEach(({ model, tokens }) => {+ it(`should return token count ${tokens} for ${model}`, () => {+ const result = tokenCount({+ model: model,+ 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+ });+ });++ it("should return undefined for unknown model", () => {+ const result = tokenCount({+ model: "unknown-model",+ text: "Hello, World!",+ });+ expect(result).toBeUndefined();+ });++ it("should return for invalid text type", () => {+ const result = tokenCount({ model: "gpt-4", text: 1234 });+ expect(result).toBe(2);+ });+ });++ describe("token count for chat messages", () => {+ [+ { model: "gpt-4", tokens: 44 },+ { model: "gpt-3.5-turbo-16k-0613", tokens: 47 },+ ].forEach(({ model, tokens }) => {+ it(`should return token count ${tokens} for ${model}`, () => {+ const result = tokenCount({+ model: model,+ text: [+ { role: "system", content: "You are a helpful assistant." },+ { role: "user", content: "Who won the world series in 2020?" },+ {+ role: "assistant",+ content: "The Los Angeles Dodgers won the World Series in 2020.",+ },+ ],+ });+ expect(result).toBeDefined();+ expect(result).toBe(44);+ });+ });++ it("should return for non array", () => {+ const result = tokenCount({+ model: "gpt-4",+ text: { role: "Helo world" },+ });+ expect(result).toBe(7);+ });++ it("should return for array of invalid object", () => {+ const result = tokenCount({+ model: "gpt-4",+ text: [{ role: "Helo world" }],+ });+ expect(result).toBe(9);+ });+ });+});diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.tsindex a6bc8eca75..208939a749 100644--- a/src/features/ingest/lib/usage.ts+++ b/src/features/ingest/lib/usage.ts@@ -1,14 +1,105 @@-import { type TiktokenEncoding, get_encoding } from "tiktoken";+import {+ type TiktokenEncoding,+ get_encoding,+ encoding_for_model,+ type TiktokenModel,+ type Tiktoken,+} from "tiktoken";import { countTokens } from "@anthropic-ai/tokenizer";import { type Pricing } from "@prisma/client";import { Decimal } from "decimal.js";export function tokenCount(p: {model: string;- text: string;+ text: unknown;}): number | undefined {- if (!p.model || !p.text) return 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;+ content: string;+};+type TokenCalculationParams = {+ messages: ChatMessage[];+ model: TiktokenModel;+};++function numTokensFromMessages(params: TokenCalculationParams) {+ let encoding: Tiktoken;+ try {+ encoding = encoding_for_model(params.model);+ } catch (KeyError) {+ console.log("Warning: model not found. Using cl100k_base encoding.");+ encoding = get_encoding("cl100k_base");+ }+ let tokens_per_message = 0;+ let tokens_per_name = 0;++ if (+ [+ "gpt-3.5-turbo-0613",+ "gpt-3.5-turbo-16k-0613",+ "gpt-4-0314",+ "gpt-4-32k-0314",+ "gpt-4-0613",+ "gpt-4-32k-0613",+ ].includes(params.model)+ ) {+ tokens_per_message = 3;+ tokens_per_name = 1;+ } 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-0301")) {+ return numTokensFromMessages({ ...params, model: "gpt-3.5-turbo-0613" });+ } else if (params.model.includes("gpt-4")) {+ return numTokensFromMessages({ ...params, model: "gpt-4-0314" });+ } else {+ console.error(`Not implemented for model ${params.model}`);+ throw new Error(`Not implemented for model ${params.model}`);+ }+ let num_tokens = 0;+ params.messages.forEach((message) => {+ num_tokens += tokens_per_message;++ Object.keys(message).forEach((key) => {+ const value = message[key as keyof typeof message];+ if (value) {+ num_tokens += encoding.encode(value).length;+ }+ if (key === "name") {+ num_tokens += tokens_per_name;+ }+ });+ });+ num_tokens += 3; // every reply is primed with <| start |> assistant <| message |>+ return num_tokens;+}++export function stringTokenCount(p: {+ model: string;+ text: string;+}): number | undefined {if (p.model.toLowerCase().startsWith("gpt")) {return getTokens("cl100k_base", p.text);}@@ -29,6 +120,75 @@ const getTokens = (name: TiktokenEncoding, text: string) => {return tokens.length;};+function isString(value: unknown): value is string {+ return typeof value === "string";+}++function isValidModel(model: string): model is TiktokenModel {+ return (+ [+ "text-davinci-003",+ "text-davinci-002",+ "text-davinci-001",+ "text-curie-001",+ "text-babbage-001",+ "text-ada-001",+ "davinci",+ "curie",+ "babbage",+ "ada",+ "code-davinci-002",+ "code-davinci-001",+ "code-cushman-002",+ "code-cushman-001",+ "davinci-codex",+ "cushman-codex",+ "text-davinci-edit-001",+ "code-davinci-edit-001",+ "text-embedding-ada-002",+ "text-similarity-davinci-001",+ "text-similarity-curie-001",+ "text-similarity-babbage-001",+ "text-similarity-ada-001",+ "text-search-davinci-doc-001",+ "text-search-curie-doc-001",+ "text-search-babbage-doc-001",+ "text-search-ada-doc-001",+ "code-search-babbage-code-001",+ "code-search-ada-code-001",+ "gpt2",+ "gpt-4",+ "gpt-4-0314",+ "gpt-4-0613",+ "gpt-4-32k",+ "gpt-4-32k-0314",+ "gpt-4-32k-0613",+ "gpt-3.5-turbo",+ "gpt-3.5-turbo-0301",+ "gpt-3.5-turbo-0613",+ "gpt-3.5-turbo-16k",+ "gpt-3.5-turbo-16k-0613",+ ].find((m) => m === model) !== undefined+ );+}++function isChatMessageArray(value: unknown): value is ChatMessage[] {+ if (!Array.isArray(value)) {+ return false;+ }++ return value.every(+ (item: unknown) =>+ typeof item === "object" &&+ item !== null &&+ "role" in item &&+ typeof item.role === "string" &&+ "content" in item &&+ typeof item.content === "string" &&+ (!("name" in item) || typeof item.name === "string"),+ );+}+export function calculateTokenCost(pricingList: Pricing[],input: {diff --git a/src/pages/api/public/generations.ts b/src/pages/api/public/generations.tsindex 3c88085ea9..128917f2d2 100644--- a/src/pages/api/public/generations.ts+++ b/src/pages/api/public/generations.ts@@ -156,7 +156,7 @@ export default async function handler((model && prompt? tokenCount({model: model,- text: JSON.stringify(prompt),+ text: prompt,}): undefined);const newCompletionTokens =@@ -424,7 +424,7 @@ const patchGeneration = async ((mergedModel && prompt? tokenCount({model: mergedModel,- text: JSON.stringify(prompt),+ text: prompt,}): undefined);