AI Engineer Portal
Your personal operating system for career transition.
Exercise
Enforce per-request token budgets
Enforce Per-Request Token Budgets
LLM API costs are linear with token usage. Without enforcement, a single user pasting a 50,000-token document into a chat box can generate a $1-$5 API call. Multiply by thousands of users and you have a runaway cost event.
Token budget enforcement happens at prompt construction time — before the API call, not after. This exercise builds the enforcement layer.
What to build
Implement a PromptBudgetEnforcer that:
- Takes a
max_total_tokens: intandmodel: strto construct a budget-aware prompt. build(system: str, history: list[dict], context_chunks: list[str], user_query: str) -> BuiltPrompt— assembles the prompt while respecting the budget.- System prompt is always included first (it is always high-priority).
- User query is always included (it is what the user asked).
- History is included newest-first until the budget is hit.
- Context chunks are included in order until the budget is hit.
- If any component is truncated,
BuiltPrompt.truncated: boolis True andBuiltPrompt.truncated_components: list[str]lists what was cut.
- Use a simple token approximation: 1 token = 4 characters.
BuiltPromptshould contain the finalmessages: list[dict]ready to send to the API, plus budget metadata.- Add a
budget_remaining(built: BuiltPrompt) -> intmethod showing how many tokens are left for the model's response.
Constraints
- No external tokenizer libraries — use the 4-char approximation.
max_total_tokensincludes both the prompt tokens and the expected completion. Reserve 20% for completion.- Raise
ValueErrorif the system prompt + user query alone exceed the budget.
Api Async / medium / Step 10 of 23
Async and provider control
Make waiting behavior explicit. Timeouts, retries, and concurrency limits matter more than squeezing everything into one helper.
- - Uses async boundaries coherently
- - Makes timeout and retry decisions legible
- - Would be maintainable under provider instability
- - Is timeout behavior explicit?
- - Is retryable failure separate from terminal failure?
- - Would logs reveal what actually timed out?
Practice
Generate a variation
Generate a new exercise variation to deepen understanding or practice a related concept.
Attempt history
Recent submissions
Before you submit, decide what a strong answer should make obvious to the reviewer.
No attempts yet.