What does the below python function do? Show me an expected example output for tokens =…
- User
What does the below python function do? Show me an expected example output for tokens = 20
global CACHED_PROMPT global CACHED_MESSAGES_TOKENS try: r = wonderwords.RandomWord() messages = [{"role":"user", "content":str(time.time()) + " "}] if max_tokens is not None: messages.append({"role":"user", "content":str(time.time()) + f" write a long essay about life in at least {max_tokens} tokens"}) messages_tokens = 0
codeif len(CACHED_PROMPT) > 0: messages[0]["content"] += CACHED_PROMPT messages_tokens = CACHED_MESSAGES_TOKENS else: prompt = "" base_prompt = messages[0]["content"] while True: messages_tokens = num_tokens_from_messages(messages, model) remaining_tokens = tokens - messages_tokens if remaining_tokens <= 0: break prompt += " ".join(r.random_words(amount=math.ceil(remaining_tokens/4))) + " " messages[0]["content"] = base_prompt + prompt CACHED_PROMPT = prompt CACHED_MESSAGES_TOKENS = messages_tokensexcept Exception as e: print (e)
return (messages, messages_tokens)
def num_tokens_from_messages(messages: list, model: str) -> int: nonlocal tokenizer if tokenizer is None: tokenizer = AutoTokenizer.from_pretrained(model)
codeif hasattr(tokenizer, 'apply_chat_template'): formatted_messages = tokenizer.apply_chat_template(messages, tokenize=False) tokens = tokenizer.encode(formatted_messages) else: tokens = tokenizer.encode(str(messages)) # Fallback if chat template is not available Assistant
This Python function generates a user message with a specified number of tokens, which can be used as a prompt for a language model. The function uses the
wonderwordslibrary to generate random words and theAutoTokenizerclass from the Hugging Face Transformers library to count the number of tokens in the message.The function first initializes an empty list
messageswith a single user message containing a timestamp. If themax_tokensargument is provided, the function appends another user message to themessageslist with a prompt to write a long essay about life with at leastmax_tokenstokens.The function then checks if there is a cached prompt available in the
CACHED_PROMPTvariable. If a cached prompt is available, the function appends it to the first user message in themessageslist and sets the variable to the number of tokens in the cached prompt. If no cached prompt is available, the function generates a new prompt by appending random words to the first user message until the desired number of tokens is reached. The generated prompt is then cached in the variable.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.