Skip to content

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

fix: fix token configuration (#951)

Max Deichmannb9a3f33e9785
diff --git a/prisma/migrations/20240124164148_correct_models/migration.sql b/prisma/migrations/20240124164148_correct_models/migration.sql
new file mode 100644
index 0000000000..17cf321523
--- /dev/null
+++ b/prisma/migrations/20240124164148_correct_models/migration.sql
@@ -0,0 +1,42 @@
+-- This is an empty migration.
+
+DELETE FROM models
+WHERE id in ('clrntjt89000908jwhvkz5crm', 'clrntjt89000908jwhvkz5crg', 'clrntjt89000108jwcou1af71', 'clrntjt89000208jwawjr894q', 'clrntjt89000308jw0jtfa4rs', 'clrntjt89000408jwc2c93h6i', 'clrntjt89000508jw192m64qi', 'clrntjt89000608jw4m3x5s55', 'clrp1wopz000708l079w02hkc');
+
+
+
+INSERT INTO models (
+ id,
+ project_id,
+ model_name,
+ match_pattern,
+ start_date,
+ input_price,
+ output_price,
+ total_price,
+ unit,
+ tokenizer_id,
+ tokenizer_config
+)
+VALUES
+ -- nothing earlier required for ada
+ ('clrntjt89000908jwhvkz5crm', NULL, 'text-embedding-ada-002', '(?i)^(text-embedding-ada-002)$', '2022-12-06', NULL, NULL, 0.0000001, 'TOKENS', 'openai', '{"tokenizerModel": "text-embedding-ada-002"}'),
+ ('clrntjt89000908jwhvkz5crg', NULL, 'text-embedding-ada-002-v2', '(?i)^(text-embedding-ada-002-v2)$', '2022-12-06', NULL, NULL, 0.0000001, 'TOKENS', 'openai', '{"tokenizerModel": "text-embedding-ada-002"}'),
+
+
+
+
+ -- -- legacy price 2023-08-22 https://platform.openai.com/docs/deprecations/2023-07-06-gpt-and-embeddings
+ ('clrntjt89000108jwcou1af71', NULL, 'text-ada-001', '(?i)^(text-ada-001)$', NULL, NULL, NULL, 0.000004, 'TOKENS', 'openai', '{"tokenizerModel": "text-ada-001"}'),
+ ('clrntjt89000208jwawjr894q', NULL, 'text-babbage-001', '(?i)^(text-babbage-001)$', NULL, NULL, NULL, 0.0000005, 'TOKENS', 'openai', '{"tokenizerModel": "text-babbage-001"}'),
+ ('clrntjt89000308jw0jtfa4rs', NULL, 'text-curie-001', '(?i)^(text-curie-001)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', '{"tokenizerModel": "text-curie-001"}'),
+ ('clrntjt89000408jwc2c93h6i', NULL, 'text-davinci-001', '(?i)^(text-davinci-001)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', '{"tokenizerModel": "text-davinci-001"}'),
+ ('clrntjt89000508jw192m64qi', NULL, 'text-davinci-002', '(?i)^(text-davinci-002)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', '{"tokenizerModel": "text-davinci-002"}'),
+ ('clrntjt89000608jw4m3x5s55', NULL, 'text-davinci-003', '(?i)^(text-davinci-003)$', NULL, NULL, NULL, 0.00002, 'TOKENS', 'openai', '{"tokenizerModel": "text-davinci-003"}'),
+
+ ('clrs2dnql000108l46vo0gp2t', NULL, 'babbage-002', '(?i)^(babbage-002)$', NULL, 0.0000004, 0.0000016, 0.0000005, 'TOKENS', 'openai', '{"tokenizerModel": "babbage-002"}'),
+ ('clrs2ds35000208l4g4b0hi3u', NULL, 'davinci-002', '(?i)^(davinci-002)$', NULL, 0.0000060, 0.0000120, 0.0000005, 'TOKENS', 'openai', '{"tokenizerModel": "davinci-002"}')
+
+
+
+
diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.ts
index 3e078e94ca..60c0548d27 100644
--- a/src/__tests__/usage.servertest.ts
+++ b/src/__tests__/usage.servertest.ts
@@ -26,6 +26,7 @@ describe("Token Count Functions", () => {
describe("token count for strings", () => {
[
{ model: "gpt-3.5-turbo", tokenizer: "openai", tokens: 114 },
+ { model: "text-embedding-ada-002", tokenizer: "openai", tokens: 114 },
{ model: "gpt-4-1106-preview", tokenizer: "openai", tokens: 114 },
{ model: "gpt-4-vision-preview", tokenizer: "openai", tokens: 114 },
{ model: "claude", tokenizer: "claude", tokens: 118 },
diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.ts
index c69913efe6..1861053435 100644
--- a/src/features/ingest/lib/usage.ts
+++ b/src/features/ingest/lib/usage.ts
@@ -1,15 +1,30 @@
-import { isTiktokenModel } from "@/src/utils/types";
+import { isChatModel, isTiktokenModel } from "@/src/utils/types";
import { countTokens } from "@anthropic-ai/tokenizer";
import { type Model } from "@prisma/client";
import {
type TiktokenModel,
type Tiktoken,
- type TiktokenEncoding,
get_encoding,
encoding_for_model,
} from "tiktoken";
import { z } from "zod";
+const OpenAiTokenConfig = z.object({
+ tokenizerModel: z.string().refine(isTiktokenModel, {
+ message: "Unknown tiktoken model",
+ }),
+});
+
+const OpenAiChatTokenConfig = z.object({
+ tokenizerModel: z
+ .string()
+ .refine((m) => isTiktokenModel(m) && isChatModel(m), {
+ message: "Chat model expected",
+ }),
+ tokensPerMessage: z.number(),
+ tokensPerName: z.number(),
+});
+
export function tokenCount(p: {
model: Model;
text: unknown;
@@ -23,20 +38,8 @@ export function tokenCount(p: {
}
if (p.model.tokenizerId === "openai") {
- // check if the tokenizerConfig is a valid OpenAiTokenConfig
- const parsedConfig = OpenAiTokenConfig.safeParse(p.model.tokenizerConfig);
- if (!parsedConfig.success) {
- console.error(
- `Invalid tokenizer config for model ${p.model.id}: ${JSON.stringify(
- p.model.tokenizerConfig,
- )}`,
- );
- return undefined;
- }
-
return openAiTokenCount({
- internalModel: p.model.modelName,
- config: parsedConfig.data,
+ model: p.model,
text: p.text,
});
} else if (p.model.tokenizerId === "claude") {
@@ -56,47 +59,57 @@ type ChatMessage = {
content: string;
};
-type TokenCalculationParams = {
- messages: ChatMessage[];
- model: TiktokenModel;
- config: z.infer<typeof OpenAiTokenConfig>;
-};
+function openAiTokenCount(p: { model: Model; text: unknown }) {
+ const config = OpenAiTokenConfig.safeParse(p.model.tokenizerConfig);
+ if (!config.success) {
+ console.error(
+ `Invalid tokenizer config for model ${p.model.id}: ${JSON.stringify(
+ p.model.tokenizerConfig,
+ )}, ${JSON.stringify(config.error)}`,
+ );
+ return undefined;
+ }
-function openAiTokenCount(p: {
- internalModel: string;
- text: unknown;
- config: z.infer<typeof OpenAiTokenConfig>;
-}) {
- if (!isOpenAiModel(p.internalModel)) return undefined;
-
- return isChatMessageArray(p.text)
- ? openAiChatTokenCount({
- model: p.internalModel,
- messages: p.text,
- config: p.config,
- })
- : isString(p.text)
- ? openAiStringTokenCount({ model: p.internalModel, text: p.text })
- : openAiStringTokenCount({
- model: p.internalModel,
- text: JSON.stringify(p.text),
- });
+ let result = undefined;
+
+ if (isChatMessageArray(p.text) && isChatModel(config.data.tokenizerModel)) {
+ // check if the tokenizerConfig is a valid chat config
+ const parsedConfig = OpenAiChatTokenConfig.safeParse(
+ p.model.tokenizerConfig,
+ );
+ if (!parsedConfig.success) {
+ console.error(
+ `Invalid tokenizer config for chat model ${
+ p.model.id
+ }: ${JSON.stringify(p.model.tokenizerConfig)}`,
+ );
+ return undefined;
+ }
+ result = openAiChatTokenCount({
+ messages: p.text,
+ config: parsedConfig.data,
+ });
+ } else {
+ result = isString(p.text)
+ ? getTokensByModel(config.data.tokenizerModel, p.text)
+ : getTokensByModel(config.data.tokenizerModel, JSON.stringify(p.text));
+ }
+ return result;
}
+
function claudeTokenCount(p: { internalModel: string; text: unknown }) {
return isString(p.text)
? countTokens(p.text)
: countTokens(JSON.stringify(p.text));
}
-const OpenAiTokenConfig = z.object({
- tokensPerMessage: z.number(),
- tokensPerName: z.number(),
- tokenizerModel: z.string().refine(isTiktokenModel, {
- message: "Unknown model",
- }),
-});
+function openAiChatTokenCount(params: {
+ messages: ChatMessage[];
+ config: z.infer<typeof OpenAiChatTokenConfig>;
+}) {
+ const model = params.config.tokenizerModel;
+ if (!isTiktokenModel(model)) return undefined;
-function openAiChatTokenCount(params: TokenCalculationParams) {
let numTokens = 0;
params.messages.forEach((message) => {
numTokens += params.config.tokensPerMessage;
@@ -118,7 +131,7 @@ function openAiChatTokenCount(params: TokenCalculationParams) {
"functionCall",
].some((k) => k === key)
) {
- numTokens += getTokensByModel(params.config.tokenizerModel, value);
+ numTokens += getTokensByModel(model, value);
}
if (key === "name") {
numTokens += params.config.tokensPerName;
@@ -130,27 +143,6 @@ function openAiChatTokenCount(params: TokenCalculationParams) {
return numTokens;
}
-const openAiStringTokenCount = (p: { model: string; text: string }) => {
- if (
- p.model.toLowerCase().startsWith("gpt") ||
- p.model.toLowerCase().includes("ada")
- ) {
- return getTokensByEncoding("cl100k_base", p.text);
- }
- if (p.model.toLowerCase().startsWith("text-davinci")) {
- return getTokensByEncoding("p50k_base", p.text);
- }
- console.log("Unknown model", p.model);
- return undefined;
-};
-
-const getTokensByEncoding = (name: TiktokenEncoding, text: string) => {
- const encoding = get_encoding(name);
- const tokens = encoding.encode(text);
-
- return tokens.length;
-};
-
const getTokensByModel = (model: TiktokenModel, text: string) => {
let encoding: Tiktoken;
try {
@@ -167,10 +159,6 @@ function isString(value: unknown): value is string {
return typeof value === "string";
}
-function isOpenAiModel(model: string): model is TiktokenModel {
- return !!model.includes(model as TiktokenModel);
-}
-
function isChatMessageArray(value: unknown): value is ChatMessage[] {
if (!Array.isArray(value)) {
return false;
diff --git a/src/server/api/services/EventProcessor.ts b/src/server/api/services/EventProcessor.ts
index 9cab8d49af..ff87c09d90 100644
--- a/src/server/api/services/EventProcessor.ts
+++ b/src/server/api/services/EventProcessor.ts
@@ -319,7 +319,6 @@ export class ObservationProcessor implements EventProcessor {
model?: Model,
existingObservation?: Observation,
) {
- console.log("calculate tokens for ", model);
const newPromptTokens =
body.usage?.input ??
((body.input || existingObservation?.input) && model && model.tokenizerId
diff --git a/src/utils/types.ts b/src/utils/types.ts
index 8dd70f4db7..13bdff4bee 100644
--- a/src/utils/types.ts
+++ b/src/utils/types.ts
@@ -54,6 +54,30 @@ export function isValidOption(
);
}
+const chatModels = [
+ "gpt-4",
+ "gpt-4-0314",
+ "gpt-4-0613",
+ "gpt-4-32k",
+ "gpt-4-32k-0314",
+ "gpt-4-32k-0613",
+ "gpt-3.5-turbo",
+ "gpt-35-turbo",
+ "gpt-3.5-turbo-0301",
+ "gpt-3.5-turbo-0613",
+ "gpt-3.5-turbo-1106",
+ "gpt-3.5-turbo-16k",
+ "gpt-3.5-turbo-16k-0613",
+ "gpt-4-1106-preview",
+ "gpt-4-vision-preview",
+];
+
+export type ChatModel = (typeof chatModels)[number];
+
+export const isChatModel = (model: string): model is ChatModel => {
+ return chatModels.includes(model);
+};
+
export const isTiktokenModel = (model: string): model is TiktokenModel => {
return [
"davinci-002",