v9.1.1
Menu

Token Budget Calculator

mediumPROPrompt Engineering & ParsingLLM 3: Applications & Evaluation

Calculate token budgets for a prompt with system, examples, and query.

Given a maximum context length and the token counts for each part, determine how many few-shot examples can fit while reserving space for the query and a completion buffer.

Input:

  • Line 1: max_tokens completion_buffer
  • Line 2: system_tokens query_tokens
  • Line 3: N (number of available examples)
  • Next N lines: example_tokens (tokens per example)

Output:

  • Line 1: Number of examples that fit
  • Line 2: Total tokens used (system + selected examples + query)
  • Line 3: Tokens remaining for completion

Example

Input
4096 512
200 100
5
150
150
150
150
150
Output
3
650
2934
Reasoning
  • The maximum available tokens for examples and the query are calculated by subtracting the completion buffer from the max tokens: 4096−512=35844096 - 512 = 3584.
  • We reserve space for the system and query tokens: 200+100=300200 + 100 = 300 tokens.
  • The remaining tokens for examples are 3584−300=32843584 - 300 = 3284, and each example takes 150 tokens, so we can fit 3284150≈21.9\frac{3284}{150} \approx 21.9 examples, but since we have 5 examples and the calculator can only use whole examples, we calculate how many examples fit: 3284÷150=21.93284 \div 150 = 21.9, so 21 examples would take 21⋅150=315021 \cdot 150 = 3150 tokens, exceeding the available tokens when adding system and query tokens, thus we try with fewer examples.
  • We try with 3 examples: 3⋅150=4503 \cdot 150 = 450 tokens for examples, 450+300=750450 + 300 = 750 total tokens used, leaving 4096−750−512=29344096 - 750 - 512 = 2934 tokens for completion, which fits within the completion buffer, so 3 examples fit.

Constraints

  • Select examples in order (first N that fit)
  • Must reserve completion_buffer tokens
  • Total used = system + examples + query
  • Available = max_tokens - completion_buffer

Learn this in

More from LLM 3: Applications & Evaluation

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.