Skip to content

Commit

Permalink
refactor: only fallback to approximate if tiktoken fails (#1898)
Browse files Browse the repository at this point in the history
  • Loading branch information
iloveitaly authored Jul 9, 2023
1 parent 99b1985 commit 3635d96
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions langchain/src/base_language/count_tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,17 @@ export const calculateMaxTokens = async ({
prompt,
modelName,
}: CalculateMaxTokenProps) => {
// fallback to approximate calculation if tiktoken is not available
let numTokens = Math.ceil(prompt.length / 4);
let numTokens;

try {
numTokens = (await encodingForModel(modelName)).encode(prompt).length;
} catch (error) {
console.warn(
"Failed to calculate number of tokens, falling back to approximate count"
);

// fallback to approximate calculation if tiktoken is not available
numTokens = Math.ceil(prompt.length / 4);
}

const maxTokens = getModelContextSize(modelName);
Expand Down

1 comment on commit 3635d96

@vercel
Copy link

@vercel vercel bot commented on 3635d96 Jul 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.