🪢 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
fix: fix toktoken tokenizer for unexpected input (#950)
Max Deichmannc2f612d0b891
diff --git a/src/__tests__/usage.servertest.ts b/src/__tests__/usage.servertest.tsindex aec3323386..3e078e94ca 100644--- a/src/__tests__/usage.servertest.ts+++ b/src/__tests__/usage.servertest.ts@@ -50,6 +50,49 @@ describe("Token Count Functions", () => {expect(result).toBeUndefined();});+ it("check extensive openai chat message", () => {+ const result = tokenCount({+ model: generateModel("gpt-3.5-turbo", "openai"),+ text: [+ {+ role: "system",+ content: "some test",+ id: "some-id",+ isPersisted: true,+ },+ {+ id: "some-id",+ content: "some test",+ role: "user",+ timestamp: "2024-01-00:00:00.488Z",+ isPersisted: true,+ },+ {+ id: "some id",+ content: "some test",+ role: "user",+ timestamp: "2024-01-24T10:00:00.929Z",+ isPersisted: true,+ },+ {+ content: true,+ role: "user",+ id: "some id",+ },+ {+ role: "system",+ content: "This is some content",+ },+ {+ id: "another id",+ role: "assistant",+ content: "This is some content",+ },+ ],+ });+ expect(result).toBe(137);+ });+it("should return for invalid text type", () => {const result = tokenCount({model: generateModel("gpt-4", "openai"),diff --git a/src/features/ingest/lib/usage.ts b/src/features/ingest/lib/usage.tsindex f738dd54e1..c69913efe6 100644--- a/src/features/ingest/lib/usage.ts+++ b/src/features/ingest/lib/usage.ts@@ -103,7 +103,21 @@ function openAiChatTokenCount(params: TokenCalculationParams) {Object.keys(message).forEach((key) => {const value = message[key as keyof typeof message];- if (value) {+ if (+ // check API docs for available keys: https://platform.openai.com/docs/api-reference/chat/create?lang=node.js+ // memory access out of bounds error in tiktoken if unexpected key and value of type boolean+ // expected keys with booleans work+ value &&+ [+ "content",+ "role",+ "name",+ "tool_calls",+ "function_call",+ "toolCalls",+ "functionCall",+ ].some((k) => k === key)+ ) {numTokens += getTokensByModel(params.config.tokenizerModel, value);}if (key === "name") {