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-key

Mistral AI Free Plan: what is free and how to get a key

  1. 1Guess

    You send a request with "max_tokens": 3. The model wants to write a longer answer. What is the finish_reason?
  2. 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/tokens and /explain/context-window show it step by step.

  3. 3Code

    Cap the answer with max_tokens

    1 / 2
    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"}]
      }'
    

    Read the program. What will it print?

  4. 4Code

    Read the usage and estimate the cost

    1 / 2
    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)
    }
    

    Read the program. What will it print?

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

  6. 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)
    }
    
    The program exits with an error before any answer. What is wrong?
  7. 7Say it back

  8. 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

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

Never miss new offers and news

New tools, credits, and AI news are added regularly. Pick how you want to hear about them.

Telegram channel

Join @aifree_dev and get new free AI offers and news right in your Telegram feed.

Browser notifications

Turn on push notifications and get an alert on this device whenever something new is posted. No account needed.

Email newsletter

A weekly digest of new, changed and expiring free AI offers. Double opt-in, one-click unsubscribe. See the latest issue.

Unsubscribe anytime. Privacy

Frequently asked questions

What is aifree.dev?

aifree.dev helps everyone access AI through a curated directory of free AI tools, API credits, free tiers, and startup programs for coding, image, voice, video, and students - verified regularly.

How are offers presented?

Each offer includes its access details, free models when available, and expiration information when provided. Limited-time deals stay visible so they are easy to compare.

Do education and startup programs need verification?

Yes. Providers usually ask students to verify their status with a school email, student ID, or a program like the GitHub Student Pack, and ask startups to verify company details such as age, funding, or website. Check each offer’s claim page for the exact requirements.

What kinds of free AI offers are listed?

Free tiers and free trials from AI providers, free API credits, startup and student programs, and free tools for coding, image generation, voice, and video.

How can I suggest a tool or report a broken link?

Use the submit form: paste the offer page URL and a short note. A person checks every submission before anything is listed. Broken links and changed terms go through the same form.

Know a good one?

Tell us about an AI tool worth knowing. Found a broken link? We want to hear that too.

Submit an offer