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
The provided Python function appears to generate a list of messages with a specified number of tokens, using a random word generator to fill in the tokens if necessary. It also caches the generated prompt and its token count to avoid recalculating it in future calls.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.