def METHOD_NAME(messages: list[ChatMessage], max_prompt_size, model_name) -> list[ChatMessage]:
    """Truncate messages to fit within max prompt size supported by model"""
    if "llama" in model_name:
        encoder = LlamaTokenizerFast.from_pretrained(tokenizer[model_name])
    else:
        encoder = tiktoken.encoding_for_model(model_name)
    system_message = messages.pop()
    system_message_tokens = len(encoder.encode(system_message.content))
    tokens = sum([len(encoder.encode(message.content)) for message in messages])
    while (tokens + system_message_tokens) > max_prompt_size and len(messages) > 1:
        messages.pop()
        tokens = sum([len(encoder.encode(message.content)) for message in messages])
    # Truncate current message if still over max supported prompt size by model
    if (tokens + system_message_tokens) > max_prompt_size:
        current_message = "\n".join(messages[0].content.split("\n")[:-1])
        original_question = "\n".join(messages[0].content.split("\n")[-1:])
        original_question_tokens = len(encoder.encode(original_question))
        remaining_tokens = max_prompt_size - original_question_tokens - system_message_tokens
        truncated_message = encoder.decode(encoder.encode(current_message)[:remaining_tokens]).strip()
        logger.debug(
            f"Truncate current message to fit within max prompt size of {max_prompt_size} supported by {model_name} model:\n {truncated_message}"
        )
        messages = [ChatMessage(content=truncated_message + original_question, role=messages[0].role)]
    return messages + [system_message]