Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
03 Dec 2026 · 14 min read ·Article 102 / 208
Go

LLM API Anatomy: Tokens, Context Window, Temperature, Sampling

A deep dive into LLM API mechanics for Go developers: how tokenization works, context window management, temperature vs top-p sampling, JSON mode, and their practical implications for production Golang apps.

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

In Article 01 we established that an LLM is “just an API call.” Now we go one layer down: how the LLM actually works behind that endpoint — because this understanding is what changes how we design, test, and cost-optimize our apps. Mastering LLM API anatomy token context window golang is the difference between an integration that merely works and one that is genuinely production-grade.


02.01 Tokenizer: How the LLM Reads Text

Everything you send to an LLM is first split into tokens by a tokenizer. You don’t need to implement it, but understanding its behavior saves you from surprise bills and truncated responses. The snippet below shows tokenization examples and two ways to count tokens from Go.

go
 1// Tokenization examples (vary by model):
 2// "Hello world"  → [15496, 995]                 (2 tokens)
 3// "santekno.com" → [82, 50, 29211, 78, 13, 785] (6 tokens!)
 4// "Rp 500,000"   → [49, 79, 220, 2636, 13, 931] (6 tokens)
 5
 6// Quick estimate BEFORE sending a request:
 7func estimateTokens(text string) int {
 8    words := strings.Fields(text)
 9    return int(float64(len(words)) * 1.3) // ~1.3 tokens per word
10}
11
12// Exact count via tiktoken-go (OpenAI):
13import "github.com/pkoukk/tiktoken-go"
14
15func countTokensExact(text, model string) (int, error) {
16    enc, err := tiktoken.EncodingForModel(model)
17    if err != nil {
18        return 0, err
19    }
20    return len(enc.Encode(text, nil, nil)), nil
21}

Four facts worth internalizing: code costs more than prose (lots of symbols), Indonesian costs more than English (non-ASCII characters), whitespace has its own token, and numbers are sometimes split per digit. Use estimateTokens for a quick guard rail and tiktoken-go when you need precise numbers for cost control.


02.02 Input vs Output Tokens: The Pricing Asymmetry

Many engineers assume all tokens cost the same — an expensive mistake. The comparison below shows why output is far pricier and how that shapes prompt design.

text
1OFTEN IGNORED: output tokens cost 2-4x more than input.
2
3gpt-4o-mini:  input $0.00015/1K  ·  output $0.00060/1K  ← 4x!
4Why: input is processed in parallel on the GPU; output is generated one token at a time (sequential).
5
6Cost of one product description:
7  input 350 tok × $0.00015 + output 150 tok × $0.00060 = ~$0.00014 ≈ Rp 2.3
8  10,000 products → ~Rp 23,000 (very affordable)

The design implication is clear: injecting long context on the input side is relatively cheap, while asking for long output is expensive. So cap output length to what you need and shift the “load” to the input where possible.


02.03 Context Window Management

Input and output must fit together inside the context window; for long conversations, storing the entire history is a recipe for overflow. The utility below tracks usage and trims history with a sliding-window pattern.

go
 1type ContextTracker struct {
 2    maxTokens, used int
 3}
 4
 5func (t *ContextTracker) CanFit(tokens int) bool { return t.used+tokens < t.maxTokens }
 6func (t *ContextTracker) Add(tokens int)          { t.used += tokens }
 7
 8// Sliding window: keep only the last N messages that fit.
 9func trimConversationHistory(messages []Message, maxTokens int) []Message {
10    total := 0
11    for i := len(messages) - 1; i >= 0; i-- {
12        total += estimateTokens(messages[i].Content) + 5 // per-message overhead
13        if total > maxTokens {
14            return messages[i+1:]
15        }
16    }
17    return messages
18}

Two strategies to keep for chatbots: sliding window (drop the oldest messages) for the common case, and summarization (condense old messages into one short message) when early context still matters. Both prevent the “context length exceeded” error that tends to strike right when a conversation gets interesting.


