code: def truncate_msgs_for_token_limit(
      messages, model_name, max_tokens, truncate="first"
  ):
      """
      Truncates message list to fit within the token limit.
      Note: first message for chat completion models are general directives with the system role, which will ideally be kept at all times.
      """  # noqa
      encoder = tiktoken.encoding_for_model(model_name)
      sys_priming = messages[0:1]
      n_tokens = count_tokens(messages, encoder, model_name)
      while n_tokens > max_tokens:
          if len(messages) == 2:
              return messages[
                  :-1
              ]  # edge case: if limit is surpassed by just one input, we remove initial instruction
          elif len(messages) == 1:
              return messages
  
          if truncate == "first":
              messages = sys_priming + messages[2:]
          else:
              messages = sys_priming + messages[1:-1]
  
          n_tokens = count_tokens(messages, encoder, model_name)
      return messages
  
file_path: mindsdb/mindsdb/integrations/handlers/openai_handler/helpers.py
imports: import os
  from typing import List
  import random
  import time
  import math
  import openai
  from openai import OpenAI
  import tiktoken
  import mindsdb.utilities.profiler
  from mindsdb.integrations.handlers.openai_handler.constants import OPENAI_API_BASE
label_desc: Use image node_id 2 for calling a global function with example usage: truncate_msgs_for_token_limit(messages, model_name, max_tokens, truncate) and returns: messages, messages, messages