{"record":{"id":"61bc6eed7c0f3e16","repo":"BerriAI/litellm","slug":"text-and-messages-cannot-both-be-set","errorCode":null,"errorMessage":"text and messages cannot both be set","messagePattern":"text and messages cannot both be set","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"litellm/litellm_core_utils/token_counter.py","lineNumber":375,"sourceCode":"    default_token_count (Optional[int]): The default number of tokens to return for a message block, if an error occurs. Default is None.\n\n    Returns:\n    int: The number of tokens in the text.\n    \"\"\"\n    from litellm.utils import convert_list_message_to_dict\n\n    #########################################################\n    # Flag to disable token counter\n    # We've gotten reports of this consuming CPU cycles,\n    # exposing this flag to allow users to disable\n    # it to confirm if this is indeed the issue\n    #########################################################\n    if litellm.disable_token_counter is True:\n        return 0\n\n    verbose_logger.debug(\"messages in token_counter: %s, text in token_counter: %s\", messages, text)\n    if text is not None and messages is not None:\n        raise ValueError(\"text and messages cannot both be set\")\n    if use_default_image_token_count is None:\n        use_default_image_token_count = False\n\n    if text is not None:\n        if tools or tool_choice:\n            raise ValueError(\"tools or tool_choice cannot be set if using text\")\n        if isinstance(text, list):\n            text_to_count = \"\".join(t for t in text if isinstance(t, str))\n        elif isinstance(text, str):\n            text_to_count = text\n        count_function: Final = _get_count_function(model, custom_tokenizer)\n        num_tokens = count_function(text_to_count)\n\n    elif messages is not None:\n        new_messages: Final = cast(list[AllMessageValues], convert_list_message_to_dict(messages))\n        params: Final = _MessageCountParams(model, custom_tokenizer)\n        num_tokens = _count_messages(params, new_messages, use_default_image_token_count, default_token_count)\n        if count_response_tokens is False:","sourceCodeStart":357,"sourceCodeEnd":393,"githubUrl":"https://github.com/BerriAI/litellm/blob/6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d/litellm/litellm_core_utils/token_counter.py#L357-L393","documentation":"token_counter() refuses ambiguous input: passing both text= and messages= makes the count undefined (count the string or the conversation?), so it raises immediately. The function counts exactly one input kind per call; this is an API-contract error, not a model or tokenizer problem.","triggerScenarios":"Calling litellm.token_counter(text=\"hello\", messages=[...]) - usually a wrapper forwarding both kwargs, or a call site that accreted parameters during a refactor.","commonSituations":"Wrappers around token_counter that pass **kwargs through; refactors that add messages= to an existing text= call; example code merged from two snippets.","solutions":["Pass only one: embed the raw string as a message ({\"role\":\"user\",\"content\":text}) and use messages=, or drop messages= and keep text=.","Audit intermediate wrapper functions that forward both kwargs with **."],"exampleFix":"# before\nn = litellm.token_counter(model=\"gpt-4o\", text=\"summarize this\", messages=[{\"role\": \"user\", \"content\": \"hi\"}])\n\n# after\nn = litellm.token_counter(model=\"gpt-4o\", messages=[{\"role\": \"user\", \"content\": \"summarize this\"}])","handlingStrategy":"validation","validationCode":"def safe_token_count(model, text=None, messages=None, **kw):\n    if text is not None and messages is not None:\n        raise ValueError(\"pass exactly one of text or messages\")\n    return litellm.token_counter(model=model, text=text, messages=messages, **kw)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Never forward **kwargs blindly into token_counter from wrapper functions.","Standardize on messages= as the single counting input across the codebase."],"tags":["token-counter","validation","api-misuse"],"backgroundTag":null,"analyzedSha":"6c2dcb801bf2b75c18f1bb24140e7cf57465cc4d","analyzedAt":"2026-08-15T07:12:03.035Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}