02.04 Messages Array: Multi-turn Conversation

A point that surprises newcomers: an LLM has no memory between requests at all. Every turn, you must resend the entire history. The example below shows the append pattern and session storage in Redis.

go
 1// Every turn: APPEND the assistant reply + the new user message — don't replace.
 2messages = append(messages,
 3    Message{Role: "assistant", Content: "Could you share your order number?"},
 4    Message{Role: "user", Content: "My order number is ORD-001"},
 5)
 6
 7// Session-based storage (Redis, 30-min TTL for idle sessions):
 8type ConversationSession struct {
 9    ID        string
10    Messages  []Message
11    UpdatedAt time.Time
12}
13
14func (s *ChatService) GetOrCreateSession(ctx context.Context, id string) (*ConversationSession, error) {
15    data, err := s.redis.Get(ctx, "chat:session:"+id).Bytes()
16    if err == redis.Nil {
17        return &ConversationSession{ID: id}, nil
18    }
19    if err != nil {
20        return nil, err
21    }
22    var sess ConversationSession
23    return &sess, json.Unmarshal(data, &sess)
24}

The core of this pattern: conversation state lives on our side (Redis), not in the LLM. Storing sessions with a TTL keeps memory cost bounded while delivering an “AI that remembers” experience without a complex stateful server.


02.05 Temperature: The Math Behind Creativity

Temperature isn’t an abstract “creative/not” knob — it literally reshapes the probability distribution of the next token. The illustration below shows its effect on a concrete example.

text
1After "These running shoes are very...", the model has a distribution:
2  comfortable 45% · light 30% · durable 15% · expensive 5% · other 5%
3
4temperature = 0.0 (argmax) → always "comfortable", 100% deterministic
5temperature = 0.5 (sharp)  → "comfortable"/"light", slight variation
6temperature = 1.0 (default)→ original distribution kept
7temperature = 2.0 (flat)   → nearly uniform, often incoherent
8
9Practical: 0.0 extraction/JSON · 0.3 technical explanation · 0.7 description/CS · 1.0 creative

Now “0.7 for product descriptions” is no longer a mantra you memorize but a decision you understand: you’re choosing how sharply the probability distribution is shaped. For machine-parseable output, stay at 0.0.


02.06 Top-P and Top-K: Other Sampling Parameters

Beyond temperature, there are two other sampling levers that are occasionally useful. The snippet below explains top-p (nucleus sampling) and top-k with usage recommendations.

go
 1// Top-P (nucleus): sample from tokens whose cumulative probability >= P.
 2// top_p = 0.9 → only tokens covering 90% of probability; automatically drops "crazy" ones.
 3// OpenAI recommendation: use temperature OR top_p, not both.
 4response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
 5    Model:       openai.F(openai.ChatModelGPT4oMini),
 6    Temperature: openai.F(0.7),
 7    Messages:    openai.F(messages),
 8})
 9
10// Top-K: sample from the top K tokens. OpenAI doesn't expose it; Claude does:
11anthropic.MessageNewParams{ TopK: anthropic.F(40) }

For Santekno Shop, the practical advice is simple: just use temperature. Top-p and top-k are advanced tuning that rarely make a meaningful difference for our copywriting and customer-service use cases.


02.07 Frequency Penalty and Presence Penalty

These two penalties reduce repetition and encourage topic variety. The snippet below shows how to use them and — more importantly — when to avoid them.

go
1// FrequencyPenalty: lower the probability of tokens that appear OFTEN (reduce repetition).
2// PresencePenalty:  lower the probability of tokens that have appeared AT ALL (push new topics).
3response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
4    Model:            openai.F(openai.ChatModelGPT4oMini),
5    FrequencyPenalty: openai.F(0.3),
6    PresencePenalty:  openai.F(0.1),
7    Messages:         openai.F(messages),
8})

Use penalties for product descriptions (avoid repeated words) or brainstorming (encourage diversity). Don’t use them for JSON output, data extraction, or code generation — a penalty can break JSON structure or alter syntax that must stay precise.


