Count tokens, cap the answer and estimate the cost
Learn LLMs · Beginner · 14 min · After Call a chat completion API with curl and Go
How do you know how many tokens a request uses, and how do you keep the cost and the answer length in check?
Run it against a real free API
The outputs in this lesson are simulated by a local mock server. To get real answers, create a free key at Mistral AI Free Plan and set these variables. Never put the key in your code.
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key1Guess
2Read
What a token is
Tokens are the pieces a model reads and writes. Providers bill by them, and limits count them, for your prompt and for the reply. This lesson's mock counts one token per word, so numbers are easy to check. Real tokenizers split text into word pieces, so a word can be several tokens, and other languages cost more. The Explain lessons
/explain/tokensand/explain/context-windowshow it step by step.3Code
Cap the answer with max_tokens
1 / 2curl -s "$LLM_BASE_URL/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $LLM_API_KEY" \ -d '{ "model": "'"$LLM_MODEL"'", "max_tokens": 3, "messages": [{"role": "user", "content": "Hello"}] }'Read the program. What will it print?
4Code
Read the usage and estimate the cost
1 / 2package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" ) // example prices in USD per 1M tokens: read yours on the provider's pricing page const ( inputPerMillion = 0.20 outputPerMillion = 0.60 ) func main() { payload, _ := json.Marshal(map[string]any{ "model": os.Getenv("LLM_MODEL"), "messages": []map[string]string{{"role": "user", "content": "What is the capital of France?"}}, }) req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY")) res, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer res.Body.Close() var out struct { Usage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` } `json:"usage"` } json.NewDecoder(res.Body).Decode(&out) cost := float64(out.Usage.PromptTokens)*inputPerMillion/1e6 + float64(out.Usage.CompletionTokens)*outputPerMillion/1e6 fmt.Println("prompt tokens:", out.Usage.PromptTokens) fmt.Println("completion tokens:", out.Usage.CompletionTokens) fmt.Printf("cost: $%.6f\n", cost) }Read the program. What will it print?
5Read
Window and limits
A model has a context window: the prompt and the answer together must fit in it. Over the window, the request fails. Free tiers add limits per minute and per day, in requests and in tokens, so a long prompt uses your allowance faster. Keep prompts short: send only the history you need, and set
max_tokensso a runaway answer cannot eat your budget. The calculator at/tools/rate-limit-calculatorshows what a limit allows.6Fix
package main import ( "bytes" "encoding/json" "fmt" "net/http" "os" "strings" ) func main() { history := strings.Repeat("The meeting notes continue. ", 100) prompt := history + "What is the capital of France?" payload, _ := json.Marshal(map[string]any{ "model": os.Getenv("LLM_MODEL"), "messages": []map[string]string{{"role": "user", "content": prompt}}, }) req, _ := http.NewRequest("POST", os.Getenv("LLM_BASE_URL")+"/chat/completions", bytes.NewReader(payload)) req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+os.Getenv("LLM_API_KEY")) res, err := http.DefaultClient.Do(req) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } defer res.Body.Close() if res.StatusCode != http.StatusOK { fmt.Fprintln(os.Stderr, "request failed:", res.Status) os.Exit(1) } var out struct { Choices []struct { Message struct { Content string `json:"content"` } `json:"message"` } `json:"choices"` } json.NewDecoder(res.Body).Decode(&out) fmt.Println(out.Choices[0].Message.Content) }7Say it back
8Mission · 10 min
Use your free key from the offer at the top. Send the usage program to it, look up the real prices on the provider page and put them in the constants. A real tokenizer will count more tokens than words, so compare its numbers with the simulated ones.
export LLM_BASE_URL=<base URL from the offer page> export LLM_MODEL=<model id from the offer page> export LLM_API_KEY=<your key> go run main.go
Common questions
- How many tokens is a word?
- In English a word is often one to two tokens, and a token is roughly four characters. Code, numbers and other languages usually use more tokens per word. The exact count depends on the model's tokenizer, so read the usage field of a response instead of guessing. The mock in this lesson counts one token per word to keep the numbers simple.
- What does max_tokens limit?
- It caps the length of the answer, not the prompt. When the model reaches the cap it stops and the finish reason is length, so the text may end mid-sentence. Newer APIs may call the field max_completion_tokens. Set it so a long answer cannot cost more than you planned, and check the finish reason before you show the text.
- What is the context window?
- It is the most tokens a model can handle in one request, counting your prompt and its answer together. A prompt over the window is rejected, or an answer is cut short. A bigger window does not mean you should fill it, because you pay for every token and long prompts are slower, so send only what the answer needs.
Sources
- https://platform.openai.com/docs/api-reference/chat/create (read 2026-12-03)
- https://docs.mistral.ai/deployment/ai-studio/tier (read 2026-12-03)
- https://pkg.go.dev/strings (read 2026-12-03)
Simulated responses from a local mock server, not from a real model. Run with local mock server (scripts/course-llm-mock.ts), go1.27.4 darwin/arm64, curl on 2026-12-03
Published Dec 3, 2026 · Updated Dec 3, 2026