from ..base import compute_tokens
from .chat import get_messages
from .protocol import CountTokensRequest, CountTokensResponse
from .helpers import create_500_error

def count_messages_tokens(request: CountTokensRequest) -> CountTokensResponse:
    try:
        input_tokens = 0
        for msg in get_messages(request):
            input_tokens += compute_tokens(
                msg.get('content', ''), request.model)
        return CountTokensResponse(input_tokens=input_tokens)
    except Exception as e:
        return create_500_error(str(e))