02.08 Stop Sequences: Precise Output Control

Sometimes you want the LLM to stop at a specific point, not when it “feels done.” Stop sequences give you that control, as in this example generating a list of exactly 5 items.

go
1// The LLM stops generating when it hits any of these strings.
2response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
3    Model: openai.F(openai.ChatModelGPT4oMini),
4    Stop:  openai.F([]string{"6.", "---"}),
5    Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
6        openai.UserMessage("List 5 key features of a running shoe:\n1."),
7    }),
8})
9// Stops before "6." → exactly 5 items.

Handy stop sequences: "\n\n" to stop after one paragraph, "###" after one Markdown section, and "```" to bound code generation. This is a firmer length-control tool than relying on MaxTokens alone.


02.09 Logprobs: Measuring LLM Confidence

Every generated token carries a log-probability we can read as “how confident” the model is. It’s a valuable signal for detecting possible hallucinations, as the snippet below shows.

go
 1response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
 2    Model:       openai.F(openai.ChatModelGPT4oMini),
 3    Logprobs:    openai.F(true),
 4    TopLogprobs: openai.F(int64(3)),
 5    Messages:    openai.F(messages),
 6})
 7
 8for _, choice := range response.Choices {
 9    if choice.Logprobs == nil {
10        continue
11    }
12    for _, tl := range choice.Logprobs.Content {
13        if prob := math.Exp(tl.Logprob); prob < 0.5 {
14            log.Debug("low confidence token", zap.String("token", tl.Token), zap.Float64("prob", prob))
15        }
16    }
17}

You won’t need this on day one of Santekno Shop, but keep it in mind: logprobs are the foundation of the quality scoring and hallucination detection we build in Topic 9 (LLMOps). Low confidence on a factual token is a red flag worth logging.


02.10 FinishReason: Why the LLM Stopped

finish_reason is one small field that explains a lot. Ignoring it lets truncated or filtered output slip through unhandled. The switch below handles every case.

go
1switch response.Choices[0].FinishReason {
2case "stop": // finished naturally — complete output ✅
3case "length": // truncated by max_tokens ⚠️ → raise max_tokens / shorten prompt
4    log.Warn("LLM response truncated")
5case "content_filter": // blocked by content filter 🚫 → modify prompt
6    return "", fmt.Errorf("content filtered by provider")
7case "tool_calls": // LLM wants to call a tool (function calling — Topic 8)
8    handleToolCall(response.Choices[0].Message.ToolCalls)
9}

Treat finish_reason as a mandatory part of every response handler: length calls for a retry with a higher ceiling, content_filter calls for a prompt fix, and tool_calls is the doorway to the agentic workflows in Topic 8.


02.11 Seed: More Reproducible Output

The LLM’s non-determinism complicates testing and debugging. The seed parameter helps make output more consistent across calls, as below.

go
1seed := int64(42)
2resp1, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
3    Model: openai.F(openai.ChatModelGPT4oMini), Seed: openai.F(seed), Messages: openai.F(messages),
4})
5resp2, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
6    Model: openai.F(openai.ChatModelGPT4oMini), Seed: openai.F(seed), Messages: openai.F(messages),
7})
8// resp1 ≈ resp2 when system_fingerprint matches.

Remember: seed makes output more reproducible, not 100% identical. For LLM unit tests, combine seed + low temperature, but still use semantic assertions (not exact match) — a principle we deepen in section 02.18.


02.12 n: Multiple Completions at Once

Sometimes you want several alternative answers in one call — for example three copy options for an admin to pick. The n parameter does this, with a cost consequence to be aware of.

go
1response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
2    Model: openai.F(openai.ChatModelGPT4oMini),
3    N:     openai.F(int64(3)), // 3 different descriptions
4    Messages: openai.F(messages),
5})
6for i, choice := range response.Choices {
7    fmt.Printf("Version %d: %s\n\n", i+1, choice.Message.Content)
8}

