Token Counting, Context Trimming, Cost Estimation & Temperature Tuning with tiktoken
Beginner · 35 minutes · 100 points
In this foundational lab you will learn how Large Language Model (LLM) APIs actually charge you and how to stay within context limits. Using the tiktoken library you will count prompt tokens, write a function that trims a chat history to fit inside a fixed context window, calculate the estimated USD cost per request, and finally explore how temperature and top_p affect model outputs by scripting comparison runs against a local Ollama endpoint (mocked with a stub server so no GPU is required).
What you’ll learn
- Use tiktoken to count tokens in a prompt and a multi-turn chat history
- Implement a sliding-window trim function that removes oldest messages to stay under a token budget
- Estimate the USD cost of a request given a per-token price and validate the formula
- Write a comparison script that calls an LLM endpoint with different temperature and top_p values and records the outputs
How this lab works
- Start the lab: One click starts a container on your computer with a real terminal: nothing to install by hand, nothing to clean up.
- Work through 4 tasks: Each task says what to build or fix. You do it yourself, in a real terminal, with hints when you get stuck.
- Check your work: Check my work runs each task’s checks in your container and says what passed and what to fix.
- Finish and keep going: 100 points, your progress saved, and the next lab to try.
What it runs on
- Runs: A container on your computer, with a real terminal
- Image: python:3.12-slim
What you need
- A free LearnXops account
- The LearnXops desktop app for macOS, Windows or Linux
- Docker Desktop installed and running
Topics: tiktoken, tokens, context-window, cost-estimation, ollama, temperature, top_p, llm, python, prompt-engineering
Create a free account to start this lab.