token_processor.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import tiktoken
  4. # Assuming result_average_token is a constant, use UPPER_CASE for its name to follow Python conventions
  5. AVERAGE_TOKENS_PER_RESULT = 100
  6. def get_token_limit_for_model(model: str) -> int:
  7. """Returns the token limit for a given model."""
  8. if model == "gpt-3.5-turbo-16k":
  9. return 16384
  10. # Consider adding an else statement or default return value if more models are expected
  11. def fetch_encoding_for_model(model="gpt-3.5-turbo-16k"):
  12. """Fetches the encoding for the specified model."""
  13. try:
  14. return tiktoken.encoding_for_model(model)
  15. except KeyError:
  16. print("Warning: Model not found. Using 'cl100k_base' encoding as default.")
  17. return tiktoken.get_encoding("cl100k_base")
  18. def calculate_num_tokens_for_message(message: str, model="gpt-3.5-turbo-16k") -> int:
  19. """Calculates the number of tokens used by a message."""
  20. encoding = fetch_encoding_for_model(model)
  21. # Added 3 to account for priming with assistant's reply, as per original comment
  22. return len(encoding.encode(message)) + 3
  23. def split_text_into_tokenized_chunks(context: dict, text_to_split: str) -> list[str]:
  24. """Splits a long string into substrings based on token length constraints."""
  25. max_tokens_per_chunk = (
  26. get_token_limit_for_model(context["model"]) -
  27. calculate_num_tokens_for_message(context["question_prompt_template"]) -
  28. AVERAGE_TOKENS_PER_RESULT * context["total_questions"]
  29. )
  30. substrings = []
  31. chunk_tokens = []
  32. encoding = fetch_encoding_for_model(context["model"])
  33. text_tokens = encoding.encode(text_to_split)
  34. for token in text_tokens:
  35. if len(chunk_tokens) + 1 > max_tokens_per_chunk:
  36. substrings.append(encoding.decode(chunk_tokens).strip())
  37. chunk_tokens = [token]
  38. else:
  39. chunk_tokens.append(token)
  40. if chunk_tokens:
  41. substrings.append(encoding.decode(chunk_tokens).strip())
  42. return substrings