n=3 fits A/B testing copy or offering an admin several choices, but remember you pay for all three outputs. Use it only when variety is genuinely valuable, not as a default habit.


02.13 JSON Mode: Structured Output

For features like smart search, we need output we can Unmarshal directly, not prose. JSON Mode forces the LLM to produce valid JSON, as in this product-info extraction example.

go
 1type ProductInfo struct {
 2    Name     string   `json:"name"`
 3    Category string   `json:"category"`
 4    Features []string `json:"features"`
 5}
 6
 7response, _ := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
 8    Model: openai.F(openai.ChatModelGPT4oMini),
 9    ResponseFormat: openai.F[openai.ChatCompletionNewParamsResponseFormatUnion](
10        openai.ResponseFormatJSONObjectParam{Type: "json_object"},
11    ),
12    Temperature: openai.F(0.0), // deterministic for parsing
13    Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
14        openai.SystemMessage("You must respond with valid JSON only."),
15        openai.UserMessage("Extract name, category, features from the product description."),
16    }),
17})
18
19var info ProductInfo
20if err := json.Unmarshal([]byte(response.Choices[0].Message.Content), &info); err != nil {
21    return nil, fmt.Errorf("parse LLM JSON: %w", err)
22}

Non-negotiable rule: always validate the parsed result, even with JSON Mode on — check empty fields and mismatched types. JSON Mode guarantees syntactically valid JSON, not semantically correct data.


02.14 Structured Output: A Guaranteed Schema

JSON Mode guarantees valid JSON but not that the fields you need are present. Schema-based Structured Output closes that gap, as below.

go
 1schema := openai.ResponseFormatJSONSchemaJSONSchemaParam{
 2    Name: "product_info",
 3    Schema: map[string]interface{}{
 4        "type": "object",
 5        "properties": map[string]interface{}{
 6            "name":     map[string]interface{}{"type": "string"},
 7            "category": map[string]interface{}{"type": "string"},
 8            "features": map[string]interface{}{"type": "array", "items": map[string]interface{}{"type": "string"}},
 9        },
10        "required": []string{"name", "category", "features"},
11    },
12    Strict: openai.Bool(true), // output is GUARANTEED to match the schema
13}

With Strict: true, output is guaranteed to follow the schema, so you can drop excessive defensive parsing. This is the option we choose for the smart-search endpoint in Article 20 to keep its contract solid.


02.15 Caching: Cut Cost with Prefix Caching

OpenAI automatically caches identical input prefixes and gives a discount — but only if you order your messages correctly. The comparison below shows the cache-friendly pattern versus the one that isn’t.

go
 1// GOOD — cache-friendly: STATIC system prompt up front.
 2messages := []Message{
 3    {Role: "system", Content: LONG_STATIC_SYSTEM_PROMPT}, // cached
 4    {Role: "user", Content: dynamicUserInput},            // varies
 5}
 6
 7// BAD — a dynamic system prompt breaks the cache:
 8messages := []Message{
 9    {Role: "system", Content: fmt.Sprintf("Today is %s, user %s...", today, userID)},
10    {Role: "user", Content: userInput},
11}

The principle: put the static part in front, the dynamic part at the back. For Santekno Shop, store the customer-service system prompt as a constant and inject order data via the user message — the 50% discount on cached tokens directly lowers the bill.


02.16 Batch API: Bulk Processing at 50% Off

For non-realtime work like generating descriptions for 1,000 products, the Batch API offers a 50% discount with a trade-off of up to 24-hour processing. The skeleton below sketches the flow.

go
 1// Flow: build a JSONL file of all requests → upload → poll status → download results.
 2func generateDescriptionsBatch(ctx context.Context, products []*Product) error {
 3    var lines []string
 4    for _, p := range products {
 5        req := buildDescriptionRequest(p)
 6        lines = append(lines, fmt.Sprintf(
 7            `{"custom_id":"%s","method":"POST","url":"/v1/chat/completions","body":%s}`,
 8            p.ID, mustMarshal(req)))
 9    }
10    // upload file → submit batch → poll every 5 min → download results → update DB
11    return nil
12}

