---
title: "Count tokens, cap the answer and estimate the cost"
slug: "tokens-and-cost"
description: "Read the usage a response reports, cap the answer with max_tokens, estimate the cost and keep a long prompt inside the context window."
published: "2026-12-03"
updated: "2026-12-03"
canonical: "https://aifree.dev/courses/learn-llm/tokens-and-cost"
---

# Count tokens, cap the answer and estimate the cost

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.

```sh
export LLM_BASE_URL=https://api.mistral.ai/v1
export LLM_MODEL=mistral-large-4
export LLM_API_KEY=your-key
```

[Mistral AI Free Plan: what is free and how to get a key](https://aifree.dev/offer/mistral-ai-free-plan)

## Predict

You send a request with "max_tokens": 3. The model wants to write a longer answer. What is the finish_reason?

- stop
- length
- error

Answer: length — The model hit the limit you set, so the answer is cut and the server says so with length.

You will see the cut answer and its usage next.

## 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/tokens` and `/explain/context-window` show it step by step.

## Cap the answer with max_tokens

```sh
curl -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"}]
  }'
```

Output:

```
{
  "id": "chatcmpl-mock-0001",
  "object": "chat.completion",
  "created": 1796256000,
  "model": "mock-chat-1",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello! How can"
      },
      "finish_reason": "length"
    }
  ],
  "usage": {
    "prompt_tokens": 1,
    "completion_tokens": 3,
    "total_tokens": 4
  }
}
```

_Simulated response (local mock server), 2026-12-03._

The answer is cut after three tokens, `finish_reason` is `length` and `usage` counts what was used. This is the simulated output.

## Read the usage and estimate the cost

```go
package 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)
}
```

Output:

```
prompt tokens: 6
completion tokens: 6
cost: $0.000005
```

_Simulated response (local mock server), 2026-12-03._

The prices are examples, not any provider's. Read the real ones on the provider's pricing page. Cost is input tokens times the input price plus output tokens times the output price.

## 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_tokens` so a runaway answer cannot eat your budget. The calculator at `/tools/rate-limit-calculator` shows what a limit allows.

## Fix it

```go
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)
}
```

The program exits with an error before any answer. What is wrong?

- The prompt is longer than the context window
- max_tokens is missing
- The free tier is out of requests

Answer: The prompt is longer than the context window — The history alone is far over the limit, so the server rejects the request with a 400.

Error message:

```
request failed: 400 Bad Request
```

Fixed:

```go
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?"
	words := strings.Fields(prompt)
	if len(words) > 100 {
		words = words[len(words)-100:]
	}
	prompt = strings.Join(words, " ")

	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)
}
```

Output:

```
The capital of France is Paris.
```

_Simulated response (local mock server), 2026-12-03._

## Say it back

In your own words: what does a request cost, and what are two ways to keep it from growing?

Our sentence: It costs the prompt tokens times the input price plus the answer tokens times the output price. I keep it small by trimming the history I send and by setting max_tokens so the answer has a ceiling. Both also keep me inside the context window and the free tier limits.

## Mission (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.

```sh
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.