The Batch API is ideal for background jobs: half the price, and since an admin isn’t waiting in real time, 24-hour latency is a non-issue. For real-time features like the chatbot, stick to ordinary synchronous calls.


02.17 Rate Limits: Living Within the Quota

Before worrying about rate limits, it helps to measure the real need. The calculation below shows Santekno Shop’s current traffic is well under the limit, and how to handle 429 as you scale.

text
1OpenAI Tier 1: 500 RPM · 200K TPM · 10,000 RPD
2
3Santekno Shop estimate:
4  product desc ~5 RPM · smart search ~50 RPM · chatbot ~30 RPM = ~85 RPM << 500 → SAFE
5
6Retry for HTTP 429 (exponential backoff): 0s → 1s → 2s → 4s → 8s
7  Read x-ratelimit-reset-requests & x-ratelimit-remaining-requests to decide.

The takeaway: rate limits are not a problem at our current scale; what matters is correct exponential backoff for 429 and reading the rate-limit headers. As traffic grows, options are raising the spend tier, queueing requests, or caching answers for repeated queries.


02.18 Measuring LLM Output Quality

Because output is non-deterministic, testing an LLM differs from testing a regular function — asserting an exact string is guaranteed to be flaky. The strategies below test the properties of the output, not its literal text.

go
 1// 1. Semantic assertion — check meaning, not the exact string.
 2func assertContainsSentiment(t *testing.T, text string) {
 3    for _, w := range []string{"comfortable", "great", "quality", "superior"} {
 4        if strings.Contains(strings.ToLower(text), w) {
 5            return
 6        }
 7    }
 8    t.Errorf("expected positive sentiment, got: %s", text)
 9}
10
11// 2. Structure validation — output valid against a schema.
12// 3. Length constraint — assert.LessOrEqual(t, len(strings.Fields(resp)), maxWords)
13// 4. Golden samples — 20 (input, acceptable_output) pairs, alert if < 90% pass.
14// 5. LLM-as-judge — another model scores the output (Topic 9).

Take one guiding principle: test structure and meaning, not literal text. Combining semantic assertions with golden samples gives a regression safety net without breaking your tests every time the model phrases things slightly differently.


02.19 Best Practice: The Parameter Matrix

Having dissected each parameter one by one, the matrix below distills them into a ready-to-use cheat sheet per Santekno Shop use case.

text
 1USE CASE             Temp  MaxToken  Top-P  Stop     n
 2Product description  0.7   200       1.0    -        1
 3JSON extraction      0.0   300       1.0    -        1
 4Customer support     0.5   400       0.9    -        1
 5Search understanding 0.0   200       1.0    -        1
 6Brainstorming        1.0   500       1.0    -        3
 7Code generation      0.2   2000      1.0    "```"    1
 8Classification       0.0   20        1.0    "\n"     1
 9
10General rules: always set MaxTokens · Temperature 0 for JSON · Stop for strict length · n>1 only for variety

Keep this matrix next to your LLM code; it turns “which parameters are right?” into a one-line lookup. The wrong default combination is the hidden cause of inconsistent output in production.


02.20 Summary: The LLM Parameters You Must Understand

After this article, the technical details of the LLM API are yours:

Tokens are subwords, not characters/words — Indonesian is pricier, and output costs 4x more than input. Always estimate and monitor.

Context window caps total tokens per request; for chat, use a sliding window or summarization to avoid overflow.

Temperature, top-p, penalties, stop, seed, n are levers you now understand mechanically, not just by memorization. JSON Mode / Structured Output handle data extraction, with validation still mandatory.

FinishReason is crucial for debugging, and rate limits are easy to manage at Santekno Shop’s scale with exponential backoff.

In the next article, we move from theory to security: production-safe API key & secret management — environment separation, rotation, and usage budgets.

Related Articles

💬 Comments